#!/usr/bin/perl -w
#
# Convert camera RAW file to HDR image
# Based on dcraw version 8.94 (May 15, 2009)
# Also requires hdrgen and exiftool
#
if ($#ARGV < 0) {
	print "Usage: raw2hdr [hdrgen opts][-h][-w][-C calib][-c cspace] -o output.hdr input1.raw ..\n";
	exit 1;
}
my $td = `mktemp -d /tmp/raw2hdr.XXXXXX`;
chomp $td;
# Calibration factor for our camera:
my $calib_fact = 1;
my $bscale = 1.1;
my @dcraw = qw(dcraw -c -t 0 -W -g 2 0 -T);
my @exiftags = qw( -GPSDateStamp -GPSTimeStamp -GPSLatitude -GPSLatitudeRef
	-GPSLongitude -GPSLongitudeRef -GPSAltitude -GPSAltitudeRef
	-Orientation -ImageOrientation -CameraOrientation
	-FocalLengthIn35mmFormat -UserComment -FocusDistance\>SubjectDistance );
my @hdrgen = "hdrgen -m 400 -e -a -r $td/sqr.rsp";
my $ocs = "sRGB";
my $force_write = 0;
my $outfile;
while ($#ARGV >= 0) {
	if ("$ARGV[0]" eq "-c") {
		shift @ARGV;
		$ocs = $ARGV[0];
	} elsif ("$ARGV[0]" eq "-C") {
		shift @ARGV;
		$calib_fact = $ARGV[0];
	} elsif ("$ARGV[0]" eq "-K") {
		push @hdrgen, @ARGV[0..4];
		shift @ARGV for (1..4);
	} elsif ("$ARGV[0]" eq "-o") {
		shift @ARGV;
		$outfile = $ARGV[0];
		push @hdrgen, "-o $outfile";
	} elsif ("$ARGV[0]" =~ /^-[qmp]$/) {
		push @hdrgen, "$ARGV[0] $ARGV[1]";
		shift @ARGV;
	} elsif ("$ARGV[0]" eq "-m") {
		shift @ARGV;
		push @hdrgen, "-m $ARGV[0]";
	} elsif ("$ARGV[0]" eq "-F") {
		$force_write = ! $force_write;
	} elsif ("$ARGV[0]" =~ /^-[aefgx]$/) {
		push @hdrgen, $ARGV[0];
	} elsif ("$ARGV[0]" =~ /^-[rs]$/) {
		print "hdrgen $ARGV[0] option not supported";
		exit 1;
	} elsif ("$ARGV[0]" =~ /^-[hw]$/) {
		push @dcraw, $ARGV[0];
	} elsif ("$ARGV[0]" eq "-b") {
		shift @ARGV;
		$bscale = $ARGV[0];
	} elsif ("$ARGV[0]" =~ /^-./) {
		print "Unknown option: $ARGV[0]\n";
		exit 1;
	} else {
		last;
	}
	shift @ARGV;
}
if (not $outfile) {
	print "Missing -o output file specification\n";
	exit 1;
}
if ($force_write) {
	push @hdrgen, "-F";
} elsif (-e $outfile) {
	print "$outfile: file exists\n";
	exit 1;
}
if ("$ocs" eq "XYZ") {
	# CIE XYZ
	push @dcraw, "-o 5";
	push @exiftags, "'-PrimaryChromaticities=1.00 0.00 0.00 1.00 0.00 0.00'",
			"'-WhitePoint=.3333 .3333'";
} elsif ("$ocs" eq "AdobeRGB") {
	# Adobe RGB (1998)
	push @dcraw, "-o 2";
	push @exiftags, "'-PrimaryChromaticities=0.64 0.33 0.21 0.71 0.15 0.06'",
			"'-WhitePoint=.3127 .3290'";
} elsif ("$ocs" eq "sRGB") {
	# sRGB is dcraw default and what hdrgen expects on input
	push @dcraw, "-o 1"
} else {
	die "Unsupported output color space";
}
push @hdrgen, "-c $ocs";
push @dcraw, "-b $bscale";
open OUTF, '>', "$td/sqr.rsp";
print OUTF "2 $calib_fact 0 0\n" x 3;
close OUTF;
foreach my $rawfile (@ARGV) {
	$_ = $rawfile;
	s|.*/||g;
	s/\.[^.]*$/.tif/;
	my $tiff = "$td/$_";
	system "@dcraw -v $rawfile > $tiff" and die 'dcraw failed';
	system "exiftool -overwrite_original -TagsFromFile '$rawfile' @exiftags $tiff";
	push @hdrgen, $tiff;
}
print "Executing: @hdrgen\n";
my $res = system "@hdrgen";
system "rm -rf $td";
exit $res;
