#!/usr/local/bin/perl

################################################################
# Author:  I. Dan Melamed, adapted from script by S. Stenchikova
# Computes:     relines 2 input files according to a line map
# Streams: the line map
# Loads:  Both input texts
# N.B.:  output goes to 2 output files, whose names are also params
################################################################
# <align file> contains a line map, as output by GMA, in the format i,j,...k <=> l,m,...n

if($#ARGV<4)
{
    print "usage $0 <line map> <input1> <input2> <output1> <output2> \n";
    exit 0;
}

$lmfile = shift;
open(ALIGN, $lmfile)  || die "\nCouldn't open $lmfile: $!\n";

$in1 = shift;
open(IN1, $in1) || die "\nCouldn't open $in1: $!\n";
$in2 = shift;
open(IN2, $in2) || die "\nCouldn't open $in2: $!\n";
$out1 = shift;
open(OUT1, ">$out1") || die "\nCouldn't open $out1: $!\n";
$out2 = shift;
open(OUT2, ">$out2") || die "\nCouldn't open $out2: $!\n";

# print STDERR "$in1 $in2 $out1 $out2";

while (<IN1>) {
    chomp;
    push(@in1, $_);
};

while (<IN2>) {
    chomp;
    push(@in2, $_);
};

# print "$#in1 $#in2 $in1[5]\n";

while(<ALIGN>)
{
#    print stderr $_;
    chop;
    @align = split '<=>';
    @left  = split ',', $align[0];
    @right = split ',', $align[1];

    @lines = ();
    foreach $li (@left){
	if ($li !~ /omit/) {
	    push(@lines, $in1[$li]);
	};
    }
    print OUT1 join(' ', @lines);
    print OUT1 "\n";

    @lines = ();
    foreach $li (@right){
	if ($li !~ /omit/) {
	    push(@lines, $in2[$li]);
	};
    }
    print OUT2 join(' ', @lines);
    print OUT2 "\n";

}
