#!/bin/env python

import sys
args = sys.argv
if not args[1:]:
    print "Usage: python KML2WKT.py <filename>.kml"
    sys.exit(1)

from lxml import etree
from keytree.factory import *
from shapely.geometry import asShape
from shapely.wkt import dumps as wkt_dumps

GEOM_TYPES = [
    "Point",
    "LineString",
    "Polygon",
    #"LinearRing",
    #"MultiGeometry"    # Not currently supported
    ]

inputFilename = args[1]
outputFilename = "%s.csv" % inputFilename[:-4]

inputFile = open(inputFilename, "rb")
data = inputFile.read()
inputFile.close()

root = etree.fromstring(data)
kmlns = root.tag.split("}")[0][1:]
placemarks = root.findall(".//{%s}Placemark" % kmlns)

output = u"Name,Comments,Lat,Lon,WKT\n"
for placemark in placemarks:
    name = placemark.find("{%s}name" % kmlns).text
    desc = placemark.find("{%s}description" % kmlns).text

    output += unicode('"')
    output += name
    output += unicode('"')
    output += unicode(",")

    output += unicode('"')
    output += desc
    output += unicode('"')
    output += unicode(",")

    for geom_type in GEOM_TYPES:
        tag = "{%s}%s" % (kmlns, geom_type)
        geom_element = placemark.findall(".//%s" % tag)
        if geom_element == []:
            continue
        else:
            g = geometry(geom_element[0])
           
        shape = asShape(g)
        if geom_type == "Point":
            output += unicode(shape.y)
            output += unicode(",")
            output += unicode(shape.x)
            output += unicode(",")
            output += unicode("\n")
        else:
            wkt = wkt_dumps(shape)
            output += unicode(",")
            output += unicode(",")
            output += unicode(wkt)
            output += unicode("\n")

import codecs

outputFile = codecs.open(outputFilename, encoding="utf-8", mode="w")
outputFile.write(output)
outputFile.close()
