#!/usr/bin/perl

my @mappings=qw(bt nw lac cellid number contact);
my %map; my %mapfile; my %max;
my $out;

&main;

sub usage
{
	print "Usage:\n";
	print "toxml.pl PERSON DEFAULT_NETWORK\n";
	exit 0;
}

sub read_mapping($)
{
	my $m=shift;
	my %map;
	my $max=0;
	open(IN, "<${m}.map");
	while(<IN>) {
		chop;
		s///;
		(my $name, my $mapped)=split;
		$map{$name}=$mapped;
		$max=$mapped if ($mapped>$max);
	}
	close(IN);
	open(my $fh, ">>${m}.map") || die "cannot open ${m}.map for writing";
	return ($fh, \%map, $max);
}
		
sub add_mapping($$)
{
	my $map=shift;
	my $name=shift;
	$name=~s/^\s*//;
	$name=~s/\s*$//;
	if ($map eq "number") {
		$name=substr($name, -8);
	}
	unless ( defined($map{$map}{$name}) ) {
		my $max=$max{$map}++;
		$map{$map}{$name}=$max;
		print { $mapfile{$map} } "$name\t$max\n";
	}
	return $map{$map}{$name};
}

my $indent; my $leaf;

sub begin_document
{
	print $out "<?xml version='1.0' encoding='iso-8859-1'?>\n";
	print $out "<!DOCTYPE events SYSTEM 'log.dtd'>\n";
	print $out "<events>";
	$indent=2;
}

sub end_document 
{
	print $out "\n</events>\n";
}

sub begin_element($)
{
	$leaf=0;
	my $e=shift;
	print $out "\n", " " x $indent, "<$e>";
	$indent+=2;
}

sub characters($)
{
	$leaf=1;
	print $out shift;
}

sub end_element($)
{
	my $e=shift;
	$indent-=2;
	if ($leaf) {
		print $out "</$e>";
	} else {
		print $out "\n", " " x $indent, "</$e>";
	}
	$leaf=0;
}

sub begin_event($$)
{
	my $dt=shift;
	begin_element("event");
	begin_element("datetime");
	characters($dt);
	end_element("datetime");
	begin_element(shift);
}
sub end_event($)
{
	end_element(shift);
	end_element("event");
}

sub leaf($$)
{
	my $e=shift;
	begin_element($e);
	my $c=shift;
	$c=~s/^\s*//;
	$c=~s/\s*$//;
	characters($c);
	end_element($e);
}

sub empty($)
{
	$e=shift;
	print $out "\n", " " x $indent, "<$e />";
}

sub main {
	if ($#ARGV<0) { usage(); }

	my $DEFAULT_NW=$ARGV[1];
	my $PERSON=$ARGV[0];

	my %started;
	foreach my $m (@mappings) {
		(my $mapfile, my $map, my $max)=read_mapping($m);
		$map{$m}=$map;
		$mapfile{$m}=$mapfile;
		$max{$m}=$max;
	}

	open $out, ">context-$PERSON.xml" || die "cannot open context-$PERSON.xml for writing";

	my @files=<log*.txt>;
	my @files=sort @files;
	begin_document;
	foreach $file (@files) {
		my $last_dt;
		open(IN, "<$file");
		while (<IN>) {
			chop;
			s///;
			$_.="  ";
			my $start; my $stop;
			$start=$stop=0;
			if (/STARTING/) {
				$start=1;
				s/ STARTING:/: /;
			} 
			elsif (/STOPPING/) {
				$stop=1;
				s/ STOPPING/: s/;
			}
			/^([^ ]+) ([^:]+): (.*)/;
			(my $dt, my $var, my $val)=($1, $2, $3);
			$last_dt=$dt;
			if ($var=~/area, cell/) {
				begin_event($dt, "location");
				if ($stop) {
					empty("stop");
					$started{"location"}=0;
				} else {
					if ($start) {
						empty("start");
						$started{"location"}=1;
					}
					if ($val =~ /^[^,]*,[^,]*$/) {
						$val.=", " . $DEFAULT_NW;
					}
						
					(my $lac, my $cell, $nw)=split(/, */, $val);
					begin_element("location.value");
					if ($cell==0 && $lac==0) {
						empty("no_coverage");
					} else {
						leaf("location.network", add_mapping("nw", $nw));
						leaf("location.lac", add_mapping("lac", $lac));
						leaf("location.cellid", add_mapping("cellid", $cell));
					}
					end_element("location.value");
				}
				end_event("location");
			} elsif ($var=~/profile/) {
				begin_event($dt, "profile");
				if ($stop) {
					empty("stop");
					$started{"profile"}=0;
				} else {
					if ($start) {
						empty("start");
						$started{"profile"}=1;
					}
					$val=~s/([0-9]).*/$1/;
					begin_element("profile.value");
					leaf("profile.id", $val);
					end_element("profile.value");
				}
				end_event("profile");
			} elsif ($var=~/bluetooth/) {
				#begin_event($dt, "bluetooth");
				#end_event("bluetooth");
			}
		}
		foreach my $st (keys %started) {
			if ($started{$st}) {
				begin_event($last_dt, $st);
				empty("stop");
				end_event($st);
				$started{$st}=0;
			}
		}
	}
	end_document;
	close($out);

	open $out, ">comm-$PERSON.xml" || die "cannot open comm-$PERSON.xml for writing";

	my @files=<comm*.txt>;
	my @files=sort @files;
	my %comm;
	foreach $file (@files) {
		open(IN, "<$file");
		while (<IN>) {
			chop;
			s///;
			s/EVENT ID/EVENTID/;
			/EVENTID: ([0-9]+)/;
			my $id=$1;
			/^([0-9]+)T/;
			my $t=$1;
			next unless( defined($id) );
			$id=$t . " " . $id;
			$comm{$id}=$_;
		}
	}
	begin_document;
	my $prev_id=-1;
	my @comm_fields=qw(EVENTID CONTACT DESCRIPTION DIRECTION DURATION NUMBER STATUS SUBJECT REMOTE);
	foreach my $id (sort keys %comm) {
		$_=$comm{$id};
		/^([^ ]+) (.*)/;
		(my $dt, my $vars)=($1, $2);
		my %vars;
		for (my $i=0; $i<=$#comm_fields; $i++) {
			my $f=$comm_fields[$i];
			my $nextf=$comm_fields[$i+1];
			my $val;
			if ( defined($nextf) ) {
				$vars=~/\Q$f\E: (.*) \Q$nextf\E:/;
				$val=$1;
				$vars{$f}=$val;
			} else {
				$vars=~/\Q$f\E: (.*)/;
				$val=$1;
				$vars{$f}=$val;
			}
		}
		next if ( $vars{"NUMBER"} eq "16507" );
		my $type;
		if ($vars{"DESCRIPTION"} eq "Voice call") {
			$type="comm.call";
		} elsif ($vars{"DESCRIPTION"} eq "Short message") {
			$type="comm.sms";
		} else {
			$prev_id=$id;
			next;
		}
		if ($id>$prev_id+1) {
			if ($prev_id!=-1) {
				begin_event($last_dt, "communication");
				empty("stop");
				end_event("communication");
			}
			begin_event($dt, "communication");
			empty("start");
		} else {
			begin_event($dt, "communication");
		}
		$prev_id=$id;
		empty($type);
		if ($vars{"DIRECTION"} eq "Outgoing") {
			empty("comm.outgoing");
		} else {
			empty("comm.incoming");
		}
		leaf("comm.duration", $vars{"DURATION"});
		leaf("comm.number", add_mapping("number", $vars{"NUMBER"}));

		if (! ($vars{"REMOTE"} eq "") ) {
			leaf("comm.contact_name", add_mapping("contact", $vars{"REMOTE"}));
		}
		end_event("communication");
		$last_dt=$dt;
	}
	begin_event($last_dt, "communication");
	empty("stop");
	end_event("communication");
	end_document;

	close($out);
}
