#!/usr/local/bin
# center_median.py
# Jure Skvarc, May 2000
# A python program which calculates median pixel value in the 
# central 100x100 region
from string import *
from sys import *
import os
import re
import fitsblink

# ========================================================================
#  This function returns, given a file name of a FITS file, a dictionary
#  of (keyword, value) pairs.  END keyword is not returned
# ========================================================================
def getFITSkeywords(file):
    fp = open(file)
    kw = {}
    while 1:
        line = fp.read(80)
	if len(line) < 80: break
	key = strip(line[0:8])
	if key == 'END': break
	valcom = line[9:]
	val = split(valcom, '/')[0]
	kw[key] = val
    fp.close()
    return kw


# ========================================================================
#  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)
for a in files:
    if imagere.search(a) != None:
    	if os.path.isfile(a):
	    keywords = getFITSkeywords(a)
	    v = getcentermedian(a, int(keywords['NAXIS1']) / 2, int(keywords['NAXIS2']) / 2)
	    print a,v
            if v < 10000:
		exposure = 15
	    else:
		exposure = 150

