#!/usr/bin/env python

import os
import sys


def correct(myflat, newname):

    SCRIPTDIR = os.path.realpath(os.path.dirname(sys.argv[0]))
    cprog = 'mkcorrflat'
    
    for band in ['j', 'h', 'k']:
        os.system('ln -s %s/lib/%scflat.fits %scflat.fits' % (SCRIPTDIR, band, band))
        os.system('ln -s %s/lib/%smflat.fits %smflat.fits' % (SCRIPTDIR, band, band))
        os.system("%s/%s %s%s.fits %s%s.fits" % (SCRIPTDIR, cprog, band, myflat, band, newname))
        os.system('rm %scflat.fits' % band)
        os.system('rm %smflat.fits' % band)


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

    if argc < 3:
        print 'usage: corrflat.py myflat newname'
        print 'corrflat.py creates [j|h|k]newname.fits from [j|h|k]myflat.fits'
        sys.exit()

    myflat = argvs[1]

    flag = 0
    if not os.path.exists('j'+myflat+'.fits'):
        print 'j'+myflat+'.fits not found'
        flag += 1
    if not os.path.exists('h'+myflat+'.fits'):
        print 'h'+myflat+'.fits not found'
        flag += 1
    if not os.path.exists('k'+myflat+'.fits'):
        print 'k'+myflat+'.fits not found'
        flag += 1

    if flag != 0:
        sys.exit()

    newname = argvs[2]

    correct(myflat, newname)



