#!/store/bin/perl
#
# Genererer program-rådata utfra HTP-filer

($felt, $test) = $ARGV[0] =~ m/(.+)=(.*)/;
(@dirs) = $ARGV[1];

for $dir (@dirs) {
    chdir $dir || die "Unable to find $dir";

    for $file (<*.htp>) {
#	print "$file\n";
	%info = parse_htp($file);
	&chech_info(%info);
	if ($info{$felt} eq $test) {
	    $url = "$dir/$file";
	    $url =~ s/\.htp$/.html/;
	    $hendelse{"$info{dato}\t$info{tid}\t$url"} = $info{'tittel'};
	}
    }
}

print "<SET tittel=\"Program $test\">\n";
print "<SET type=\"program\">\n";
print "<BLOCK artikkel>\n";
print "<DL compact=\"compact\">\n";

$sistedato = "";
for $key (sort keys %hendelse) {
    ($dato, $tid, $file) = split(/\t/, $key);

    if ($dato != $test && $sistedato ne $dato) {
	print "<DT><STRONG>$dato</STRONG></DT>\n";
	$sistedato = $dato;
    }
    print "<DT>$tid<DD><A HREF=\"$file\">$hendelse{$key}</A>\n";
}
print "</DL>\n</BLOCK>\n";

sub chech_info {
    my(%info) = @_;
    warn "Bad or missing '<SET dato=\"\">'"
	if (! ($info{'dato'} =~ m/^\d\d\d\d-\d\d-\d\d$/) );
}

sub parse_htp {
    my($filename) = @_;

    my(%info);

    open(HTP, "<$filename") || die "Unable to open $filename for reading";
    while (<HTP>) {
	($key, $val) = m/<set (.*)=\"(.*)\">/i;
	$info{$key} = $val if ($key);
    }
    close HTP;
    return %info;
}
