#!/usr/bin/perl -w
# lab #5 solution

#$datafile = '/mnt/homes/CLASSES/CIS2279/LAB05/logger.csv';
$datafile = '/home/mark/Desktop/logger.csv';

if(-r $datafile) {
        open(DF, "<$datafile") || die "cannot open datafile: $!";
        chomp(@datalines = <DF>); # read the entire file to an array
        close(DF);
}else{
        exit;
}

do{
    print "Please enter a julian date (060-069) or 'q' to quit:";
    chomp($ans = <STDIN>);
    if($ans ne 'q') {
        # now search for matching lines in the file data
        $lowwc = 999999;
        foreach $line (@datalines) {
            @ldata = split(/,/, $line); # split the line by comma
            # only process data with the correct julian date and a wind 
            # speed greater than 1mph
            if(($ldata[1] eq $ans) && ($ldata[9] >= 1)) {
                $t = $ldata[5];
                $v = $ldata[9];
                # Calculate the windchill
                $wchill = 35.74 + 0.6215 * $t - 35.75 * $v**0.16 + 
                    0.4275 * $t * $v**.16;
                # save the value if the windchill is lower than any previous low
                if($wchill < $lowwc) {
                    $lowwc = sprintf("%0.2f", $wchill);
                    $lowwc_time = "$ldata[2]:$ldata[3]";
                    $lowwc_date = "julian day $ldata[1] in $ldata[0]";
                }
            }
        }
        $lowwind_cel = ($lowwc - 32)/1.8;
        print "The low windchill for $lowwc_date or $lowwind_cel is $lowwc at $lowwc_time.\n";
    } # end if block
}until($ans eq 'q');

exit;