my $IN = shift or die "Syntax : $0 <input sdlxliff file> <output renum-xliff file?>";
my $OUT = shift; unless ($OUT) { $OUT = $IN; $OUT =~ s/\.sdlxliff/\.renum\.xlf/; }

open(IN, $IN) or die "Could not open '$IN': $!";
open (OUT, ">$OUT") or die "Cannot write $OUT: $!"; 

local $/ = '</header>';
$CONTENTS = <IN>; $CONTENTS =~ s!<header(.+)</header>!<header />!s; print OUT $CONTENTS;

$/ = '</trans-unit>';
while (defined ($CONTENTS = <IN>)) {
    $CONTENTS =~ s{<seg-source>(.+?)</seg-source>}{renum($1,'seg-source')}ges;
    $CONTENTS =~ s{<source>(.+?)</source>}{renum($1,'source')}ges;
    $CONTENTS =~ s{<target>(.+?)</target>}{renum($1,'target')}ges;
    
    # Remove segments with only tags -- these ones could be translated automatically
    my $SrcText = $1 if $CONTENTS =~ m{<source(?:.+?)>(.+?)</source>}; $SrcText =~ s/<.+?>//g; 
    unless ($SrcText) { $CONTENTS =~ s{<trans-unit.+?</trans-unit>}{}s; }
    
    print OUT $CONTENTS;
}


close IN; close OUT;


sub renum($) {
    my $txt = shift;
    my ($first) = ($txt =~ m!<(?:g|x) id="(\d+)"!);
    $txt =~ s!<(g|x) id="(\d+)"!"<$1 id=\"" . ($2 - $first) . "\""!ge;
    my $mark = shift || 'seg-source';
    return "\n<$mark renum=\"$first\">$txt</$mark>\n";
}
