#!/usr/bin/python
import sys, time, datetime, math, gpstime
secsInWeek = 604800
secsInDay = 86400
gpsEpoch = (1980, 1, 6, 0, 0, 0)  # (year, month, day, hh, mm, ss)
leapSecs = 16 #UTC to GPS timestamp diff

def gpsFromUTC(t):
    secFract = t % 1 
    epochTuple = gpsEpoch + (-1, -1, 0)
    t0 = time.mktime(epochTuple)
    tdiff = t - t0 + leapSecs
    gpsSOW = (tdiff % secsInWeek)
    gpsWeek = int(math.floor(tdiff/secsInWeek)) 
    gpsDay = int(math.floor(gpsSOW/secsInDay))
    gpsSOD = (gpsSOW % secsInDay)
    return (gpsWeek, gpsSOW, gpsDay, gpsSOD)

def parse_csv_time(date, _time):

  #7.8.2014 14:00:21.17 
  format_str = "%d.%m.%Y %H:%M:%S.%f"
  input_str = "{0} {1}".format(date, _time)
  t = time.strptime(input_str, format_str)
  dt = datetime.datetime.strptime(input_str, format_str)
  return gpsFromUTC(time.mktime(t) + dt.microsecond/1e6)[1]

def fix_headers(headers):
  columns = [] 
  first_height = True 
  for column in headers:
    column = "".join([ char.lower() if char.isalnum() else "_" for char in column.strip()])
    if (column == 'height' and first_height):
      column = 'barometer_height'
      first_height = False 
    columns.append(column)
  return ",".join(columns)

if __name__ == "__main__":
  file_arg = sys.argv[1]
  infile = open(file_arg, "r")
  outfile = open(sys.argv[2], "w")
  input_lines = infile.readlines()
  headers = input_lines[0].split(";")
  outfile.write("{0}, {1}\r\n".format("gps_sow", fix_headers(headers[1:])))
  time_format = "%d.%m.%Y %H:%M:%S.%f"
  for line in input_lines[1:]:
    data = line.split(";")
    gps_sow = gpstime.gps_from_string("{0} {1}".format(data[0], data[1]), time_format, 0, 1)[1]
    outfile.write("{0}, {1}".format(gps_sow, ",".join(data[1:])))
