#!/usr/bin/perl -s
BEGIN { unshift @INC, "$ENV{'HOME'}/perl",
		      "$ENV{'HOME'}/libp/perl", "$ENV{'HOME'}/lib/perl" }

# ctimecol - convert input columns from time to ctime format
# Steve Kinzler, steve@kinzler.com, Oct 98/Jan 03/Oct 04/Jun 06
# https://kinzler.com/me/home.html#unix

grep($argv{($_ eq 'NF') ? 'NF' : int($_)}++, @ARGV);
@ARGV = ();

$usage = "usage: $0 [ -s | -t ] [ -u ] [ -i | -I ]
	[ -f ] [ -w ] [ column ... ]
	-s	whitespace-separated input columns,
		  space-separated output columns (default)
	-t	tab-separated input and output columns
	-u	output ctime columns with spaces instead of underscores
	-i	output ctime columns in 'YYYY-MM-DD_HH:MM:SS' format
	-I	output ctime columns in 'MM/DD/YYYY_HH:MM:SS' format
	-f	only convert lines that begin with '>>>'
	-w	suppress invalid format warnings
Input columns are numbered as integers from zero, or are NF to indicate
the last column.\n";
die $usage if $h || grep($_ eq '' || $_ < 0, keys %argv);

use Time::CTime;

while (<>) {
	print, next if ! %argv || $f && ! /^>>>/;

	chop;
	@field = ($t) ? split(/\t/) : split;

	foreach $c (keys %argv) {
		$c = $#field if $c eq 'NF';
		! $w && warn("$0: invalid time format in column $c ($_)\n"),
			next unless $field[$c] =~ /^\d+$/;

		$date =  ($i) ? &stdtime($field[$c]) :
			 ($I) ? &ustime( $field[$c]) : ctime($field[$c]);
		$date =~ s/^\s+//; $date =~ s/\s+$//;
		$date =~ s/\s/_/g unless $u;
		$field[$c] = $date . ($ENV{'CTIMECOL_TZ'}
				      ? " $ENV{'CTIMECOL_TZ'}" : '');
	}

	print join(($t) ? "\t" : ' ', @field), "\n";
}

sub stdtime { strftime('%Y-%m-%d %H:%M:%S', localtime($_[0])); }
sub ustime  { strftime('%m/%d/%Y %H:%M:%S', localtime($_[0])); }
