#!/usr/bin/python
# A DaCHS processor for inverting PL&TS images that have a "bright"
# background.  I have no idea why some of them are inverted an some aren't.
# Also, as usual, there's sometimes random junk at the end of files which
# will later irritate pyfits.  We're doing away with that, too.

import os

import pyfits

from gavo import api
from gavo.utils import fitstools


BLOCKSIZE = 2880

def _getExpectedSize(srcName):
	with open(srcName) as f:
		hdr = fitstools.readPrimaryHeaderQuick(f)
		f.seek(0)
		hdrLength = len(fitstools.readHeaderBytes(f))

	np1, np2 = hdr.get("NAXIS1"), hdr.get("NAXIS2")
	expectedSize = abs(np1*np2*hdr.get("BITPIX")/8)
	expectedDataBlocks = (
		expectedSize/BLOCKSIZE+(not not expectedSize%BLOCKSIZE))
	return expectedDataBlocks*BLOCKSIZE+hdrLength


class Inverter(api.FileProcessor):
	def process(self, srcName):
		expected = _getExpectedSize(srcName)

		if os.path.getsize(srcName)>expected:
			with open(srcName) as f:
				f.seek(expected)
				junk = f.read()
				# I have no idea what that junk might have been once
				if not set(junk)<set('\0\xff\x7f\x80'):
					raise api.CannotComputeHeader(
						"Hu: unexpected bytes in junk: %s"%set(junk))

				with open(srcName, "a") as f:
					f.truncate(expected)

		im = pyfits.open(srcName)
		if sum(im[0].data.ravel()[:100000])/100000.<30000:
			return  # dark background, all is fine

		im[0].data = 65535-im[0].data
		im[0].scale("int16", "", bzero=32768)
		im.writeto("zw.fits")
		im.close()
		os.rename("zw.fits", srcName)


if __name__=="__main__":
	api.procmain(Inverter, "plts/q.rd", "import_pls")
