#!/usr/bin/perl

# This script takes data generated by PSATool and converts it into a format
# suitable for importing into Adobe Lightroom.  
# This code is Copyright (C) Pablo Averbuj, 2006.

use strict;
use Data::Dumper;
$Data::Dumper::Quotekeys = 0;
$Data::Dumper::Indent = 1;

my $data = {};

while(<STDIN>) {
	chomp; 
	my @fields = split(/;/, $_, 7);
	next unless ($fields[6]);
	$_ = $fields[6];
	tr/"\n\r//d;
	my @tags = split(/;/);
	foreach my $tag (@tags) { 
		next if ($tag =~ /Adobe Atmosphere/);
		my $p = $data;
		foreach my $name (split(/\\/, $tag)) { 
			if (!defined $p->{$name}) { $p->{$name} = {}; } 
			$p = $p->{$name} 
		} 
	}
}

my $s =  Dumper($data);
$s =~ s/^\S+.*$//mg; # Get rid of $VAR line
$s =~ s/\s*=>.*$//mg; # Get rid of hash structure data
$s =~ s/^\s*\}.?\s*$//mg; # Get rid of hash structure data
$s =~ s/^(\s*)'/$1/mg; # Get rid of quotes on keys
$s =~ s/'\s*$//mg; # Get rid of quotes on keys
$s =~ s/\\'/\'/g; # Unescape quotes
while ( $s =~ s/^(\t*) {2}/$1\t/mg ) { } # Transform spaces to tabs
$s =~ s/^\t//mg; # Drop 1 indent level
$s =~ s/^\s*$//mg; # Get rid of space-only lines
$s =~ tr/\n//s; # Collapse empty lines
$s =~ s/^\n+//s; # Get rid of empty lines at the beginning
print $s;

