#!/usr/bin/env perl

use utf8;
use 5.008;
use strict;
use warnings;
use autodie;
use List::MoreUtils qw( any all );

#my @parsers = (qw(MATE TURBO MALT MST GOLD));
#my @parsers = (qw(MATE TURBO MALT MST PARSITO GOLD));
my @parsers = (qw(MATE TURBO MALT MST PARSITO));
#my @parsers = (qw(MATE TURBO MST PARSITO GOLD));

my (@ords, @forms, %lems, %tags, %heads, %afuns);
{ foreach my $p (@parsers) { @{$lems{$p}}=(); @{$tags{$p}}=(); @{$heads{$p}}=(); @{$afuns{$p}}=(); } }

my $INPUT_DIR = $ARGV[0];
chomp $INPUT_DIR;
$INPUT_DIR =~ s|(.+)\/$|$1|;

my $dirDH;
#print "Opening directory:\n$INPUT_DIR\n.";
opendir($dirDH, $INPUT_DIR) or die "Error opening directory $INPUT_DIR !\n";

my $parsed_files=-1;
foreach my $INPUT_FILE (sort readdir($dirDH)) {
    next if ($INPUT_FILE =~ /^\.{1,2}$/);
    next if ($INPUT_FILE !~ /.+\.vert$/);
    my $p = $INPUT_FILE;
    $p =~ s/^.*((MATE)|(TURBO)|(MALT)|(MST)|(PARSITO)|(GOLD)).*$/$1/;

    $INPUT_FILE = $INPUT_DIR . '/' . $INPUT_FILE;
    print "$INPUT_FILE\n";
    $parsed_files++; # print "PARSED_FILES: $parsed_files\n";
    open my $INFILE, '<:utf8', $INPUT_FILE or die;

    my $o=0;
    my $lines=0;
    my $last_line='Y?';
    while (<$INFILE>) {
	chomp;
	my $l = $_;
	$lines++;
	if ($l eq '') {
	    $o=0;
	    next if ($last_line eq '');
	    if ($parsed_files < 1) {
		push (@ords,''); push (@forms, ''); }
	    elsif (($ords[$lines-1] ne '')||($forms[$lines-1] ne '')) {
		die "Neshoda na řádku $., parser $p, měla by zde být prázdná řádka!\n"; }
		push (@{$lems{$p}}, '');
		push (@{$tags{$p}}, '');
		push (@{$afuns{$p}}, '');
		push (@{$heads{$p}}, '');
	}
	else {
	    $o++;
	    my ($fo,$le,$tg,$af,$or,$he) = split /\t/,$l;
	    if ((not defined $fo)||(not defined $le)||(not defined $tg)||(not defined $af)||(not defined $or)||(not defined $he)) {
		die "Špatně přečtený řádek $., parser $p:\n\"$l\"\n";}
	    if (($parsed_files > 0)&&($forms[$lines-1] ne $fo)) {
		die "Neshoda forem \"$fo\" a \"$forms[$lines-1]\" na řádku $., parser $p!"; }
	    elsif ($parsed_files < 1) { push (@ords,$or); push (@forms, $fo); }
	    $tg =~ s/\<None\>/X/;
	    push (@{$lems{$p}}, $le);
	    push (@{$tags{$p}}, $tg);
	    push (@{$afuns{$p}}, $af);
	    push (@{$heads{$p}}, $he);
	}
	$last_line = $l;
    }
}

open my $OUT, '>:utf8', './Merged_VertsNnomalt.xvert';

# DEBUG
#print $OUT "\$\#forms == $#forms\n";
#foreach my $i (0 .. $#forms) {
#    if (defined $lems{'MATE'}[$i]) {
#	print $OUT "$i\t$forms[$i]\t$lems{'MATE'}[$i]\n"; }
#}
# DEBUG END
foreach my $i (0 .. $#forms) {
    if ($forms[$i] eq '') { print $OUT "\n"; }
    else {
	print $OUT "$ords[$i]\t$forms[$i]";
	foreach my $pa (@parsers) {
	    if (not defined $lems{$pa}[$i]) { die "lems $pa $i undefined\n"; }
	    if (not defined $heads{$pa}[$i]) { die "heads $pa $i undefined\n"; }
	    if (not defined $afuns{$pa}[$i]) { die "afuns $pa $i undefined\n"; }
	    print $OUT "\t$lems{$pa}[$i]\t$tags{$pa}[$i]\t$heads{$pa}[$i]\t$afuns{$pa}[$i]"; 
	}
	print $OUT "\n";
    }
}
