"""
2011-03: Several "tweaks" on old calibrations are so bad that we want
to redo at least those calibrations.  This processor locates the
affected scans and clears their calibrations so they will be redone
at the next recalibration.
"""

import os

from gavo import api
from gavo import base
from gavo.helpers import HeaderProcessor, procmain

import resetheader

class ResetPlease(base.ExecutiveAction):
	pass


class BotchedFinder(HeaderProcessor):

	checkedHeaderFields = [
		"AP_0_1", "AP_0_2", "AP_0_3",
		"AP_1_0", "AP_1_1", "AP_1_2",
		"AP_2_0", "AP_2_1", "AP_3_0 ",
		"BP_0_1", "BP_0_2", "BP_0_3",
		"BP_1_0", "BP_1_1", "BP_1_2",
		"BP_2_0", "BP_2_1", "BP_3_0 ",]
	coeffLimit = 0.05

	def process(self, srcName):
		hdr = self.getPrimaryHeader(srcName)
		try:
			for name in self.checkedHeaderFields:
				if abs(hdr[name])>self.coeffLimit:
					raise ResetPlease()
		except KeyError:
			# probably uncalibrated, ignore
			pass
		except ResetPlease:
			print "\nResetting %s...\n"%srcName
			resetheader.process(srcName)
			cacheName = self._makeCacheName(srcName)
			if os.path.exists(cacheName):
				os.rename(cacheName, cacheName+".botched")


if __name__=="__main__":
  procmain(BotchedFinder, "lswscans/res/positions", "import")

