# Produces a set of shapefiles (OSM, NRN, STATSCAN) for
# each provincial + NTS tile combination.
# 
# usage: create_shapefiles.sh inputfile.txt
#
#
#
# Where inputfile.txt is a file of the form
#
# HAMILTON,031M05,ONTARIO
# GTA,031M.*,ONTARIO
# 90Ftiles,090F.*,BRITISH_COLUMBIA
#
# the second argument can be any regular expression that describes
# a set of 50k NTS tiles.  
#
# Provinces with spaces in them sh

export DBNAME=gis
export PGHOST=localhost

for line in $(cat $1)
do
echo "Starting on $line"
name=`echo $line | cut -d, -f1`
regex=`echo $line |cut -d, -f2`
prov_=`echo $line|cut -d, -f3`
prov=`echo $prov_|sed  -e 's/_/ /g'`
mkdir -p $prov_
mkdir -p $prov_/$name
pgsql2shp -f $prov_/$name/OSM.shp $DBNAME "select * FROM select_osm_roadtile('$regex','$prov')"
pgsql2shp -f $prov_/$name/NRN.shp $DBNAME "select * FROM select_nrn_roadtile('$regex','$prov')"
pgsql2shp -f $prov_/$name/STATSCAN.shp $DBNAME "select * FROM select_statscan_roadtile('$regex','$prov')"
psql $DBNAME -t -c " select ST_AsEwkt(st_box2d(st_transform( st_union(the_geom),4326))) FROM nts_50k_index where identif ~ '$regex' "|sed -e 's/SRID=4326;//' >$prov_/$name/bounds.txt

done
