#!/usr/bin/perl

# libby.miller@bristol.ac.uk 2003-05-13
# see http://esw.w3.org/topic/OpeningHoursUseCase
# http://lists.w3.org/Archives/Public/www-rdf-calendar/2003Mar/0016.html


## need something like this:
# DTSTART:20030908T190000
# DTEND:20030908T233000
# RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=MO
# but this is wrong - need a timezone thing - how can we get this?
# a mapping from <Country>United Kingdom</Country>?

# sample text from chefmoz
#<ParsedHours>10-23|10-23|10-23|10-23|10-23|10-23|10-23</ParsedHours>

# can start with | or nothing
# can have comma separated pairs within a day
# half hours are rep by .5
# | separates a day
# 24 hour clock
# some don't have any ParsedHours
# ranges are sepaated by -
# midnight is 0

# some oddities e.g
# <ParsedHours>|12-15,18-23.9833333333333|12-15,18-23.9833333333333|12-15,18-23.9833333333333|12-15,18-23.9833333333333|12-15,18-23.9833333333333|12-15,18-23.9833333333333</ParsedHours>

my @days=("MO","TU","WE","TH","FR","SA","SU");

my $file= $ARGV[0];

# arbitrary start date
my $startdate="20030101T";

## because can have different opening hours for each day
## each different timeset becomes another vevent, which 
## perhaps isn't quite right
## where all days are the same could be improved
## could also have a look at skical opening hours

if($file ne ""){

open(IN,"$file");
	while(<IN>){
	my @hrs;

		if($_=~ m/<ParsedHours>\|?(.*)<\/ParsedHours>/){
		@hrs = split /\|/, $1;


### preprocess the hours
## if some are the same, keep them together

		my %hrshash;

			for($k=0;$k<=$#hrs;$k++)
			{
			my $hh=$hrs[$k];
			my $bla=$hrshash{$hh};
			my $tmpday=$days[$k];
				if($bla ne ""){
				$hrshash{$hh}=$bla.",".$tmpday;
				}else{
				$hrshash{$hh}=$tmpday;
#				print "adding " . $hh . " " . $tmpday;
				}
			}

		printOH(\%hrshash);

		}
	}
}

sub printEvent{

my $key=shift;
my $value=shift;
my $st=$key;
my $en=$key;

	$st=~ s/(\d\d?\.?5?)-(\d\d?\.?5?)/$1/;
	$en=~ s/\d\d?\.?5?-(\d\d?\.?5?)/$1/g;

	if($st<10){
	$st="0".$st;
	}
	if($en<10){
	$en="0".$en;
	}

### use only 0000 for midnight. I've used 2359 to avoid confusion
### with the next day

	if($st==24){
	$st="2359";
	}
	if($en==24){
	$en="2359";
	}

	$st=~ s/\.5/30/;
	$en=~ s/\.5/30/;

	if($st=~ m/\d\d\d\d/){
	}else{
		$st=$st."00";
	}
	if($en=~ m/\d\d\d\d/){
	}else{
		$en=$en."00";
	}


#print "s $st e $en\n";

	print "\n";
	print "BEGIN:VEVENT\n";
	print "DTSTART:".$startdate.$st."00\n";
	print "DTEND:".$startdate.$en."00\n";
	print "RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=".$value."\n";
	print "END:VEVENT\n";

}


sub printOH{

my $hashy =shift;

	print "BEGIN:VCALENDAR";

	while(($key,$value) = each %{$hashy}){
#	print "$key $value\n";

			
		my @difftimes = split /\,/, $key;

		   if($#difftimes==0){
			printEvent($key,$value);

		   }else{
			for($j=0;$j<=$#difftimes;$j++)
			{
			my $da=$difftimes[$j];
			printEvent($da,$value);
			}
		   }

	}
	   print "END:VCALENDAR\n";
	   print "\n";

}

