#============================================================================================
# 	SCRIPT		:	ExifToFile.pl
#	AUTHOR		:	M.P.J. Jansen
#	DATE		:	15-06-2013
#
#	BASED UPON	:	Original script 			: 	http://blog.justagirl.us/category/exiftool/
#					ExifTool by Phil Harvey 	:	http://owl.phy.queensu.ca/~phil/exiftool/
#
#	DESCRIPTION	:	Add EXIF information to pictures as custom labels
#					Put pictures at default output location
#					Write debug output to file
#					Create overview list to file.
#	
#	LABELS		:	Contrast						C		x9(1)	-3 ~ +3
#					Saturation						S		x9(1)	-3 ~ +3
#					Flash Exposure Compensation		FEC		x9(1)	-3 ~ +3
#					WhiteBalance in Kelvin			99999K	9(5)	5000K
#
#	VERSION		:	0.8 		
#
#============================================================================================
#	Assumptions
#
# 	1. Copy pictures manually from SD-card to harddisk.
#   2. Default picture location is C:\Users\<username>\Pictures\<current year>\<yyyymmdd subject>\ORG
#	3. This script will add EXIF data as label to pictures and copy the result to output directory
#   4. Default output location is C:\Users\<username>\Pictures\<current year>\<yyyymmdd subject>\EXIF
#
#============================================================================================
#
#	
#	VERSION HISTORY
#	VERSION		DATE			COMMENTS
#	0.5			15-06-2013		Changed script to default drive and directory locations
#	0.6			15-06-2013		Assumptions added
#	0.7			15-06-2013		Debug logging to logfile, list of data to listfile
#	0.8			07-07-2013		Active Daylight written to tags
#
#============================================================================================
#!/usr/bin/perl -w

use Time::localtime;
use File::Copy;
use Image::ExifTool;						#use ExifTool - 
require 'Image/ExifTool/Shift.pl';			#camera set to UTC0; will shift [-]10 for Hawaii

#open file for logging-to-file purposes
open (MYFILE, '>>ExifLog.txt');
open (LISTFILE, '>>Listfile.txt');
my $listheader = "Fname, Exposuretime, FNumber, ISO, FocalLength, WhiteBalance, ActiveD_Lighting, PictureControlName, Contrast, Saturation, fm, fcm, fec ". "\n";
print LISTFILE $listheader;

#Username
my $UsrNme = 'Martin';

#Calculate current year
my $curyr = localtime->year() + 1900;
print MYFILE "curyr = ".$curyr."\n";

#set subdir-volumename - this is where photos with new EXIF info are backupped/written to
my $baktag = 'EXIF';
my $orgtag = 'ORG';

#set directory pictures
my $cidir = 'C:\Users\Martin\Pictures';	
print MYFILE "cidir = ".$cidir."\n";

#define major directory for current year - current picture (cpdir).
my $cydir = "$cidir/$curyr";
#eg $cydir = 'C:\Users\Martin\Pictures\2013';

#current subdirectory
#=================================
# Enter below: required subdirectory of $cydir to be processed.
#=================================
my $csubdir= '20130707 Tuin';

my $cpdir = "$cydir/$csubdir";
print MYFILE "cpdir = ".$cpdir."\n";

#set photo pattern-type - only look for photo's with this pattern
my $pat = 'jpg';	
print MYFILE "pat=".$pat."\n";

#set extensiontype
my $ext = '.' . $pat;
print MYFILE "ext = ".$ext."\n";

my $imgdir= "$cpdir/$orgtag";
#my $imgdir = 'C:\Users\Martin\Pictures\2013\<csubdir>\ORG';
print MYFILE "imgdir = ".$imgdir."\n";

my $bdrv="$cpdir/$baktag";
#eg $bdrv = 'C:\Users\Martin\Pictures\2013\<csubdir>\EXIF';
print MYFILE "bdrv = ".$bdrv."\n";

opendir($dh, $imgdir) or die "Couldn't open $imgdir : $!";
# fill an array of all image files in the current directory
# note case-insensitive pattern match (/i)
@imgfiles = grep(/$pat/i, readdir($dh));
closedir($dh);

# process all the image files in our array
foreach $imgfile(@imgfiles) {

	print MYFILE "\n\n\n";

	$exifTool = new Image::ExifTool;
	# sort by groups in family 2, and extract unknown tags
	$exifTool->Options(Unknown => 1);		
	
	# extract meta information from the image;
	# note use of full path in filename
	$exifTool->ExtractInfo("$imgdir/$imgfile");

	# get date and time in image
	$exifdto = $exifTool->GetValue('DateTimeOriginal');
	print MYFILE "DateTimeOriginal = ".$exifdto."\n";
	
	$exiffname = $exifTool->GetValue('FileName');
	print MYFILE "FileName = ".$exiffname."\n";
	
	$exifContrast = $exifTool->GetValue('Contrast');
	print MYFILE "Contrast = ".$exifContrast."\n";

	#Get requirede specific NIKON D7000 Exif Values on Flash and Picture Control settings
	$exifExposureTime = $exifTool->GetValue('ExposureTime');
	print MYFILE "ExposureTime=".$exifExposureTime ."\n";
			
	$exifFNumber = $exifTool->GetValue('FNumber');
	print MYFILE "FNumber=".$exifFNumber ."\n";
		
	$exifISO = $exifTool->GetValue('ISO');
	print MYFILE "ISO=".$exifISO ."\n";
	
	$exifFocalLength = $exifTool->GetValue('FocalLength');
	print MYFILE "FocalLength=".$exifFocalLength ."\n";

	$exifWhiteBalance = $exifTool->GetValue('WhiteBalance');
	print MYFILE "WhiteBalance=".$exifWhiteBalance ."\n";

	$exifActiveD_Lighting = $exifTool->GetValue('ActiveD-Lighting');
	print MYFILE "ActiveD_Lighting=".$exifActiveD_Lighting ."\n";

	#Get ActiveD_Lighting
	if ($exifActiveD_Lighting =~ /Off/) {
		#Geen ADL toegepast in foto
		#ADL = 0 : ADL0
		$adl='ADL0';
		}
		else {
			if ($exifActiveD_Lighting =~ /Low/) {
				$adl='ADL1';
				}
				else {
					if ($exifActiveD_Lighting =~ /Normal/) {
						$adl='ADL2';
						}
						else {
							if ($exifActiveD_Lighting =~ /Extra/) {
								$adl='ADL4';
								}
								else {
								if ($exifActiveD_Lighting =~ /High/) {
									$adl='ADL3';
									}
									else {
									if ($exifActiveD_Lighting =~ /Auto/) {
										$adl='ADLA';
										}
									}
									
								}
						}
				}
		}

	print MYFILE "ADL IPTC keyword =".$adl."\n";
	$exifTool->SetNewValue('IPTC:Keywords' => [$adl], 'AddValue' => 1);
	
	$exifPictureControlName = $exifTool->GetValue('PictureControlName');		
	print MYFILE "PictureControlName=".$exifPictureControlName ."\n";		

	$exifContrast = $exifTool->GetValue('Contrast (1)');		
	print MYFILE "Contrast=".$exifContrast ."\n";		

	$exifSaturation = $exifTool->GetValue('Saturation (1)');				
	print MYFILE "Saturation=".$exifSaturation ."\n";					

	#Get WhiteBalance in Kelvin
	$wb=$exifWhiteBalance;
	print MYFILE "WhiteBalance =".$wb."\n";
	
	#Put Whitebalance Kelvin value in keyword.
	$exifTool->SetNewValue('IPTC:Keywords' => [$wb], 'AddValue' => 1);	
	
	#Get ContrastAdjustments
	if ($exifContrast =~ /Normal/) {
		#Geen compensatie toegepast in foto
		#Contrast = 0 : C0
		$cc='C0';
		}
		else {
		#Contrast is wel aangepast in foto
		$cc='C'.$exifContrast;
		}
	print MYFILE "contrastIPTC keyword =".$cc."\n";
	$exifTool->SetNewValue('IPTC:Keywords' => [$cc], 'AddValue' => 1);

	#Get SaturationAdjustments
	if ($exifSaturation =~ /Normal/) {
		#Geen compensatie toegepast in foto
		#Contrast = 0 : C0
		$sa='S0';
		}
		else {
		#Contrast is wel aangepast in foto
		$sa='S'.$exifSaturation;
		}
	print MYFILE "SaturationIPTC keyword =".$sa."\n";
	$exifTool->SetNewValue('IPTC:Keywords' => [$sa], 'AddValue' => 1);
	
	# get flash compensation tags (FlashMode)
	$fm = $exifTool->GetValue('FlashMode');
	print MYFILE "FlashMode=".$fm."\n";
	
	# if the flash fired... get flash exposure compensation
	if($fm =~ /^Fired/) {
		print MYFILE "Flash Fired!\n";
		# get the mode
		$fcm = $exifTool->GetValue('FlashCommanderMode');
		print MYFILE "FlashCommanderMode=".$fcm."\n";
		
		# if mode is Off
		if($fcm eq 'Off') {
			$tag = 'ExternalFlashExposureComp';
		}
		# else mode is On
		else {
			$tag = 'FlashGroupACompensation';
			$flashgrp = ': Group A';
			}
			$val = $exifTool->GetValue($tag);
			print MYFILE "FlashGroupACompensation=".$val."\n";
			
			# want decimal values here, convert fractions
			$num = Image::ExifTool::Exif::ConvertFraction($val);
			print MYFILE "num=".$num."\n";
			
			# round to one decimal place (i.e., '0.666666666666667' after fraction conversion)
			#$val = sprintf('%.1g', $num);
			$val = sprintf('%.2g', $num);
			print MYFILE "val rounded=".$val."\n";
			
			$fec = 'FEC: ' . $val;
			print MYFILE "FEC=".$fec."\n";				
			
			#tn = tagname
			$tn = 'Flash Exposure Compensation';
			# $flashgrp is always defined after it's first occurrence in the loop...
		if(defined($flashgrp)) {
		$tn .= $flashgrp;
		# ...so undefine the bleeping thing if you found it earlier
		undef $flashgrp;
		}
		# add flash compensation keywords without replacing existing keywords in the file
#		$exifTool->SetNewValue('IPTC:Keywords' => [$tn, $fec], 'AddValue' => 1);
		$exifTool->SetNewValue('IPTC:Keywords' => [$fec], 'AddValue' => 1);		
	}
	
	# get exposure compensation tags
	$sm = $exifTool->GetValue('ShootingMode');
	if($sm =~ /Exposure Bracketing/) {
		$tn = 'Bracketing Exposure Compensation';
		$val = $exifTool->GetValue('ExposureBracketValue');
		$num = Image::ExifTool::Exif::ConvertFraction($val);
		$valEBV = sprintf('%.1g', $num);
		$ebv = 'EBV: ' . $valEBV;
		$val = $exifTool->GetValue('ExposureCompensation');
		$num = Image::ExifTool::Exif::ConvertFraction($val);
		$valEC = sprintf('%.1g', $num);
		# calculate 'actual' exposure compensation
		$num = $valEC - $valEBV;
		$val = sprintf('%.1g', $num);
		$ec = 'EC: ' . $val;
		# add exposure compensation keywords without replacing existing keywords in the file
		$exifTool->SetNewValue('IPTC:Keywords' => [$tn, $ebv, $ec], 'AddValue' => 1);
	}

	# get values for use in new filename
	# set desired date format
	$exifTool->Options('DateFormat' => '%Y%m%d_%H%M%S');
	# to *use* a shifted date/time value the shift must be applied to the unformatted (ValueConv) value
	# then you must do the DateFormat conversion yourself
	$dto = $exifTool->GetValue('DateTimeOriginal', 'ValueConv');
	$dto = $exifTool->ConvertDateTime($dto);
	# Nikon records up to 6 frames per second; get 'SubSecTimeOriginal' to avoid filename collision
	$ssto = $exifTool->GetValue('SubSecTimeOriginal');
	
	print MYFILE "ssto=".$ssto."\n";
	
	# get shutter count
	# $sc = $exifTool->GetValue('ShutterCount');
	# pad the shutter count number
	# $sc = '_' . sprintf('%07d', $sc);
	
	# concatenate all the pieces of the new filename
	# i.e., 20100126-08040600_0020213.nef
	#$nn = $dto . $ssto . $sc . $exiffname . $ext;
	$nn = $dto . $ssto . '_' .$exiffname ;
	print MYFILE "new name=".$nn."\n";
	print MYFILE "imgfile=".$imgfile."\n";
	print MYFILE "imgdir=".$imgdir."\n";
	print MYFILE "imgdir/imgfile="."$imgdir/$imgfile"."\n";
	print MYFILE "bdrv/nn="."$bdrv/$nn"."\n";
	
	# add information to source file, writing output to new file
	
	$WriteResult = $exifTool->WriteInfo("$imgdir/$imgfile", "$bdrv/$nn" );
	
	print MYFILE "WriteResult=".$WriteResult."\n";
	if ($WriteResult eq '0') {
		$errorMessage = $exifTool->GetValue('Error');
		print MYFILE "error=".$errorMessage."\n";
	}
	
	$listout = $listout .$exiffname. ",". $exifExposureTime. "," .$exifFNumber. "," .$exifISO. "," . $exifFocalLength . "," ;
	$listout = $listout .$exifWhiteBalance . "," . $exifActiveD_Lighting. ",". $exifPictureControlName. ",". $exifContrast. ",".$exifSaturation. ",".$fm. ",". $fcm. ",". $fec;
	print LISTFILE $listout."\n";
	$listout = "";
	
}
close (MYFILE); 
close (LISTFILE);