#!/usr/bin/env perl

use File::Path;
use XML::Twig;

my $f = $ARGV[0];
if (-e $f) {
    my $abs_path = Cwd::abs_path($f);
    do_parallels_exist($abs_path);
} else {
    die "$f doesn't exist\n";
}

sub do_parallels_exist {
    my ($xslfile) = @_;
    
    my $document = XML::Twig->new;
    if ($document->safe_parsefile($xslfile)) {
        my $root = $document->root;
        my $parallel_texts_elt = $root->first_child('xsl:variable[@name="parallel_texts"]');
        if ($parallel_texts_elt && $parallel_texts_elt->{'att'}{'select'} eq "'1'") { 
            if (change_para_doc($root)) {
                open(FH, ">:encoding(utf8)", $xslfile) or die "Cannot open $xslfile $!";
                $document->set_pretty_print('indented');$document->print(\*FH);
            }
        }
    }
    return 0;
}

sub change_para_doc {
    my ($root) = @_;
    
    my @langs = ("dan", "eng", "fin", "fkv", "ger", "isl", "kal", "nno", "nob", "sma", "sme", "smj", "swe");

    print ".";
    for my $lang (@langs) {
        my $key = 'xsl:variable[@name="para_' . $lang . '"]';
        my $para_elt = $root->first_child($key);
        my $para_doc = $para_elt->{'att'}{'select'};
        if ($para_doc ne "''") {
            
            my $after = lc($para_doc);
            $after =~ s/^'-+/'/;
            if ($after ne $para_doc) {
                print "\nBefore $para_doc … ";
                print "after $after\n";
                $para_elt->{'att'}{'select'} = $after;
                print "after ", $para_elt->{'att'}{'select'}, "\n";
                return 1;
            }
            
        }
    }
    return 0;
}
