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

def test_kombine():
	base		= "."
	flatfile	= "flat/flatc.ST7"

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

	flist = os.listdir(srcdir)
	flist.sort()
	frames = []
	p = cmpack.Photometry()
	m = None
	with cmpack.CCDFile.open(os.path.join(outdir, "kombined.fits"), cmpack.CREATE) as out:
		k = cmpack.Kombine(out)
		#
		# 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])
						k.add(dst, pht)
					else:
						print "Not matched.";
				frame_id = frame_id + 1
		#
		# Save output file
		#
		print "Writing output file..."
		k.flush()
		print "Done."

try:
	import cmpack

	test_kombine()

except Exception as E:
	print E

