#!/bin/env python

import sys

try:
    if len(sys.argv) > 1:
        # Run as python scriptname xxx.csv
        input = sys.argv[1]
    else:
        # Run as ./scriptname xxx.csv
        input = sys.argv[0]
except:
    print "Specify CSV file as argument: python moveWKT.py myfile.csv"
    sys.exit(2)

try:
    prefix, extension = input.split(".", 1)
except:
    print "Invalid filename!"
    sys.exit(2)

if extension != "csv":
    print "Input file should be xxx.csv!"
    sys.exit(2)

try:
    inputFile = open(input, "r")
except:
    print "Cannot open file!"
    sys.exit(2)

output = "%s-fixed.csv" % prefix
outputFile = open(output, "w")

header = True
for line in inputFile:
    if header:
        outputFile.write(line.strip().split(",", 1)[1] + ",WKT\n")
        header = False
        continue
    pieces = line.split('"', 2)
    wkt = pieces[1]
    rest = pieces[2][1:].strip()
    outputFile.write(rest + ',"' + wkt + '"\n')

inputFile.close()
outputFile.close()
