#! /usr/bin/perl -w
########################################################################
## Mon Mar 12 16:35:43 PDT 2007
##
## this is going to unzip a whole mess of tiger files and
## call oger2ogr on them so as to load them into postgis
########################################################################

use strict;

my $TIGS ='/data/commons/carlm/Tiger02/CA';

my $FIPS ='fips.txt';

#"CompleteChain",
my @layers =(
"AltName" ,
"FeatureIds" ,
"ZipCodes" ,
"Landmarks" ,
"AreaLandmarks" ,
"Polygon" ,
"PolygonCorrections" ,
"EntityNames",
"PolygonEconomic" ,
"IDHistory" ,
"PolyChainLink" ,
"PIP",
"TLIDRange" ,
"ZeroCellID" ,
"OverUnder" ,
"ZipPlus4" );


open(FIPS, "$FIPS") or die("$FIPS is crap");
my $fips;
foreach(<FIPS>){
  next if $_ =~m/County Name/;
  chomp($_);
  my @parts=split(/\t/, $_);
  chomp($parts[0]);
  $parts[0]=~s/\s/\_/g;
  $parts[0]=~s/\_+$//;
  $fips->{$parts[0]} = sprintf("%03d",$parts[1]);
}

chdir $TIGS;

while(my($cname, $fip) = each(%{$fips})){
  my $fzip = 'TGR06'.$fip.'.ZIP';
  (-f $fzip ) or warn("$fzip is crap");
  warn "unzipping $fzip";
  system("unzip -o $fzip");
  
  foreach my $layer (@layers){
    
    my $tgrfile = 'TGR06'.$fip.'.RT1';
    my $schemaName = $cname.'_'.$layer;
## $tgrfile TGR06001.RT1
## $layer   Landmarks
## $schemaName  alameda_landmarks

    my $OGR = qq|ogr2ogr -update -append -f "PostGreSQL" PG:"host=pareto user=carlm dbname=carlm password=5581727" $tgrfile layer $layer -nln $schemaName  -a_srs "EPSG:4269"|; 

    print $OGR."\n";
    system($OGR);
  }
}
