#!/perl -w
# NAME: fixtitle.pl
# AIM: specialized perl, to read a particular XML file,
# extract the file name, and make it into a title, and write results.
# 25/08/2007 geoff mclane - geoffair.net/mperl/
use strict;
use warnings;
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /\w{1}:\\.*/) {
	my @tmpsp = split(/\\/,$pgmname);
	$pgmname = $tmpsp[-1];
}
my $outfile = "temp.$pgmname.txt";
open_log($outfile);
prt( "$0 ... Hello, World ...\n" );
my $in_file = 'C:\Documents and Settings\Geoff McLane\My Documents\Louis\banan\myP2\BananAlbum.xml';
###my $in_file = 'Banan.xml';
my $out_file = 'tempxml.xml';
my @lines = ();
my $nxml = '';

#         <image width="771" height="783">images/1_LaBaieDeLaMoselleAcrylic100X100.jpg</image>
if (open( INF, "<$in_file") ) {
	@lines = <INF>;
	close INF;
	my $max = scalar @lines;
	my $labln = 0;
	my $ll = '';
	my $llsp = '';
	my $nll = '';
	prt( "Processing $max lines ...\n" );
	for (my $i = 0; $i < $max; $i++) {
		my $line = $lines[$i];
		if ($line =~ /<label>.*<\/label>/) {
			$labln = $i;
			$ll = $line;
			$llsp = '';
			if ($ll =~ /(\s*)\S/) {
				$llsp = $1;
			}
		} elsif ($line =~ /<image\s+.*>(.*)<\/image>/) {
			my $file = $1;
			if ($labln) {
				my $fil = substr($file,7);
				my $ch = substr($fil,0,1);
				while (($ch =~ /\d/)||($ch eq '_')) {
					$fil = substr($fil,1);	# eat numbers and under score
					$ch = substr($fil,0,1);
				}
				my $sfn = split_file_name($fil);
				$nll = "$llsp<label>$sfn</label>\n";
				$lines[$labln] = $nll;
				prt( "[$sfn] [$llsp]\n" );
			} else {
				prt( "\n*********\nWARNING: Missed label line ...\n" );
			}
			$labln = 0;
		}
	}
}

$nxml = join('', @lines);

write2file($nxml,$out_file);

close_log($outfile,1);
exit(0);

################################
#### subs
sub split_file_name {
	my ($fil) = shift;
	my $len = length($fil);
	my $sfn = '';
	my $pch = '';
	my $inn = 0;
	for (my $i = 0; $i < $len; $i++) {
		my $ch = substr($fil,$i,1);
		if ($ch eq '.') {
			last;
		}
		my $val = ord($ch);
		if ( !$inn ) {
			if ($ch =~ /\d/) {
				$sfn .= '|' if (length($sfn));
				$inn = 1;
			} elsif (($val >= 65) && ($val <= 90)) {
				$sfn .= '|' if (length($sfn));
			}
		}
		$sfn .= $ch;
		$pch = $ch;
	}
	if ($sfn =~ /^F\|\S/) {
		$sfn = 'FS'.substr($sfn,3);
	}
	$sfn =~ s/\|/ /g;
	return $sfn;
}

# eof - fixtitle.pl
