#!/usr/bin/perl

my @mappings=qw(descr category loc cn mailto);
my %map; my %mapfile; my %max;
my $out;

&main;

sub usage
{
	print "Usage:\n";
	print "cal-anon.pl PERSON CALENDAR_FILE\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;
	if ($map eq "") { return $name; }

	$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};
}

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

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

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

	open $out, ">cal-$PERSON.ics" || die "cannot open cal-$PERSON.ics for writing";

	open IN, "<$CAL_FILE" || die "cannot open $CAL_FILE for reading";

	$linesep="";
	$*=1;
	while(<IN>) {
		s///;
		chop;
		$curr .= $linesep . $_;
		if (/[:;]$/) {
			$linesep="\n";
			next;
		} else {
			$linesep="";
			$_ = $curr;
			$curr="";
		}
		next if (/ORGANIZER.*Unknown/); 
		if (/SUMMARY/ || /DESCRIPTION/) {
			/([^:]+): *(.*)$/;
			$field=$1; $descr=$2;
			print $out $1, ":", add_mapping("descr", $descr);
		} elsif (/CATEGORIES/) {
			/([^:]+): *(.*)$/;
			$field=$1; $cat=$2;
			print $out $1, ":", add_mapping("category", $cat);
		} elsif (/LOCATION/) {
			/([^:]+): *(.*)$/;
			$field=$1; $loc=$2;
			print $out $1, ":", add_mapping("location", $loc);
		} else {
			$sep1="";
			foreach $f1 ( split(/:/) ) {
				$sep2=""; 
				print $out $sep1;
				foreach $f2 ( split(/;/, $f1) ) {
					$sep3="";
					print $out $sep2;
					foreach $f3 ( split/=/, $f2 ) {
						print $out $sep3, add_mapping($anon, $f3);
						$sep3="=";
						$anon="";
						$anon="cn" if ($f3 eq "CN");
					}
					$sep2=";";
				}
				$anon="";
				$anon="mailto" if ($f1 eq "MAILTO");
				$sep1=":";
			}
		}
		print $out "\n";
	}

	close(IN);
	close($out);
}


