#
# j6igettime.pl
# get timestamp in *.j6i/j6s/whatever file.
#
# copyright(c) 1996 by Jun-ichiro itojun Itoh.
# all rights reserved.
# freely redistributable.  absolutely no warranty.
#
# Known problems: the script ignores timezone information on j6i/j6s flies.
#
# $Id: j6igettime.pl,v 1.9 1996/09/19 14:38:03 itojun Exp $
#

require 'timelocal.pl';

sub bcd2bin {
	local($value) = @_;

	return (($value & 0xf0) >> 4) * 10 + ($value & 0x0f);
}

sub j6igetrawtime {
	local($fname) = @_;
	local($rawdate);
	local($year, $month, $day, $hour, $min, $sec);

	if (!open(FILE, "< $fname")) {
		return ();
	}
	
	# magic number check
	if (read(FILE, $magic, 5) != 5) {
		return ();
	}
	if (substr($magic, 0, 1) ne "\200" || substr($magic, 2, 3) ne 'DSC') {
		return ();
	}

	# get jpeg start addess
	seek(FILE, 56, 0);
	if (read(FILE, $jpegstart, 4) != 4) {
		return ();
	}
	$jpegstart = unpack('N', $jpegstart);

	# seek to next tuple
	seek(FILE, 2 + unpack('C', substr($magic, 1, 1)), 0);

	# look for date field
	while (1) {
		# to prevent infinite loop
		if ($jpegstart <= tell(FILE)) {
			return ();
		}

		if (read(FILE, $tuplehead, 2) != 2) {
			return ();
		}
		if (unpack('Cx', $tuplehead) eq 0x81) {
			# skip tuple offset, timezone and junk
			seek(FILE, 2, 1);
			last;
		}

		seek(FILE, unpack('xC', $tuplehead), 1);
	}

	if (read(FILE, $rawdate, 6) != 6) {
		return ();
	}
	close(FILE);
	($year, $month, $day, $hour, $min, $sec) = unpack("c6", $rawdate); 
	$year = &bcd2bin($year);
	$month = &bcd2bin($month);
	$day = &bcd2bin($day);
	$hour = &bcd2bin($hour);
	$min = &bcd2bin($min);
	$sec = &bcd2bin($sec);
	return ($year, $month, $day, $hour, $min, $sec);
}

sub j6igettime {
	local($fname) = @_;
	local(@r);

	@r = &j6igetrawtime($fname);
	if (scalar(@r) == 6) {
		return &timelocal($r[5], $r[4], $r[3], $r[2], $r[1] - 1, $r[0]);
	} else {
		return 0;
	}
}

# for test/example...
#require 'ctime.pl';
#print &ctime(&j6igettime('/tmp/r0100001.j6i'));
