#!/usr/bin/perl

use CGI ':standard';
use Date::Calc 'Delta_Days', 'Delta_YMD', 'Days_in_Month';
use POSIX 'strftime';

my ($d, $m, $y) = (param('d'), param('m'), param('y'));
my ($td, $tm, $ty) = (localtime)[3,4,5];
$tm++;
$ty+=1900;

unless ($d) {
  ($d, $m, $y) = ($td, $tm, $ty);
}

my $tense;
if ($y < $ty || $y == $ty && $m < $tm || $y == $ty && $m == $tm && $d < $td) {
  $tense = "was";
} elsif ($y > $ty || $y == $ty && $m > $tm || $y == $ty && $m == $tm && $d > $td) {
  $tense = "will be";
} else {
  $tense = "is";
}


my $date = dformat($d, $m, $y);

print header();

print qq{<a href="brains/"><img border=0 src="brains/brains3-crop.jpg" align=left></a>\n};
print "<h1>Age of Iris Dominus Kim</h1>\n";

print "<p>As of <b>$date</b>, Iris $tense ";
my $dd = Delta_Days(2004, 6, 14, $y, $m, $d);
print "$dd ", ($dd == 1 ? "day" : "days"), " old.</p>\n\n";

unless ($tense eq "was") {
  my ($dY, $dM, $dD) = my_Delta_YMD(2004,6,14, $y, $m, $d);
  my $years =  $dY == 1 ? "year"  : "years" ;
  my $months = $dM == 1 ? "month" : "months";
  my $days =   $dD == 1 ? "day"   : "days"  ;
  print "<p>That is $dY $years, $dM $months, and $dD $days.</p>\n";
}

print qq{<form method=POST action="$ENV{SCRIPT_NAME}">
<table>
<tr><td align=center colspan=3><input type=submit value="Calculate her age on this date instead">
<tr><td>Year<td>Month<td>Day
<tr><td><input name=y size=4 maxsize=4 value=$y>
    <td><input name=m size=2 maxsize=2 value=$m>
    <td><input name=d size=2 maxsize=2 value=$d>
</table>

</form>

<h3>Disclaimer</h3>

<p>This application was Derek Chu's idea.</p>
};

exit 0;


sub dformat {
  my ($d, $m, $y) = @_;
  strftime("%A, %e %B %Y", 0, 0, 12, $d, $m-1, $y-1900);
}

sub my_Delta_YMD {
  my ($ay, $am, $ad,
      $by, $bm, $bd) = @_;
  my ($dY, $dM, $dD) = Delta_YMD($ay, $am, $ad, $by, $bm, $bd);
  return ($dY, $dM, $dD) if $dY < 0;
  if ($dD < 0) {
    $dD += Days_in_Month($by, $bm);
    $dM --;
  }
  if ($dM < 0) {
    $dY--;
    $dM += 12;
  }
  ($dY, $dM, $dD);
}
