#!/usr/local/bin/perl -w
#	SETUPPHOTO  OLDDIRECTORYINDEX OLDDIRECTORYIMAGE NEWDIRECTORY
#	Write outline and options file in NEWDIRECTORY given 
#	outline(.txt) and images in OLDDIRECTORYINDEX and OLDDIRECTORYIMAGE respectively
#	OLDDIRECTORYINDEX and OLDDIRECTORYIMAGE can be identical
#
#	use relative: in control1-3
#
$foilsbasicdir = '/home/A7E/gcf/foils3';
#
$today=`date`;
chomp($today);
$today =~ s/\d\d:\d\d:\d\d ... //;      # Today's Date
#
#	Read Alias File of URL's of interest!
&readalias("$foilsbasicdir/wwwalias");
#
#	Open all the critical files
#
$sourceimage= $ARGV[0];
opendir(ORGIMAGE,$sourceimage) || die("\nSorry Could not open ",$sourceimage," \n");
$sourceindex= $ARGV[1];
opendir(ORGINDEX,$sourceindex) || die("\nSorry Could not open ",$sourceindex," \n");
$destination = $ARGV[2];
unless( -e $destination )    {
        mkdir $destination,0755;
}
$write = $destination . '/outline';
open(OUTLINE,'>'.$write) || die("\nSorry Could not open ",$write," \n");
$write = $destination . '/options';
open(OPTIONS,'>'.$write) || die("\nSorry Could not open ",$write," \n");
#
$seporgimagedir = $destination .'/seporgimagedir';
unless( -e $seporgimagedir )	{
	mkdir $seporgimagedir,0755;
}
#
$signature = "$foilsbasicdir/options.signature";
open(SIGNATURE,'<'.$signature) || die("\nSorry Could not open ",$signature," \n");
@signaturedata=<SIGNATURE>;
close(SIGNATURE);
#
#	Set relative pathname between NEWDIRECTORY and OLDDIRECTORY
# $reljump = &jumpfoil($destination.'/',$source);
# $reljump .= '/';
$reljump = '';
#
#	See what files are on original OLDDIRECTORY
#	Identify and convert if necessary original summary(outline) file
$summary='';
$originalindex='';
$ct=0;
while( $name=readdir(ORGINDEX))	{
	next if( $name eq '.' || $name eq '..' );
	next unless $name;
	$lcname = $name;
	$lcname =~ tr/A-Z/a-z/;
	if( ($lcname =~ m%outline%) || ($lcname =~ m%index%) )	{
		$originalindex = $sourceindex . '/' . $name;
		$com = "macconv $sourceindex/$name";
		system($com);
		next;
	}
	if( ($lcname =~ m%abstract%) || ($lcname =~ m%summary%) )	{
		$summary = $sourceindex . '/' . $name;
		$com = "macconv $sourceindex/$name";
		system($com);
		next;
	}
	next unless $name =~ m%^(.*)\.([^\.]*)$%;
	$namemod = $1;
	$tag = $2;
	$tag =~ tr/A-Z/a-z/;
	next unless (($tag eq 'gif') || ($tag eq 'jpg') || ($tag eq 'htm') || ($tag eq 'html') );
	$filename{$namemod} = $sourceindex . '/' . $name;
	$referenced{$namemod}=0;
	$ct++;
}
close(ORGINDEX);
while( $name=readdir(ORGIMAGE))	{
	next if( $name eq '.' || $name eq '..' );
	next unless $name;
	$lcname = $name;
	$lcname =~ tr/A-Z/a-z/;
	if( ($lcname =~ m%outline%) || ($lcname =~ m%index%) )	{
		next if($originalindex);
		$originalindex = $sourceimage . '/' . $name;
		$com = "macconv $sourceimage/$name";
		system($com);
		next;
	}
	if( ($lcname =~ m%abstract%) || ($lcname =~ m%summary%) )	{
		next if($summary);
		$summary = $sourceimage . '/' . $name;
		$com = "macconv $sourceimage/$name";
		system($com);
		next;
	}
	next unless $name =~ m%^(.*)\.([^\.]*)$%;
	$namemod = $1;
	$tag = $2;
	$tag =~ tr/A-Z/a-z/;
	next unless (($tag eq 'gif') || ($tag eq 'jpg') || ($tag eq 'htm') || ($tag eq 'html') );
	$filename{$namemod} = $sourceimage . '/' . $name;
	$referenced{$namemod}=0;
	$ct++;
}
close(ORGIMAGE);
unless($summary)	{
	print("No abstract or summary provided for this cassette\n");
}
unless($originalindex)	{
	die("\nSorry no index file on $source\n");
}
unless($ct)	{
	die("\nSorry no photos on $source\n");
}
#
#	Process Summary file and as you read it, write destination outline file
#	Accumulate data for later output into options file
%procoptvocab =
 ( "bullet1",1,"bullet2",1,"bullet3",1,"bullet4",1,"htmlline",1,
 "foilauthor",1,"foildate",1,"foilevent",1,
 "author",0, "date",0,,"datemod",0,"event",0,"source",0,
 "abstract",0,"addsource",0,"contd",0,"name",0,"label",0,
 "runningtitle",0,"titleset",0,"signature",0,"html",0,"endhtml",0);
#
&readopt($originalindex);
#
#	Output warning for ignored photos
foreach $namemod (keys %filename)	{
	print "File $filename{$namemod} Not Referenced\n" unless($referenced{$namemod});
}
#
#	Output options file
print OPTIONS "bulletsongif:\n";
#
$label = $optionvalues{'label'};
unless($label)	{ # default for label
	if( $optionvalues{'name'} )	{
		$label = $optionvalues{'name'};
	}
	else	{
		$label = $destination;
		$label =~ s%^(.*)/%%;
	}
	$optionvalues{'label'} = $label;
}
$name = $optionvalues{'name'};
unless($name)	{ # default for name:
	$name = $optionvalues{'label'};
	$name =~ tr/A-Z/a-z/;
}
print OPTIONS "name:$name\n";
print OPTIONS "label:$label\n";
print OPTIONS "addsource:$label\n";
#
$author = $optionvalues{'author'};
unless($author)	{
	$author = 'Unknown Photo Snapper';
}
print OPTIONS "author:$author\n";
#
$event = $optionvalues{'event'};
unless($event) {
        $event = 'Unknown Photo Event';
}
print OPTIONS "event:$event\n";
#
$date = $optionvalues{'date'};
unless($date) {
        $date = 'Unknown Cassette Date';
}
print OPTIONS "date:$date\n";
#
$datemod = $optionvalues{'datemod'};
unless($datemod) {
        $datemod = $today;
}
print OPTIONS "datemod:$datemod\n";
#
$title = $optionvalues{'titleset'};
unless($title) {
	$title = "Cassette $destination from $sourceimage";
}
print OPTIONS "titleset:$title\n";
#
$runningtitle = $optionvalues{'runningtitle'};
unless($runningtitle) {
        $runningtitle = $title;
}
print OPTIONS "runningtitle:$runningtitle\n";
#
print OPTIONS "abstract:outsidesummary\n";
#
print OPTIONS @signaturedata;
close(OPTIONS);
#
#	Output summary file
$write = $destination . '/outsidesummary';
open(SUMMARY,'>'.$write) || die("\nSorry Could not open ",$write," \n");
if($summary)	{	# Abstract File provided
	$summaryfile =  $summary;
	open(OLDSUMMARY,'<'.$summaryfile) || die("\nSorry Could not open ",$summaryfile," \n");
	@summarydata = <OLDSUMMARY>;
	close(OLDSUMMARY);
	$lasti=@summarydata;
	$wwwfoilformat =0;
	if( $lasti)	{
		$testline = $summarydata[0];
		$testline =~ m%([^:]*):(.*)$%;
		$testline = $1;
		if( $testline)	{
			$testline =~ tr/A-Z/a-z/;
			$wwwfoilformat = 1 if($testline eq 'endhtml' );
			$wwwfoilformat = 1 if($testline eq 'beginfoil' );
		}
	}
	if($wwwfoilformat)	{	# Simple Copy
		print SUMMARY @summarydata;
	}
	else	{	# Simple Ascii Text in Summary
		print SUMMARY <<EOF;
endhtml:
beginfoil:
title:Summary of $title
noimageversion:
EOF
		for($i=0;$i<$lasti;$i++)	{
			$line = $summarydata[$i];
			chomp($line);
			print SUMMARY "Bullet1:$line\n";
		}
		print SUMMARY <<EOF;
endfoil:
EOF
	}
}
else	{	# Make default Abstract
print SUMMARY <<EOF;
endhtml:
beginfoil:
title:Summary of $title
noimageversion:
endfoil:
EOF
}
close(SUMMARY);
#
sub jumpfoil{ # Return relative path from $from to $to
#
        my($from,$to)=@_;
        my($path);
#
        return $to if( $to =~ m%^/% );
        return $to if( $to =~ m%^http% );
        die("Undefined jump from ",$from," to",$to,"\n")        if( $from =~ m%^/% );
#
        $from =~ s%/\./%/%g;
        $from =~ s%//%/%g;
        $from =~ s%^\./%%;      # Remove null directory movements
        $to =~ s%/\./%/%g;
        $to =~ s%//%/%g;
        $to =~ s%^\./%%;        # Remove null directory movements
        return $to unless $from =~ s%/[^/]*$%%; # Remove last slash and filename leaving directories
        $path='';
        $from =~ s%\.%\\\.%g;   # Ensure all dots are real dots in $from!
        while($from)    {
                if( ($to =~ m%^${from}/%) )     {
                        $to =~ s%^${from}/%% ;
                        last;
                }
                if( ($to =~ m%^${from}$%) )     {
                        $to =~ s%^${from}%%;
                        last;
                }
                $path .= '../';
                $from='' unless $from =~ s%/[^/]+$%% ;
        }
        $path .= $to;
        return $path;
}       # End routine returning relative path
#
sub readalias	{ # Read alias file
#
	my($file)=@_;
#
	my($fullline);
#
	open(ALIAS,$file) || die("Sorry Couldnt read ALIAS ",$fullline," \n");
        while($fullline=<ALIAS>)        {
                chomp($fullline);
                &alias_decode('',$fullline);
        }
        close(ALIAS);
	&alias_cleanup;
}
#
sub alias_decode	{ # Decode alias definition
# key is EITHER in first argument or in first entry in value1@value2@  ..
# string transmitted as second argument
# if key is alias assume next entry in string is real key!
#
	my($key,$line)=@_;
	my(@fields,$test);
#
	@fields=split(/@/,$line);
	$test=$fields[0];
	$test =~ tr/A-Z/a-z/;
	shift(@fields)	if($test eq 'alias');
	$key=shift(@fields) unless $key;
	$key=shift(@fields) if $key eq 'alias';
#
	$wwwalias_url{$key}=$fields[0];
	if($fields[1])	{
		$wwwalias_title{$key}=&tohtml($fields[1]);
		$wwwalias_titlegiven{$key}=1;
	}
	else	{
		$wwwalias_title{$key}='At location ' . &tohtml($fields[0]);
		$wwwalias_titlegiven{$key}=0;
	}
	$wwwalias_comment{$key}= &tohtml($fields[2]);
	$wwwalias_author{$key}= &tohtml($fields[3]);
	$wwwalias_date{$key}= &tohtml($fields[4]);
#
}	# End alias_decode
#
sub alias_cleanup	{
#
	my($name,$replace);
#
	foreach $name (keys %wwwalias_url)	{
		$changed_alias=1;
		$replace=$wwwalias_url{$name};
		while( $changed_alias)	{
			$changed_alias=0;
			$replace=&alias_subst($replace);
		}
		$wwwalias_url{$name}=$replace;
	}
}	# End alias_cleanup
#
sub alias_subst	{
#
	my($total);
#
	$end_alias=$_[0];
	$total="";
	while($end_alias)	{
		if(&aliascurlyscan($end_alias))	{
			$total .= $begin_alias;
			if( $full=$wwwalias_url{$tag_alias} )	{
				if( &aliasroundbracket($end_alias) )	{
					$string_alias=$wwwalias_title{$tag_alias} unless $string_alias;
					$total .= '<a href="' . $full . '" >' . $string_alias . '</a>';
				}
				else	{
					$total .= $full;
				}
				++$changed_alias;
			}
			else	{
				$total .= '{' . $tag_alias . '}';
			}
			next;
		}
		else	{
			$total .= $begin_alias;
			last;
		}
	}	# End loop over curly brackets
	return $total;
#
}	# End alias_subst
#
sub aliasroundbracket	{
#
	$end_alias=$_[0];
	if( $end_alias =~ m%^\\\(%	)	{
		$end_alias =~ s/^.//;
		return 0;
	}
	if( $end_alias =~ m%^\(([^\(\)]*)\)(.*)% )	{
		$string_alias= $1;
		$end_alias=$2;
		return 1;
	}
	return 0;
#
}	# End aliasroundbracket
#
sub aliascurlyscan	{ 
#
	my($inline)=@_;
	my($line);
#
	$line=$inline;
	$begin_alias='';
	while($line)	{
#
		if( $line =~ m%([^{]*){([^}]*)}(.*)% 	)	{
			if( $1 =~ m%\\$% )	{
				$begin_alias .= $1 . '{';
				$line = $2.'}'.$3;
				next;
			}
			$begin_alias .= $1;
			$end_alias=$3;
			$tag_alias=$2;
			$tag_alias =~ s/\s*//g;
			return 1;
		}
		$begin_alias=$inline;
		$end_alias='';
		$tag_alias='';
		return 0;
	}	# End loop over starting curly bracket
	$begin_alias=$inline;
	return 0;
#
}	# End alias curly scan
#
# read index according to  PROCPHOTOS
sub readopt {
#
	my($procfile)=@_;
	my($writeout,$curkey,$vocabmem,$reading_html,$colon,$possiblekey,$savekey,$entry,$rest,$line);
#
	open(PROCPHOTOS,$procfile) || die("\nSorry couldnt Open Procoptions ",$procfile, "\n");
#
	$reading_html=0;	# Initial HTML option
	undef %optionvalues;
        $optionvalues{'filename'}='NULL';
	$writeout=0;
#	$writeout =0 no photo in action
#	$writeout =1 photo initialized
#	$writeout =2 photo pending
#
	$curkey='none';
	while( $line=<PROCPHOTOS> )	{
		chomp($line);
		$colon = index($line,":");
		if ( ($line =~ /^\s/) || $colon < 0 )	{
			die("\nIllegal Continuation Line", $rest,"\n") if $curkey eq 'none';
			$line =~ s/^\s+/ /;
			if($writeout == 1 )	{
				print OUTLINE "contd:$line\n";
			}
			else	{
				$optionvalues{$curkey} = &join($optionvalues{$curkey},$line);
			}
			next;
		}
		$possiblekey = substr($line ,0, $colon);
		$possiblekey =~ s/\s+//g;
		$savekey=$possiblekey;
		$possiblekey = &phototofoil($possiblekey);
		$entry = -1;
		foreach  $vocabmem (keys %procoptvocab) {
			if( $possiblekey eq $vocabmem )	{
				$entry = $procoptvocab{$vocabmem};
				last;
			}
		}
		if( $entry < 0 )	{	# Check if a Filename
			$possiblekey =~ s/^0*//;
			$possiblekey =~ s/\.(.*)$//;
			foreach $vocabmem (keys %filename)	{
				next unless( $vocabmem =~ m%^(\D*)0*$possiblekey$% );
				$possiblekey = $vocabmem;
				$entry =1001;
				if( (++$referenced{$vocabmem}) > 1 )	{
					print "Multiple reference to $filename{$vocabmem}\n";
				}
				if( $writeout == 1 )	{
					print OUTLINE "endfoil:\n";
				}
				elsif( $writeout == 2 )	{
					&procphoto();
					print OUTLINE "endfoil:\n";
				}
				$writeout =2;
				$optionvalues{'filename'} =$possiblekey;
				last;
			}
		}
		if( $entry < 0 )	{
			die("\nIllegal key Processing User Index ", $possiblekey, "\n");	}	
		if( $possiblekey eq "html" )	{
			$reading_html=1;
			next;
		}
		if( $possiblekey eq "endhtml" )	{
			$reading_html=0;
			next;
		}
		$rest = substr($line, $colon+1);
		if( $possiblekey eq "contd" )	{
			if ($curkey eq 'none')	{
				die("\nIllegal Continuation Line", $rest,"\n");	}
			if($writeout == 1 )     {
                                print OUTLINE "$savekey:$rest\n";
                        }
			else	{
				if( $savekey eq "CONTD" )	{
					$optionvalues{$curkey} .= "\n" . $rest;
					next;
				}
				$optionvalues{$curkey} = &join($optionvalues{$curkey},$rest);
			}
			next;
		}
		if( ($entry <2) && ($writeout == 2) )	{
			$writeout = &procphoto();
		}
		if( $writeout == 1 )	{
			$possiblekey = 'foildate' if( $possiblekey eq 'date' );
			$possiblekey = 'foilplace' if( $possiblekey eq 'place' );
			$possiblekey = 'foilauthor' if( $possiblekey eq 'author' );
			print OUTLINE "$possiblekey:$rest\n";
		}
		$optionvalues{$possiblekey} = $rest;
		$optionvalues_html{$possiblekey} = $reading_html;
		$curkey=$possiblekey;
	}	# End loop over input lines
#
	if( $writeout == 1 )    {
		print OUTLINE "endfoil:\n";
	}
	elsif( $writeout == 2 ) {
		&procphoto();
		print OUTLINE "endfoil:\n";
	}
	close(PROCPHOTOS);
#
	return;
#
} # end readopt
#
sub procphoto	{ # Process photograph(foil) parameters
#
	my($outkey,$key,$title);
#
	return 0 if( ($key=$optionvalues{'filename'}) eq 'NULL');
	$title = $optionvalues{$key};
	return 0 if( $title =~ m%^\s*DELETE\s*$% );
	$oldtitle = $title;
	undef %tagvalues;
	while( $oldtitle ne ($title= &interprettags($title)) )	{
		$oldtitle = $title;
	}
	$optionvalues{$key}=$title;
	print OUTLINE <<EOF;
beginfoil:
title:$optionvalues{$key}
getimagefrom:$reljump$filename{$key}
Criticalmissing:
EOF
	foreach $key (keys %tagvalues)	{
		next unless(defined($tagvalues{$key}));
		$outkey = $key;
		$outkey = 'foildate' if( $outkey =~ m%date% );
		$outkey = 'foilevent' if( $outkey =~ m%event% );
		$outkey = 'foilauthor' if( $outkey =~ m%author% );
		print OUTLINE "$outkey:$tagvalues{$key}\n";
	}
	return 1;
}
sub interprettags	{
	my($line)=@_;
	my($remains,$tag,$value);
#
	return $line unless($line =~ m%(.+){([^{}=]+)\s*=\s*([^{}]+)}\s*$% );
	$tag = $2;
	return $line unless(defined($tag));
	$remains = $1;
	$value =$3;
	$tag = &phototofoil($tag);
	return $line unless( $tag =~ m%(date|event|author)% );
	$tagvalues{$tag}=$value;
	return $remains;
}
#
sub tohtml	{ # Convert HTML magic characters in current line
	my($convline)=@_;

	return($convline)	unless $convline;
	$convline =~ s/&/&amp;/g;
	$convline =~ s/</&lt;/g;
	$convline =~ s/>/&gt;/g;
	$convline =~ s/"/&quot;/g;
	$convline;
}
#
#       Join  2 lines together returning result
#       add white space as necessary
sub join        {
        my($a,$b) = @_;
        $a = $a . ' '   if( ($a =~ /\S$/) && ($b =~ /^\S/) ) ;
        return $a . $b ;
}
#
sub phototofoil	{	# Make uniform names
	my($key) = @_;
	$key =~ tr/A-Z/a-z/;
	$key =~ s/photographer/author/;
	$key =~ s/snapper/author/;
	$key =~ s/place/event/;
	$key =~ s/datemodified/datemod/;
	$key =~ s/datesnapped/date/;
	$key =~ s/photo/foil/;
	$key =~ s/nickname/name/;
	$key =~ s/printlabel/label/;
	$key =~ s/summary/abstract/;
	return $key;
}
#
1;
