use strict;
use Data::Dumper;

my $no_no=0;
my $no_en=0;

my @links;
my $out_file = shift @ARGV;
if (-e $out_file) {
    open (OUT, $out_file);
    while (<OUT>) {
	chomp;
	my ($a,$b) = split;
	my @a = split(/,/, $a);
	foreach my $el (@a) { if ($el > $no_no) { $no_no = $el } }
	my @b = split(/,/, $b);
	foreach my $el (@b) { if ($el > $no_en) { $no_en = $el } }
	push @links, [\@a,\@b];
    }
    close OUT;
    if ($no_no > 0) { $no_no++ }
    if ($no_en > 0) { $no_en++ }
}


my $no_file = shift @ARGV;
my $en_file = shift @ARGV;

my @no = load_file($no_file);
my @en = load_file($en_file);




my $span_no=1;
my $span_en=1;

my $resp="-";


while ($resp ne "quit") {

    system("clear");

#    print "$en[$no_en+$span_en]\n";
#    print "$en[$no_en+$span_en+1]\n";
#    print "$en[$no_en+$span_en+2]\n\n";

#    print "$no[$no_no+$span_no]\n";
#    print "$no[$no_no+$span_no+1]\n";
#    print "$no[$no_no+$span_no+2]\n\n";


    if ($resp eq "") {

	# store link
	my @links_no = $no_no..$no_no+$span_no-1;
	my @links_en = $no_en..$no_en+$span_en-1;
	push @links, [\@links_no, \@links_en];

	$no_no=$no_no + $span_no;
	$span_no=1;
	$no_en=$no_en + $span_en;
	$span_en=1;

    }
    elsif ($resp eq "e") { $span_en++ }
    elsif ($resp eq "n") { $span_no++ }
    elsif ($resp eq "ee") { $span_en-- }
    elsif ($resp eq "en") { $span_no-- }
    elsif ($resp eq "load") {
	@no = load_file($no_file);
	@en = load_file($en_file);
    }
    elsif ($resp eq "ok") {
	open (OUT, ">$out_file");
	foreach my $link (@links) {
	    my $a=$link->[0];
	    my $b=$link->[1];
	    print OUT join(",",@$a), " ", join(",",@$b), "\n";
	}
	die("done ...\n");
    }
    elsif ($resp eq "z") {
	pop @links;
	$no_no--; $no_en--;
	$span_en=1; $span_no=1;
    }

    system("clear");

#    print "$en[$no_en+$span_en]\n";
#    print "$en[$no_en+$span_en+1]\n";
#    print "$en[$no_en+$span_en+2]\n\n";

#    print "$no[$no_no+$span_no]\n";
#    print "$no[$no_no+$span_no+1]\n";
#    print "$no[$no_no+$span_no+2]\n\n";

    print "", join("\n", @no[$no_no..$no_no+$span_no-1]), "\n\n";
    print "", join("\n", @en[$no_en..$no_en+$span_en-1]), "\n\n";

    $resp = <STDIN>;
    chomp $resp;

}



sub load_file {

    my $file = shift;
    my @ar;
    open (IN, $file);
    while (<IN>) { chomp; next unless ($_ =~ m/\S/); push @ar, $_;}
    close IN;
    return @ar;

}
