#!/usr/local/bin
# insert_keywords.py
# Jure Skvarc, May 2000
# A python program which inserts and modifies needed keywords into FITS 
# header of TASS images
# Also renames files to get .fts extension

from string import *
from sys import *
import os
import re
import fitsblink

# ========================================================================
#  Determine exposure time by measuring the median value of
#  pixels in image center.  
# ========================================================================
def getcentermedian(name, xmid, ymid):
    if fitsblink.load_image(name, 0) < 0:
        stderr.write('Error loading the image')
	exit()
    v = []
    n = 0
    for j in range(-50, 50):
        for i in range(-50, 50):
             v.append(fitsblink.Video_point(0, xmid + i, ymid + j))
             n = n + 1
    v.sort()
    fitsblink.Erase_image(0)
    return v[n / 2]




imagenames = '^H.*'
# Fitsblink must be started with option -s to know it is in script mode
arguments = ["fitsblink", "-s"] #  Define the command line tokens
argc = len(arguments)          
args = fitsblink.string_array(argc + 1) #  Create an array of chars
#  Put arguments into array
for i in range(argc):
    fitsblink.string_set(args, i, arguments[i])

fitsblink.string_set(args, argc, "")
# Start fitsblink and initialize graphic interface
fitsblink.main0(argc, args)


#  Get a list of all files
files = os.listdir('.')
#  Compiled regular expression
imagere = re.compile(imagenames)
outfile = open('keywords.fits', 'w')
for a in files:
    if imagere.search(a) != None:
    	if os.path.isfile(a):
            # Create new file name
            name = join(split(a, '.'), '-') + '.fts'
	    #name = a
	    print name
            keywords = getFITSkeywords(a)
	    try:
		dateobs = keywords['DATE-OBS'] + 'T' + keywords['UT']
	    except:
		stderr.write('File %s has missing DATE-OBS or UT keywords' % (a))
	    # Rename the file
	    os.rename(a, name)
            #  Pixel size (see TASS technical note 64)
            if 'I' in keywords['FILTER']:
		pixelsize = 7.66 / 3600
		threshold = 10000
            else:
		pixelsize = 7.74 / 3600
		threshold = 8000
	    outfile.write(name + '\n')
	    outfile.write('CTYPE1 TSTRING RA---TAN insert_keywords\n')
	    outfile.write('CTYPE2 TSTRING DEC--TAN insert_keywords\n')
	    outfile.write('CRVAL1 TDOUBLE %f insert_keywords\n' % (float(keywords['CRVAL2'])))
	    outfile.write('CRVAL2 TDOUBLE %f insert_keywords\n' % (float(keywords['CRVAL1'])))
	    outfile.write('CRPIX1 TDOUBLE %f insert_keywords\n' % ((float(keywords['NAXIS1']) / 2)))
	    outfile.write('CRPIX2 TDOUBLE %f insert_keywords\n' % (float(keywords['NAXIS2']) / 2))
	    outfile.write('CDELT1 TDOUBLE %f insert_keywords\n' % (pixelsize))
	    outfile.write('CDELT2 TDOUBLE %f insert_keywords\n' % (pixelsize))
	    outfile.write('IMAGETYP TSTRING object insert_keywords\n')
	    #  Determine exposure time by measuring the median value of
	    #  pixels in image center.  For values < 10000 say 15 seconds
	    #  for values > 10000 say 150 seconds
	    v = getcentermedian(name, int(keywords['NAXIS1']) / 2, int(keywords['NAXIS2']) / 2)
	    print v
            if v < threshold:
		exposure = 15
	    else:
		exposure = 150
	    outfile.write('EXPOSURE TFLOAT %.2f insert_keywords\n' % (exposure))
	    outfile.write('EXPTIME TFLOAT %.2f insert_keywords\n' % (exposure))
	    outfile.write('END\n')
outfile.close()



