#!/usr/bin/perl
#
# seconds2text
# perl function
# Convert Seconds to a String like "1 day, 17 hours, 12 minutes, 11 seconds"
#
# Examples:
#  * seconds2text 1  returns "1 second"
#  * seconds2text 2  returns "2 seconds" (automatically sets plural)
#  * seconds2text 3925  returns "1 hour, 5 minutes, 25 seconds"
#  * seconds2text 390370  returns "4 days, 12 hours, 26 minutes, 10 seconds"
#
$AUTHOR = "Mike Arnold <mike at razorsedge dot org>";
$VERSION = "200407060238";
#

# Format the time unit (sets plurality)
# expects: TIME_VALUE UNIT (ie "6" "day")
# returns: formatted OUT
sub mkstring {
  my $TIME_VALUE = $_[0];
  my $UNIT = $_[1];
  if ($TIME_VALUE == 0) { $OUT = ""; }
  elsif ($TIME_VALUE == 1) { $OUT = "1 " . $UNIT . ", "; }
  else { $OUT = $TIME_VALUE . " " . $UNIT . "s, "; }
  return $OUT;
}

sub seconds2text {
  my $sec = $_[0];
  # Convert seconds to week/day/hour/minute
  my $SECOND = $sec%60;
  my $MINUTE = ($sec/60)%60;
  my $HOUR = ($sec/(60*60))%24;
  my $DAY = int($sec/(24*60*60))%7;
  my $WEEK = int($sec/(24*60*60*7));

  # Build the output string
  $STRING = mkstring($WEEK, week);
  $STRING .= mkstring($DAY, day);
  $STRING .= mkstring($HOUR, hour);
  $STRING .= mkstring($MINUTE, minute);
  $STRING .= mkstring($SECOND, second);

  # Remove the trailing comma and space
  chop $STRING;
  chop $STRING;

  # Print it out
  return $STRING;
}

print (seconds2text $ARGV[0] . "\n");

