#!/bin/bash

#
# igt2cfg : read in IGT-formatted data and output CFG structures that
#           match the source-language patterns
#
# usage: igt2cfg igt-file trans-file output-dir
#
#   where: igt-file   contains the IGT instances
#          trans-file contains just the translation lines from the IGT
#          output-dir is where temporary and output files go
#


if [ $# -ne 3 ]; then
    echo "Usage: `basename $0` igt-file trans-file output-dir" >&2
    exit 1
else
    igtfile="$1"
    transfile="$2"
    outdir="$3"
fi

if [ ! -d "$outdir" ]; then
    mkdir -p "$outdir"
fi

export PATH=./riples:$PATH
export PERLLIB=./riples:$PERLLIB
export PATH=./scripts:$PATH

#### step 1: get the parse tree
run_nlparser.pl "$transfile" "$outdir/a1.nl_parsed"


#### step 3: get a1.res
eng_morph_table="/projects/IGT/fxia/IGT_process/English/eng_morph_table"
head_table="/projects/IGT/fxia/IGT_process/English/head_table"
trans_lexicon="/projects/IGT/fxia/IGT_process/trans_lexicon"

ab600.exec "$igtfile" "$outdir/a1.nl_parsed" "$eng_morph_table" "$head_table" left "$outdir/a1.res" 0 1 1  "$trans_lexicon" > "$outdir/a1.res.log" 2>"$outdir/a1.res.stderr"

#### step 4: get the CFG
PS_to_PS.pl "$outdir/a1.res" "$outdir/a1.CFG" > "$outdir/a1.CFG.stdout" 2>"$outdir/a1.CFG.stderr"

sort -k 2 "$outdir/a1.CFG.syn" > "$outdir/a1.CFG.syn.sorted"


#### step 5: get the morph
## $cmd = "oa600.exec $dir/a1.res $dir/a1.morph > $dir/a1.morph.log 2>$dir/a1.morph.stderr";
## systemx($cmd);

#### step 6: get b1.res
ob600.exec "$outdir/a1.res" "$outdir/b1.res" > "$outdir/b1.res.log"

#### step 7: get b1.CFG
PS_to_PS.pl "$outdir/b1.res" "$outdir/b1.CFG" > "$outdir/b1.CFG.log" 2>&1

sort -k 2 "$outdir/b1.CFG.syn" > "$outdir/b1.CFG.syn.sorted"


####post-production: igt.all construction:

# replace the nontokenized version of the language line in the 
# igt file with the tokenized version
# using the untokenized version leads to a broken igtall file
fix_igtall "$igtfile" "$transfile"

align_align_with_igt "$outdir/a1.res" "$igtfile"
if [ -f "$igtfile.all" ]; then
    align_sent_with_igt "$outdir/a1.nl_parsed" "$igtfile.all"
    align_a1CFG_with_igt "$outdir/a1.CFG" "$igtfile.all"
    align_b1res_with_igt "$outdir/b1.res" "$igtfile.all"
    align_b1cfg_with_igt "$outdir/b1.CFG" "$igtfile.all"
else
    echo "no igt.all found"
fi
