#!/usr/bin/env python

#NOTE: look if your track files order coordinates lat,lon or lon,lat.
#      Then select the appropriate order in the places marked XXX in this
#      source code.

import sys, re, hashlib
from pysqlite2 import dbapi2 as sqlite

if len(sys.argv) < 4:
  print "usage:"
  print "./gpx2tango gpxfile routename poidbfile"
  print "  gpxfile: a file in the gpx file format, containing the route"
  print "  routename: this will be entered as keyword into the poi database"
  print "  poidbfile: usually poi.db, or any other wellformed tangogps poi sqlite database file"
  sys.exit(1)

#XXX
RE_TRKPT = '<trkpt lat="([0-9\.]+)" lon="([0-9\.]+)"'
#RE_TRKPT = '<trkpt lon="([0-9\.]+)" lat="([0-9\.]+)"'
#/XXX

re_trkpt = re.compile(RE_TRKPT)

ROUTE_NAME = sys.argv[2]

con = sqlite.connect(sys.argv[3]) 
cur = con.cursor()

gpx = open(sys.argv[1])
for line in gpx:
  results = re_trkpt.findall(line)
  for match in results: 
#   XXX
    lat, lon = match 
#   lon, lat = match 
#   /XXX
    idmd5 = hashlib.md5(str(lon)+str(lat)).hexdigest()[0:18] #not the format tangogps uses, but what's an idmd5?s
    query = "insert into poi (idmd5, lon, lat, keywords, visibility, cat, subcat, price_range, extended_open) values ('"+idmd5+"', '"+str(lon)+"', '"+str(lat)+"', '"+ROUTE_NAME+"', 0.0, 0.0, 0.0, 3.0, 0.0)" #tangogps crashes if some of these remain NULL. whatever.
    cur.execute(query)

#if everything went fine, commit the changes.
con.commit()

