#!/usr/bin/perl

# This Perl script converts Nautilus file annotations to embedded
# JPEG image comments.

# This script is in the public domain.  marko.makela (at) iki.fi, Nov 4, 2005.

# treat all errors as fatal

use strict;
use XML::DOM;

my $HOME = $ENV{HOME};

my $uri = $ENV{NAUTILUS_SCRIPT_CURRENT_URI};
#my @uris = split("\n", $ENV{NAUTILUS_SCRIPT_SELECTED_URIS});

$uri =~ s|%|%25|gs;
$uri =~ s|/|%2F|gs;

my $parser = new XML::DOM::Parser;

my $doc = $parser->parsefile("$HOME/.nautilus/metafiles/$uri.xml");
my $files = $doc->getElementsByTagName("file");
my $n = $files->getLength;

open(NOTE, "|jpegcom");

for (my $i = 0; $i < $n; $i++)
{
    my $file = $files->item($i);
    my $note = $file->getAttributeNode("annotation");
    my $name = $file->getAttributeNode("name");

    if ($note && $name) {
	$name = $name->getNodeValue();
	$note = $note->getNodeValue();
	$name =~ s/%([0-9a-fA-F][0-9a-fA-F])/pack("H*",$1)/geos;
	$note =~ s/%([0-9a-fA-F][0-9a-fA-F])/pack("H*",$1)/geos;
	$name =~ s/([\\\"])/\\$1/gos;
	$note =~ s/([\\\"])/\\$1/gos;

	print NOTE "copy \"$name\" \"$name\"\n\"$note\"\n";
    }
}

close(NOTE);

$doc->dispose;
