#!/usr/bin/perl -w
use CGI;

$query = new CGI;

$val = $query->param('val');
$remotehost = $query->remote_host();

$epoch = time() ;
( $sec  , $min  , $hour ,
  $mday , $mon  , $year ,
  $wday , $yday , $isdst  ) = localtime(time) ;

$cyear = $year + 1900 ;
$cmon = $mon + 1 ;

open ( HALOG , ">>/cgihomedir/log/keypad.log" ) || die ( "Cannot Open Log" ) ;
print HALOG "$mday/$cmon/$cyear:$hour:$min:$sec - Received $val from $remotehost \n" ;
close ( HALOG ) ;


open ( HAJOURNAL , ">>/cgihomedir/log/journal.log" ) || die ( "Cannot Open Log" ) ;
print HAJOURNAL "$epoch" . "_" . "$val" . "_ \n" ;


# Each array is _ delim like this <epochtime>_<character entered>
@fifth  = split(/_/, `tail -1 /cgihomedir/log/journal.log`) ;
@forth  = split(/_/,`tail -2 /cgihomedir/log/journal.log | head -1`) ;
@third  = split(/_/,`tail -3 /cgihomedir/log/journal.log | head -1`) ;
@second = split(/_/,`tail -4 /cgihomedir/log/journal.log | head -1`) ;
@first  = split(/_/,`tail -5 /cgihomedir/log/journal.log | head -1`) ;

# If less key press is the hash(go) key and it look less than 10 secs
# to enter the nums then print the combo out to the log
if (( $fifth[1] eq 'H' ) && ( $fifth[0] - $first[0] < 10 )) {
    $combo="$first[1]$second[1]$third[1]$forth[1]" ;
    print HAJOURNAL "Code entered: $combo \n";

    # Write last code out to lastcode.log file
    open ( LASTCODE , ">/cgihomedir/log/lastcode.log" ) || die ( "Cannot Open " ) ;
    print LASTCODE "$combo \n" ;
    close ( LASTCODE ) ;

    }

close ( HAJOURNAL ) ;