while (<STDIN>)
{
	$txt .= $_;
}

$| = 1;

$TGTCODE = $ARGV[1];
if ($TGTCODE ne "ES" && $TGTCODE ne "CA")
{
	die "second arg. should be ES or CA\n";
}

open INFILE,$ARGV[0];
while (<INFILE>)
{
	$line++;
	chomp;
	if (m/EN: /) { $EN = $'; $TGT = ""; }
	if (m/$TGTCODE: /) { $TGT = $'; }
	if ($TGT)
	{
		$enSubCnt = 0;
		$tgtSubCnt = 0;
		$tmp = $EN;
		while ($tmp =~ m/\[\[/) { $enSubCnt++; $tmp = $'; }
		$tmp = $TGT;
		while ($tmp =~ m/\[\[/) { $tgtSubCnt++; $tmp = $'; }
		if ($enSubCnt!=$tgtSubCnt) {
			print STDERR "[[...]] mismatch in $ARGV[0]:$line\n";
			print "EN: $EN\nTGT: $TGT\n";
			exit -1;
		}
		$TGTs{$EN} = $TGT;
	}
}

foreach $EN (sort { length($b) <=> length($a) } keys(%TGTs) )
{
	$TGT = $TGTs{$EN};

	$EN =~ s|\(|\\(|g;
	$EN =~ s|\)|\\)|g;
	$EN =~ s/\[\[(.*?)\]\]\d/[[$1]]/gs;
	$TGT =~ s/\[\[(.*?)\]\](\d)/[[$2$1]]$2/gs;
	$EN =~ s/\@/\\@/g;
	$TGT =~ s/\@/\\@/g;
	$EN =~ s/\+/\\+/g;
	$EN =~ s/\?/\\?/g;
	$EN =~ s/\*/\\*/g;
	$EN =~ s|\[|\\[|g;
	$EN =~ s|\]|\\]|g;
	$EN =~ s/\\\[\\\[/(<[^>]+>)/g;
	$EN =~ s/\\\]\\\]/(<[^>]+>)/g;
	$EN =~ s/ /\\s+/g;
	$TGT =~ s/\[\[0/\${1}/g;
	$TGT =~ s/\]\]0/\${2}/g;
	$TGT =~ s/\[\[1/\${3}/g;
	$TGT =~ s/\]\]1/\${4}/g;
	$TGT =~ s/\[\[2/\${5}/g;
	$TGT =~ s/\]\]2/\${6}/g;
	$TGT =~ s/\[\[3/\${7}/g;
	$TGT =~ s/\]\]3/\${8}/g;
	$TGT =~ s/\[\[/\${1}/g;
	$TGT =~ s/\]\]/\${2}/g;
	if ($EN =~ m/LaFarga/g)
	{
		#print "s/$EN/$TGT/gs";
		#exit;
	}
	$EN =~ s|/|\\/|g;
	$TGT =~ s|/|\\/|g;
	print STDERR "EN: $EN\nTGTCODE: $TGT\n";
	print STDERR "REPLACED: ";
	print STDERR eval("\$txt =~ s/$EN/$TGT/gs;")+0;
	print STDERR "\n\n";
}

print $txt;
