# For historical reasons, there were some plates that declared -SIP
# in the projection header but then provide no polynomials.	This
# confuses Aladin.	This script finds problematic plates and fixes
# their projection headers.

from gavo import api


class ProjectionFixer(api.ImmediateHeaderProcessor):
	def _isProcessed(self, srcName, hdr):
		if not "CTYPE1" in hdr:
			# there's no calibration at all
			return True
		if not hdr["CTYPE1"].endswith("SIP"):
			# I'm not claiming to have polynoms
			return True
		if "A_ORDER" in hdr:
			# I'm claiming to have polynoms, and I have them
			return True
		
		# we need to fix CTYPEx
		return False

	def _changeHeader(self, srcName, hdr):
		if hdr["CTYPE1"].endswith("-SIP"):
			hdr["CTYPE1"] = hdr["CTYPE1"][:-4]
		else:
			raise Exception("Oops: %s"%hdr["CTYPE1"])

		if hdr["CTYPE2"].endswith("-SIP"):
			hdr["CTYPE2"] = hdr["CTYPE2"][:-4]
		else:
			raise Exception("Oops: %s"%hdr["CTYPE2"])

		return hdr

if __name__=="__main__":
		res = api.procmain(ProjectionFixer, "lswscans/res/positions", "import")
