#!/usr/bin/perl -w

use strict;
use Getopt::Long;
use utf8;
use Encode;

my $xmllint = "xmllint";
my $xmllint_flag = "--noout";
my $aligned;
my $lang1;
my $lang2;
my $file;

# Assumption: $aligned contains the results of tca2, 
# $lang1 contains the files in lang1 and $lang2 those in lang2

GetOptions (
	    "aligned=s" => \$aligned,
	    "lang1=s" => \$lang1,
	    "lang2=s" => \$lang2,
	   );

if(! -d $aligned || ! -d $lang1 || ! -d $lang2) {
  die "ERROR: Can't open ", Encode::decode_utf8($aligned), Encode::decode_utf8($lang1), Encode::decode_utf8($lang2), "\n";
} else {
  &buildTMX($aligned);
}

sub buildTMX {
  my($path) = @_;
  ## append a trailing / if it's not there
  $path .= '/' if($path !~ /\/$/);
  for $file (glob($path.'*')) {
    ## if the file is a directory
    if( -d $file) {
      next
    } else {
      if($file =~ /\.xml$/) {
	$file =~ s/^.*\/([^\/]+)$/$1/;
	my ($lang1_file, $lang2_file) = ($file =~ m/^(.+\.xml\.sent)_(.+)$/);
	$lang1_file .= '.xml';
	$lang1_file = Encode::decode_utf8($lang1_file);
 	$lang2_file = Encode::decode_utf8($lang2_file);
	$file = Encode::decode_utf8($file);

	print "|=| file $file \n";
	print "|=|=| file1 $lang1_file \n";
	print "|=|=|=| file2 $lang2_file \n\n";

	my $command = "java -Xmx2024m net.sf.saxon.Transform -it main alignedCorpus2tmx.xsl file12=$aligned/$file file1=$lang1/$lang1_file file2=$lang2/$lang2_file lang1=$lang1 lang2=$lang2";
	print STDERR "$0: $command \n\n";
	if (system($command) != 0) { return "errors in $command: $!\n"; }
      }
      else {
	print "::: no xml file \t", Encode::decode_utf8($file),"\n";
      }
    }
  }
}
