#!/bin/env python

#
# Script to convert GADM files to UTF-8
#

import os
import codecs

#from osgeo import ogr

for filePrefix in ["gadm1_lev0", "gadm1_lev1", "gadm_v1_lev2"]:

    # Download the file
    #wget http://gadm.org/data/gadm_v1_lev0_shp.zip
    #wget http://gadm.org/data/gadm_v1_lev1_shp.zip
    #wget http://biogeo.ucdavis.edu/data/gadm/gadm_v1_lev2_shp.zip

    # Unzip it
    #unzip gadm_v1_lev0_shp.zip
    #unzip gadm_v1_lev1_shp.zip
    #unzip gadm_v1_lev2_shp.zip

    # Use OGR to convert SHP to CSV
    #ogr2ogr -f CSV CSV gadm1_lev0.shp -lco GEOMETRY=AS_WKT
    #ogr2ogr -f CSV CSV gadm1_lev1.shp -lco GEOMETRY=AS_WKT
    #ogr2ogr -f CSV CSV gadm_v1_lev2.shp -lco GEOMETRY=AS_WKT
    
    # Convert CSV to UTF-8
    fileName = os.path.join("CSV", "%s.csv" % filePrefix)
    fileObj = codecs.open(fileName, "r", "latin-1")
    input = fileObj.read()
    fileOut = codecs.open("%s_utf8.csv" % filePrefix, "w", "utf-8")
    fileOut.write(input)
    fileOut.close()

    #os.rmdir("CSV")

    # Import the data into PostGIS
    # pgloader
    
    
    
