#!/usr/local/bin/perl
#
#
# This script is intended for use on the output of the simple-form 
# cgi-script http://deneb.npac.syr.edu:3768/cgi-bin/simple-form
# 
# it processes a mail with a list of key-value pairs and
# does something with it.  something must be coded by the users (you)
# guidelines follow--look for comments
# 
#


# Process command line
#
# as usual, if -f switch is not there pipe input from sdtin
# and if -o switch is not there pipe output to stdout
#

$IN = 'STDIN';
$OUT = 'STDOUT';

require "getopts.pl";

&Getopts("f:o:");

$IN = $opt_f if $opt_f;
$opt_f && open($IN,"<$opt_f");
$OUT = $opt_o if $opt_o;
$opt_o && open($OUT,">$opt_o");


#
# read in file and create @mail array
#

$\="\n";
$/="\n\n";
$,=" ";

while (<$IN>){
    chop;
    s/^\n//g;
    $mail[$i] = $_; 
    $i++ if ($_ ne "");
}

# Now $mail[0] has the header info, $mail[1] has the referer info
# (such as the client machine which sent the mail and its IP number)
# and $mail[2] has the key value pairs. Now we build the associative arrays

%Header = &DoHeader($mail[0]);

%Referer = &DoReferer($mail[1]);

%KeyValue = &DoKeyValue($mail[2]);

#
# Now the three associative arrays have been created and you can do whatever
# you like with them! Here I print them out.
#

foreach (keys(%Header)) {
    print $OUT "Key",$_,"Value",$Header{$_};
}

foreach (keys(%Referer)) {
    print $OUT "Key",$_,"Value",$Referer{$_};
}

foreach (keys(%KeyValue)) {
    print $OUT "Key",$_,"Value",$KeyValue{$_};
}

exit (0);

#
# subroutines 
#

sub DoHeader {
    local(%array);
    local($lin)=@_;
    local($key);
    local($value);

    @line = split("\n",$lin);  # create array


    foreach (@line){
	s/(\d*):(\d*):(\d*)/$1;$2;$3/;   # pay attention to the hour field
	if (/\w+:/) {	 
	    ($key,$value) = split(":",$_);
	    $value =~ s/(\d*);(\d*);(\d*)/$1:$2:$3/; # restore the colons 
	    $array{$key} .= $value;
	} else {
	    s/(\d*);(\d*);(\d*)/$1:$2:$3/; # restore the colons
	    s/\s+/ /g;
	    $array{$key} .= $_;
	}
    }
    return %array;
}


sub DoReferer {
    local(%array);
    local($lin)=@_;
    local($key);
    local($value);

    @line = split("\n",$lin);

    foreach (@line){
	next if /===/;                 # ignore lines made up of =
	($key,$value) = split(":",$_);
	$array{$key} = $value;
    }
    return %array;
}


sub DoKeyValue {
    local(%array);
    local($lin)=@_;
    local($key);
    local($value);

    @line = split("\n",$lin);

    foreach (@line){
	next if /^-+$/;          #ignore the lines made up of -----
	if (/\(.+\)/) {
	    s/\((.+)\)/$1\378/;
	    ($key,$value) = split("\378",$_);
	    $key =~ s/\s+//g;	# remove whitespaces in keys
	    $array{$key} .= $value;
	} else {
	    $array{$key} .= " ".$_;
	}
    }
    return %array;
}

