#!/usr/bin/env python

import os
import sys
import recombyhand
from pyraf import iraf


def getxy(band, ifwhm, zline):

    iraf.digiphot(_doprint = 0)
    iraf.apphot(_doprint = 0)
    iraf.unlearn('phot')
    
    if ifwhm < 5:
        iraf.apphot.centerpars.cbox = 5
    else:
        iraf.apphot.centerpars.cbox = ifwhm

    iraf.apphot.fitskypars.dannulu = 2 * ifwhm
    iraf.apphot.datapars.datamin = -1000
    iraf.apphot.datapars.readnoise = 30
    iraf.apphot.datapars.epadu = 5
    iraf.apphot.photpars.aperture = 2 * ifwhm
    iraf.apphot.fitskypars.annulus = 3 * ifwhm

    SCRIPTDIR = os.path.realpath(os.path.dirname(sys.argv[0]))

    xcoo = []
    ycoo = []
    wflag = 0
    for line in zline:
        fdir = (line[:-1].split())[0]
        fnum = (line[:-1].split())[1]
        # yymmdd = (fdir.split('ffiles'))[0]
        fname = '../' + fdir + '/' + band + 'f' + fnum + '.fits'

        if not os.access(fname, os.F_OK):
            print '%s was not found' % fname
        else:
            cprog = 'badfill'
            os.system("%s/%s %s recomtmp.fits" % (SCRIPTDIR, cprog, fname))
            v = recombyhand.phot2v('recomtmp.fits')
            os.remove('recomtmp.fits')
        
            if v[0] == 'INDEF' or v[1] == 'INDEF':
                print '%s was not measured' % fname
                wflag = 1
                break 
            else:
                xcoo.append(float(v[0]))
                ycoo.append(float(v[1]))    

    if wflag == 1:
        print 'measurement was failed.'
        print 'choose another star'
        sys.exit()
    else:
        for i in range(1, len(xcoo)):
            xcoo[i] = (xcoo[i] - xcoo[0]) * 0.45
            ycoo[i] = (ycoo[i] - ycoo[0]) * -0.45
        xcoo[0] = 0
        ycoo[0] = 0

    return xcoo, ycoo
    

def zerocorr(type, band, ifwhm):


    aline = []
    zline = []

    if type == 'img':

        f = open(band+'imgrecom.list')
        for line in f:
            aline.append(line[:-1])
            v = line[:-1].split()
            if v[3] == '0.0' and v[4] == '0.0':
                zline.append(line[:-1])
        f.close()

        xcoo, ycoo = getxy(band, ifwhm, zline)

        fo = open('comlist.tmp', 'w')
        j = -1
        for i in range(len(aline)):
            v = aline[i].split()
            if v[3] == '0.0' and v[4] == '0.0':
                j += 1
            print >> fo, '%s %s %s %.1f %.1f %s' % (v[0], v[1], v[2], float(v[3])+xcoo[j], float(v[4])+ycoo[j], v[5])
        fo.close()

        os.rename('comlist.tmp', band+'imgrecom.list')

    else:
        
        f = open(band+'polrecom.list')
        for line in f:
            aline.append(line[:-1])
            v = line[:-1].split()
            if v[3] == '0.0' and v[4] == '0.0' and v[6] == '0.':
                zline.append(line[:-1])
        f.close()

        xcoo, ycoo = getxy(band, ifwhm, zline)

        fo = open('comlist.tmp', 'w')
        j = -1
        for i in range(len(aline)):
            v = aline[i].split()
            if v[3] == '0.0' and v[4] == '0.0' and v[6] == '0.':
                j += 1
            print >> fo, '%s %s %s %.1f %.1f %s %s' % (v[0], v[1], v[2], float(v[3])+xcoo[j], float(v[4])+ycoo[j], v[5], v[6])
        fo.close()
    
        os.rename('comlist.tmp', band+'polrecom.list')
   


if __name__ == "__main__":
    
    argvs = sys.argv
    argc = len(argvs)

    ifwhm = 4

    if argc < 2 or argvs[1] == '--help':
        print 'usage: zeroshiftcorr.py [img|pol] [j|h|k] -fwhm=[float] (optional) '
        sys.exit()

    if argvs[1] != 'img' and argvs[1] != 'pol':
        print 'typo?'
        print 'usage: zeroshiftcorr.py [img|pol] [j|h|k]'
        sys.exit()

    if argvs[2] != 'j' and argvs[2] != 'h' and argvs[2] != 'k':
        print 'typo?'
        print 'usage: zeroshiftcorr.py [img|pol] [j|h|k]'
        sys.exit()

    if argc > 3 and argvs[3] == '-fwhm=':
        ifwhm = float(argvs[3][6:])

    if os.access(argvs[2]+argvs[1]+'recom.list', os.F_OK):
        zerocorr(argvs[1], argvs[2], ifwhm)
    else:
        print argvs[2]+argvs[1]+'recom.list not found'
        sys.exit()


        
        
