#!/usr/bin/env python

#
# 2014-1-22 hdr.has_key('keyword') changed to 'keyword' in hdr 
#

import sys
import os
import pyfits
import warnings
import re
warnings.simplefilter('ignore', DeprecationWarning)

def mklog():


    numarr3 = []
    jnumarr = []
    hnumarr = []
    knumarr = []
    for fname in os.listdir('../rawdata'):
        if re.search('fits', fname):
            fitsname = fname
            fnum = fitsname[8:12]
            numarr3.append(fnum)
            if fname.startswith('j'):
                jnumarr.append(fnum)
            if fname.startswith('h'):
                hnumarr.append(fnum)
            if fname.startswith('k'):
                knumarr.append(fnum)

    pref = fitsname[1:7]
    if fitsname[-2:] == 'ic':
        etype = '.fits.ic'
        hdunum = 1
    elif fitsname[-2:] == 'fz':
        etype = '.fits.fz'
        hdunum = 1
    else:
        etype = '.fits'
        hdunum = 0

    numarr = list(set(numarr3))
    numarr.sort()

    fo = open('obslog', 'w')

    print >> fo, 'FRAME OBJECT ITIME RA_OFF DEC_OFF DATE_UTC TIME_UTC DATE_LT TIME_LT JD EPOCH RA DEC AIRMASS'

    for i in range(len(numarr)):

        jfits = '../rawdata/j' + pref + '_' + numarr[i] + etype
        hfits = '../rawdata/h' + pref + '_' + numarr[i] + etype
        kfits = '../rawdata/k' + pref + '_' + numarr[i] + etype

        eflag = 0
        if not os.access(jfits, os.R_OK):
            print 'Cannot read %s' % jfits
            eflag += 1
        if not os.access(hfits, os.R_OK):
            print 'Cannot read %s' % hfits
            eflag += 1
        if not os.access(kfits, os.R_OK):
            print 'Cannot read %s' % kfits
            eflag += 1
            
        if os.access(jfits, os.R_OK):
            hdr = pyfits.getheader(jfits, hdunum)
        elif os.access(hfits, os.R_OK):
            hdr = pyfits.getheader(hfits, hdunum)
        elif os.access(kfits, os.R_OK):
            hdr = pyfits.getheader(kfits, hdunum)

        if eflag != 3:
            if 'JD' in hdr:
                jdkey = hdr['JD']
            elif 'MJD' in hdr:
                jdkey = hdr['MJD']

            if str(hdr['EXPOS']).endswith('.0'):
                itime = str(hdr['EXPOS'])[:-1]
            else:
                itime = str(hdr['EXPOS'])

            if 'RA' in hdr and 'RA_OFF' in hdr:
                print >> fo, numarr[i], hdr['OBJECT'], itime, hdr['RA_OFF'], hdr['DEC_OFF'], hdr['DATE_UTC'],hdr['TIME_UTC'], hdr['DATE_LT'], hdr['TIME_LT'], jdkey, hdr['EPOCH'], hdr['RA'], hdr['DEC'], hdr['AIRMASS']
            else:
                print >> fo, numarr[i], hdr['OBJECT'], itime, '0', '0'


    fo.close()


if __name__ == "__main__":

    if not os.path.isdir('../rawdata'):
        print 'no ../rawdata directory'
        sys.exit()

    mklog()
        
