#!/usr/bin/python
from PIL import Image
import numpy
import pyfits
from glob import glob
import os
import sys

def tifftofits(infile, outfile, compression = None, dtype = None):
	image = Image.open(infile)
	if dtype is not None:
		numarray = numpy.array(image, dtype = dtype)
	else:
		numarray = numpy.array(image)

	# crop away the borders.  Let's see if we can get by without having to
	# look at things
	numarray = numarray[700:14900,600:14800]

	# Then invert pixels for optical reasons and because sextractor likes
	# that much better
	numarray = 65536-numarray
	
	if compression is not None:
		hdu =  pyfits.CompImageHDU(numarray, compression_type = compression)
	else:
		hdu = pyfits.PrimaryHDU(numarray)
	
	hdu.scale('int16', '', bzero=32768)
	hdu.writeto(outfile)


def main():
	for infile in glob('data/scans_244/*.tif'):
		filename = ''.join(os.path.basename(infile).split('.')[0:-1])
		
		outfile = 'data/fits/' + filename + '.fits'
		if exists(outfile):
			continue

		sys.stdout.write('Converting file {} to {}\n'.format(infile, outfile))
		sys.stdout.flush()

		tifftofits(infile, outfile)


if __name__ == '__main__':
	main()
