#! /usr/bin/perl
#
# This script was written and placed into the public domain by 
# Joerg Reuter <jreuter@yaina.de>. No guarantee, warranty or liability
# whatsoever. Even no support. Use at your own risk.
#

use strict;

use Image::ExifTool;
use Date::Parse;
use POSIX;

my %conf={};
my %comment={};

sub waypoint {
	my $filename=$_[0];
	my $path=$conf{"imagedir"}."/".$filename;
	my $exif=new Image::ExifTool;
	return if (!$exif->ExtractInfo($path));
	return if (!($exif->GetValue("GPSVersionID", "Raw")));
	my $lat=$exif->GetValue("GPSLatitude", "ValueConv");
	my $lon=$exif->GetValue("GPSLongitude", "ValueConv");
	return if (!$lat || !$lon);
	my $ele=$exif->GetValue("GPSAltitude", "ValueConv");
	my $date=$exif->GetValue("DateTimeOriginal", "ValueConv");

	if ($date) {
		$date =~ s/:/-/;
		$date =~ s/:/-/;
		$date =~ s/ /T/;
		$date .= "Z";
	}

	my $comment=$comment{$filename};
	utf8::encode($comment);

	print '<wpt lat="'.$lat.'" lon="'.$lon.'">';
	print '<ele>'.$ele.'</ele>' if ($ele);
	print '<time>'.$date.'</time>' if ($date);
	print '<name>'.$filename.'</name>';
	print '<cmt>'.$comment.'</cmt>' if ($comment);
	print '<desc>&lt;img src="'.$conf{"thumburi"}.'/'.$filename.'"/&gt;</desc>';
	print '<link href="'.$conf{"imageuri"}.'/'.$filename.'"><type>image/jpeg</type></link>';
	print "</wpt>\n";
}

my $folder=$ARGV[0];
my $fname=$ARGV[0];
if ($fname eq "") {
        print "usage: exif2gpx configfile\n";
        exit(1);
}

open(fp, "< ",$ARGV[0]);
while(<fp>) {
	chomp;
	my ($key, @value)=split /\s*=\s*/;
	$conf{$key}=join("=", @value);
}
close(fp);


open(fp, "<", $conf{"imagedir"}."/comments.properties");
while (<fp>) {
	my ($key,@cmt)=split /=/;
	$comment{$key}=join("=", @cmt);
}
close(fp);

print '<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Yaina.DE" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
<metadata>
	<name>'.$conf{"name"}.'</name>
	<desc>'.$conf{"description"}.'</desc>
	<author>'.$conf{"author"}.'</author>
</metadata>
';

my $imgfile="";
opendir(dir,$conf{"imagedir"});
while(($imgfile=readdir(dir))) {
	next if ($imgfile !~ /\.jpg$/);
	waypoint($imgfile);
}
closedir(dir);

print "</gpx>\n";
