#!/usr/bin/perl

$DEBUG = 0;
%MSG = () ;

usage() unless( @ARGV );

for $file ( @ARGV )
{
	print "parsing $file ...\n" if $DEBUG ;

#	open(FH, "<:utf8", $file );
	open(FH, "< $file" );
	my $content = join( '', <FH> ) ;
	close(FH);

	while( $content =~ /(<Message.+?<\/Message>)/sg ) 
	{
		my $msg = $1 ;
		my $datetime ;

		if( $msg =~ /DateTime="([\d\w-:\.]+)"/ ) {
			$datetime = $1 ;
		} else {
			print "Error parsing DateTime in [$msg]\n";
		}

		print "[$msg]\n" . "="x80 . "\n" if $DEBUG ;

		$MSG{$datetime}{'msg'} = $msg ;
		$MSG{$datetime}{'file'} = $file ;
		
	}
}

my @order = sort keys %MSG ;

$lastid = 0 ;
$lastfile = 0 ;
$newid = 0;
$newmsg = "" ;
for( @order ) {
	$msg = $MSG{$_}{'msg'};
	$file = $MSG{$_}{'file'};

	if( $msg =~ /SessionID="(\d+)">/ ) {
		$sessionid = $1 ;
	} else {
		print "[1;33mError parsing SessionID in [$msg][m\n";
	}

	if( ($sessionid != $lastid) || ($file ne $lastfile) ) {
		$newid++ ;
	}

	$msg =~ s!SessionID="$sessionid"!SessionID="$newid"! ;
	$lastid = $sessionid ;
	$lastfile = $file ;

	$newmsg .= "$msg\r\n" ;

	print "[$_] : $sessionid ($file)\n" if $DEBUG ;
}

print "<?xml version=\"1.0\"?>\r\n";
print "<?xml-stylesheet type='text/xsl' href='MessageLog.xsl'?>\r\n";
print "<Log FirstSessionID=\"1\" LastSessionID=\"$newid\">";
print $newmsg ;
print "</Log>";

sub usage
{
	print "Usage: $0 file1 file2 file3 ... > newfile\n";

	exit(-1);
}

