#!/usr/bin/perl

use Getopt::Long;

use lib "/mt/apps/gpms/DateTrans/lib";
use DateTrans qw(monName monNumber timeFormat AmPmFormat dayNumbeFormat);


sub usage() {
    print "Usage: perl $0 [-theme=<theme>]\n";
 print "Example:\n";
    print "perl $0 -theme=theme\n";
    print "where -theme is the theme of the files that are to be updated\n"
};

%gOptions;
&GetOptions(\%gOptions, qw(theme=s));
unless ($gOptions{theme}) {
        usage();
        exit(1);
};

#$theme="addr";
$theme= $gOptions{theme};
print "\$theme = $theme\n";

$mainDir = "/home/m/mccre004/GPMSscripts/FileMoverDir";
$metadataDir ="http://meta.geo.census.gov/data/existing/decennial/GEO/GPMB/TIGERline/TIGER2013/";
$FirstPartOfLine ="<gco:CharacterString xmlns:gco=\"http:\/\/www.isotc211.org\/2005\/gco\">";
$lastPartOfLine="</gco:CharacterString>";

$indir = $mainDir . "/" . $theme;



my $now=`date`;
$mon = substr($now,4,3);
$day=substr($now,8,2);
$year =substr($now,24,4);
$hour = substr($now,11,2);
$min = substr($now,14,2);
my $daynum= dayNumbeFormat($day);

#2013_addr.ea.iso.xml
#2013_addr.ea.iso.xml

print "\$year = $year\n";
$eaFile = $year . "_" . $theme . ".ea.iso.xml";

print "\$eaFile = $eaFile\n";
opendir INDIR, $indir or die "cannot open $indir: $!";

foreach $file (readdir INDIR ){
if ($file ne "."){
#print "\$file = $file\n";

$firstdot = index($file, ".");
$predicate = substr($file,0,$firstdot);
$suffix= substr($file,$firstdot);
$newFile = $predicate . "_ver2" . $suffix;

#print "\$predicate = $predicate\n";
#print "\$suffix = $suffix\n";
#print "\$newFile = $newFile\n";

$inFile = $indir  . "/" . $file;
$outnewFile = $indir  . "/" . $newFile;
open INPUT, "<$inFile";
open OUTPUT, ">$outnewFile";

while (<INPUT>){
$line =$_;
#print "\$line= $line";

if ($line =~ /<gco:CharacterString xmlns:gco=\"http:\/\/www.isotc211.org\/2005\/gco\">http:\/\/www2.census.gov\/geo\/tiger\/TIGER2013/){

$zipPos=rindex($line,".zip");
if ($zipPos <0){
$newLine =  $FirstPartOfLine .  $metadataDir . $theme . "/" . $eaFile . $lastPartOfLine;
print OUTPUT $newLine;
}else{
print OUTPUT $line;
};

}else{
print OUTPUT $line;
};





};
close OUTPUT;
close INPUT;

$swpLocation =rindex($outnewFile,".swp");
$lastSlashLoc=rindex($outnewFile,"/");
$lastFile=substr($outnewFile,$lastSlashLoc+1);
$lastFileLen=length($lastFile);

if ($lastFileLen <8){
print "\$lastFile = $lastFile\n";
print "\$lastFileLen = $lastFileLen\n";
};

if ($swpLocation < 0 or $lastFile ne "_ver2.."){
system "mv $outnewFile $inFile";
}else{
system "rm $outnewFile";
};
};
};
