if (!$ARGV[0]) { die "missing translations filename"; }

open INFILE,$ARGV[0];
while (<INFILE>)
{
	$line++;
	chomp;

	if ($_ =~ m/^\s*$/)
	{
	}
	elsif (m/^=+ OBSOLETE/)
	{
	}
	elsif (m/EN: /) { $EN = $'; $ES = ""; $CA = ""; }
	elsif (m/ES: /) { $ES = $'; }
	elsif (m/CA: /) { $CA = $'; }
	else{
		print STDERR "Error in $ARGV[0]: $line\n";
		print STDERR "  $_\n";
		exit(-1);
	}	
	if ($ES)
	{
		$ESs{$EN} = $ES;
		push(@oldENs,$EN);
	}
	if ($CA)
	{
		$CAs{$EN} = $CA;
		push(@oldENs,$EN);
	}
}
close INFILE;


open OUTFILE,">$ARGV[0]";

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

$txt =~ s/<p>/_BLOCK_/gs;
$txt =~ s/<p .*?>/_BLOCK_/gs;
$txt =~ s/<h\d>/_BLOCK_/gs;
$txt =~ s/<h\d .*?>/_BLOCK_/gs;
$txt =~ s/<div>/_BLOCK_/gs;
$txt =~ s/<div .*?>/_BLOCK_/gs;
$txt =~ s/<li>/_BLOCK_/gs;
$txt =~ s/<li .*?>/_BLOCK_/gs;
$txt =~ s/<img .*?>/_BLOCK_/gs;

$txt =~ s/<!--.*?-->//gs;

$txt =~ s/<head>.*?<\/head>//gs;

$X = 0;

$txt =~ s/<a [^>]*><\/a>//gs;

@blocks = split /_BLOCK_/,$txt;
$line = 1;
foreach $block (@blocks)
{

	if ($block)
	{
		$X = 0;
		while (
		$block =~ s/(<a .*?>(.*?)<\/a>|<b>(.*?)<\/b>|<i>(.*?)<\/i>|<strong>(.*?)<\/strong>|<em>(.*?)<\/em>)/[[$2$3$4$5$6]]$X/s
		)
		{
			$X++;
		}
		if ($X==1)
		{
			$block =~ s/\[\[(.*?)\]\]0/[[$1]]/s;
		}
		$block =~ s/<.*?>//gs;
		$block =~ s/\s+/ /gs;
		$block =~ s/^\s+//g;
		$block =~ s/\s+$//g;
		if ($block && !$done{$block})
		{
			$done{$block} = 1;
			$EN = $block;
			$lines{$EN} = $line;
			print OUTFILE "EN: $EN\n\n";
			$line+=2;
			if ($ESs{$EN})
			{
				print OUTFILE "ES: $ESs{$EN}\n\n";
				$line+=2;
			}
			if ($CAs{$EN})
			{
				print OUTFILE "CA: $CAs{$EN}\n\n";
				$line+=2;
			}
		}
		#for ($i=0;$i<$X;$i++)
		#{
		#	print "$i\[\[:$tagO[$i]\n";
		#	print "$i\]\]:$tagC[$i]\n";
		#}
	}
}

foreach $EN (@oldENs)
{
	if (($ESs{$EN} || $CAs{$EN}) && !$done{$EN})
	{
		print OUTFILE "============ OBSOLETE =============\n\n";
		print OUTFILE "EN: $EN\n\n";

		if ($ESs{$EN})
		{
			print OUTFILE "ES: $ESs{$EN}\n\n";
		}

		if ($CAs{$EN})
		{
			print OUTFILE "CA: $CAs{$EN}\n\n";
		}
	
		$done{$EN} = 1;
	}
}
