"""
Some ROSAT file headers had some typos in them.

This processor fixes them; it is written (and should remain that way)
that changes are applied immediately, but that files are only touched
if they're actually broken.
"""

import gzip
import os
import shutil
import tempfile

import pyfits

from gavo import api
from gavo.utils import fitstools

# fixer functions get a pyfits header and return False if they didn't change
# it, 1 if they did.

def fixCTYPE(hdr):
	rtval = False
	if not "CTYPE2" in hdr:
		return rtval
		
	if hdr["CTYPE2"]=="DEC-TAN":
		hdr["CTYPE2"] = "DEC--TAN"
		rtval = True
	if hdr["CTYPE1"]=="RA--TAN":
		hdr["CTYPE1"] = "RA---TAN"
		rtval = True
	return rtval
	
class HeaderFixer(api.FileProcessor):

	def process(self, srcName):
		with gzip.open(srcName) as f:
			hdr = fitstools.readPrimaryHeaderQuick(f)
		if fixCTYPE(hdr):
			handle, tmpName = tempfile.mkstemp(
				prefix="headerfixer", dir=os.path.dirname(srcName))
			dest = gzip.GzipFile(fileobj=os.fdopen(handle, "w"))
			with gzip.open(srcName) as input:
				fitstools.replacePrimaryHeader(input, hdr, dest)
			dest.close()
			shutil.copystat(srcName, tmpName)
			os.rename(tmpName, srcName)
				
			
if __name__=="__main__":
	api.procmain(HeaderFixer, "rosat/q", "import_images")
