"""
A quick hack to resurrect FITS header that were destroyed by a
1-too-long card serialization bug, as it has occurred before.
"""
import re
import sys

from gavo.utils import fitstools
from gavo.utils import pyfits

def alignCards(header):
	"""returns a fixed version of a FITS header.

	This is for when alignment was botched again by a conspiracy between my
	code and changes in pyfits.

	This makes sure that each 79th char is empty and each 0th char is filled
	for each card (basically).  Only one level of indenting or de-denting is
	allowed per card.
	"""
	headerChars = list(header)
	for cardInd in range(len(header)/80):
		firstChar = headerChars[cardInd*80]
		if not re.match(r"[A-Z]", firstChar):
			if not header[cardInd*80:(cardInd+1)*80].strip():
				# empty lines are ok
				continue
			if headerChars[cardInd*80+1]==' ':
				raise Exception("double dedent '%s'??!"%
					"".join(headerChars[cardInd*80:cardInd*80+20]))
			print "dedent", repr("".join(headerChars[cardInd*80:cardInd*80+10]))
			del headerChars[cardInd*80]

		lastChar = headerChars[cardInd*80+79]
		# this can have false alarms when the cards are completely full.
		# there's little I can to about this, if it hits you, you may
		# need to intervene manually
		if lastChar!=' ':
			if not headerChars[cardInd*80+78]==' ':
				raise Exception("double indent, '%s'??!"%
					"".join(headerChars[cardInd*80+78:cardInd*80+90]))
			print "indent", repr("".join(headerChars[cardInd*80+70:cardInd*80+90]))
			headerChars.insert(cardInd*80+79, ' ')

	return "".join(headerChars)


fitsName = sys.argv[1]
with open(fitsName) as f:
	oldHdr = fitstools.readHeaderBytes(f)
newHdr = alignCards(oldHdr)
if len(oldHdr)!=len(newHdr):
	raise Exception("Header changed size %s %s?!"%(len(oldHdr), len(newHdr)))
with open(fitsName, "r+") as targetFile:
	targetFile.seek(0)
	targetFile.write(newHdr)
hdus = pyfits.open(fitsName)
hdus.verify('exception')
