#!/usr/bin/env python
import os
import datetime

def test_reduce():
	base		= "."
	flatfile	= "flat/flatc.ST7"
	aperture	= 1
	var			= [7]
	comp		= [5]
	check		= [11, 12]
	object      = ("CR Cas", 23.0811, 59.5658)
	location    = ("Vyskov", 17.0225, 49.2836)

	srcdir = os.path.join(base, "data")
	tmpdir = os.path.join(base, "tmp")
	outdir = base
	try:
		os.mkdir(tmpdir)
	except:
		pass

	stars = []
	stars.extend(var)
	stars.extend(comp)
	stars.extend(check)
	
	flist = os.listdir(srcdir)
	flist.sort()
	frames = []
	p = cmpack.Photometry()
	m = None
	s = cmpack.FrameSet(stars, range(1, 13))
	#
	# Calibration, photometry and matching
	#
	frame_id = 1
	with cmpack.CCDFile.open(os.path.join(base, flatfile), cmpack.READONLY) as ff:
		f = cmpack.Flat(ff)
		for path in flist:
			srcpath = os.path.join(srcdir, path)
			print srcpath + ":"
			with cmpack.CCDFile.open(srcpath, cmpack.READONLY) as src:
				dst = f.apply(src)
				dst.save(os.path.join(tmpdir, "frame%d.fits" % frame_id))
				pht = p.run(dst)
				print("%d stars found." % len(pht.stars))
				pht.save(os.path.join(tmpdir, "frame%d.pht" % frame_id))
				if m == None:
					m = cmpack.Match(pht)
				res = m.run(pht)
				if res:
					print ("%d stars matched." % res[0])
					s.append(frame_id, pht)
				else:
					print "Not matched.";
			frame_id = frame_id + 1

	#
	# Make light curve
	#
	cols = ["JD", "V-C", "HELCOR", "AIRMASS"]
	print "----------------------------------------"
	print " ".join(cols)
	c = cmpack.LightCurve(s, 1, var, comp, check, helcorr=True, airmass=True, object=object, location=location)
	for (jd, v_c, h_c, x) in c.get_all(cols):
		print jd, v_c, h_c, x
	print "----------------------------------------"
	print "Done."


try:
	import cmpack

	test_reduce()

except Exception as E:
	print E

