"""
The old lightmeter driver used to generated something that wasn't
really skyglow.  This script converts these old files.

It ignores other files and files already converted, so it should be
safe to run this on larger collections of files.
"""

import gzip
import os
import sys
import time


def convert_line(ln):
	if ln.startswith("#"):
		return ln
	utd, utt, ltd, ltt, temp, unit, count = ln.split(";")
	ut = time.strftime("%Y-%m-%dT%H:%M:%S",
		time.strptime(utd+"T"+utt, "%d.%m.%YT%H:%M:%S"))
	lt = time.strftime("%Y-%m-%dT%H:%M:%S",
		time.strptime(ltd+"T"+ltt, "%d.%m.%YT%H:%M:%S"))
	
	return "%s;%s;%s;%s"%(ut, lt, temp, count)
			

def convert_one(fname):
	if fname.endswith(".gz"):
		f = gzip.open(fname)
	else:
		f = open(fname)

	try:
		lines = [f.readline()]
		if not lines[0].startswith("# Community Standard Skyglow Data Format"):
			raise ValueError("Not a skyglow file.")
		lines.extend(f.readlines())
	finally:
		f.close()

	for l in lines:
		if not l.startswith("#"):
			break
	else:
		raise ValueError("No data")
	
	if not ";C;" in l:
		raise ValueError("Already converted")
	
	converted = map(convert_line, lines)

	if fname.endswith(".gz"):
		f = gzip.open(fname+".tmp", "w")
	else:
		f = open(fname+".tmp", "w")
	
	try:
		f.write("".join(converted))
	finally:
		f.close()
	
	os.rename(fname+".tmp", fname)


def convert_all():
	for name in sys.argv[1:]:
		try:
			convert_one(name)
		except Exception, msg:
			sys.stderr.write("%s: %s\n"%(name, msg))


if __name__=="__main__":
	convert_all()
