#!/usr/bin/env python

import os
import shutil
import sys
import math
import re
from pyraf import iraf


#
# this getgmap is different from one in tripol
#

class readgdb():

    def __init__(self):

        fdb = open('getgmap.db')
        for ii, gline in enumerate(fdb):
            gvalue = gline[:-1].split()
            if ii == 2:
                self.xrefmean = gvalue[1]
            if ii == 3:
                self.yrefmean = gvalue[1]
            if ii == 4:
                self.xmean = gvalue[1]
            if ii == 5:
                self.ymean = gvalue[1]
            if ii == 12:
                self.rot = gvalue[1]
            if ii == 14:
                self.xrms = gvalue[1]
            if ii == 15:
                self.yrms = gvalue[1]
            if ii == 25:
                self.aa = gvalue[0]
                self.dd = gvalue[1]
            if ii == 26:
                self.bb = gvalue[0]
                self.ee = gvalue[1]
            if ii == 27:
                self.cc = gvalue[0]
                self.ff = gvalue[1]
        fdb.close()


def getedge():

    xarr = [1, 1024]
    yarr = [1, 1024]
    gm = readgdb()

    xarr.append(float(gm.aa) + float(gm.bb) + float(gm.cc))
    xarr.append(float(gm.aa) + float(gm.bb) + float(gm.cc) * 1024)
    xarr.append(float(gm.aa) + float(gm.bb) * 1024 + float(gm.cc))
    xarr.append(float(gm.aa) + float(gm.bb) * 1024 + float(gm.cc) * 1024)

    yarr.append(float(gm.dd) + float(gm.ee) + float(gm.ff))
    yarr.append(float(gm.dd) + float(gm.ee) + float(gm.ff) * 1024)
    yarr.append(float(gm.dd) + float(gm.ee) * 1024 + float(gm.ff))
    yarr.append(float(gm.dd) + float(gm.ee) * 1024 + float(gm.ff) * 1024)

    xmin = min(xarr)
    xmax = max(xarr)
    ymin = min(yarr)
    ymax = max(yarr)

    #return xmin, xmax, ymin, ymax, gm.aa, gm.dd, gm.xrms, gm.yrms
    return xmin, xmax, ymin, ymax, float(gm.xrms), float(gm.yrms)


def pregeo(band, ufwhm, uellip, minsep, theta):

    fo = open(band+'xyoff.txt', 'w')
    f = open(band+'fwhm.txt')

    minnum = 1000
    maxnum = 0
    for line in f:

        v = line[:-1].split()

        xoff = ( float(v[1]) * math.cos(theta) + float(v[2]) * math.sin(theta) ) / 0.45
        yoff = ( float(v[1]) * math.sin(theta) - float(v[2]) * math.cos(theta) ) / 0.45
        fwhm = float(v[3])
        ellip = float(v[4])

        if os.access(v[0]+'.mag', os.R_OK):

            if fwhm <= ufwhm and ellip <= uellip:
                snum = 0
                f1 = open(v[0]+'.mag')
                for line1 in f1:
                    v1 = line1[:-1].split()            
                    if float(v1[0]) >= minsep and v1[5] == '0' and v1[6] == '0' and v1[7] == '0':
                        snum = snum + 1
                f1.close()

                if snum > 0:
                    print >> fo, '%s %.1f %.1f %d' % (v[0], xoff, yoff, snum)
                    if snum > maxnum:
                        maxnum = snum
                    elif snum < minnum:
                        minnum = snum
                else:
                    print '%s does not meet the conditions of minsep and cier=0 & sier=0 & pier=0' % v[0]

            else:
                print '%s does not meet your conditions for fwhm and/or ellipticity.' % v[0]

        else:
            print '%s.mag not found' % v[0]

    f.close()
    fo.close()

    return minnum, maxnum


def trimcoo(imgref, imgin, timgref, timgin, dx, dy, trimon):

    if trimon == 1:

        '''
        if dx > 0:
            x0 = 0
            x1 = 1024 - dx
        else:
            x0 = -1 * dx
            x1 = 1024

        if dy > 0:
            y0 = 0
            y1 = 1024 - dy
        else:
            y0 = -1 * dy
            y1 = 1024
        '''

        # for a reference list

        x0 = max(0, -1 * dx)
        x1 = min(1024, 1024 - dx) 

        y0 = max(0, -1 * dy)
        y1 = min(1024, 1024 - dy) 

        refnum = 0
        fo = open(timgref, 'w')
        f = open(imgref)
        for line in f:
            v = line[:-1].split()
            if float(v[1]) > x0 and float(v[1]) < x1 and float(v[2]) > y0 and float(v[2]) < y1 and v[5] == '0' and v[6] == '0' and v[7] == '0':
                refnum += 1
                print >> fo, line[:-1]
        f.close()
        fo.close()

        # print 'ref'
        # print '%d : %d  %d : %d' % (x0, x1, y0, y1)


        # for an input list

        '''
        if dx > 0:
            x0 = dx
            x1 = 1024
        else:
            x0 = 0
            x1 = 1024 + dx
            
        if dy > 0:
            y0 = dy
            y1 = 1024
        else:
            y0 = 0
            y1 = 1024 + dy
        '''

        x0 = max(0, dx)
        x1 = min(1024, 1024 + dx) 

        y0 = max(0, dy)
        y1 = min(1024, 1024 + dy) 

        innum = 0
        fo = open(timgin, 'w')
        f = open(imgin)
        for line in f:
            v = line[:-1].split()
            if float(v[1]) > x0 and float(v[1]) < x1 and float(v[2]) > y0 and float(v[2]) < y1 and v[5] == '0' and v[6] == '0' and v[7] == '0':
                print >> fo, line[:-1]
                innum += 1
        f.close()
        fo.close()

        # print 'in'
        # print '%d : %d  %d : %d' % (x0, x1, y0, y1)


    else:

        refnum = 0
        fo = open(timgref, 'w')
        f = open(imgref)
        for line in f:
            v = line[:-1].split()
            if v[5] == '0' and v[6] == '0' and v[7] == '0':
                refnum += 1
                print >> fo, line[:-1]
        f.close()
        fo.close()
        
        innum = 0
        fo = open(timgin, 'w')
        f = open(imgin)
        for line in f:
            v = line[:-1].split()
            if v[5] == '0' and v[6] == '0' and v[7] == '0':
                print >> fo, line[:-1]
                innum += 1
        f.close()
        fo.close()


    return refnum, innum



def sparsematch(timgref, timgin, xoff, yoff, searchrad):

    xc0 = []
    yc0 = []
    mag0 = []
    f = open(timgref)
    for line in f:
        v = line[:-1].split()
        xc0.append(float(v[1]))
        yc0.append(float(v[2]))
        mag0.append(float(v[3]))
    f.close()

    xc = []
    yc = []
    mag = []
    f = open(timgin)
    for line in f:
        v = line[:-1].split()
        xc.append(float(v[1]) - xoff)
        yc.append(float(v[2]) - yoff)
        mag.append(float(v[3]))
    f.close()

    mnum, dmag = getmatch(xc0, yc0, mag0, xc, yc, mag, xoff, yoff, searchrad) 

    return mnum




def getgmap(band, ufwhm, uellip, searchrad, minsep, urms, lstarnum):

    trimon = 1

    print ''

    iraf.xyxymatch.unlearn()
    iraf.geomap.unlearn()

    iraf.xyxymatch.xmag = 1
    iraf.xyxymatch.ymag = 1
    iraf.xyxymatch.xcolumn = 2
    iraf.xyxymatch.ycolumn = 3
    iraf.xyxymatch.xrcolumn = 2
    iraf.xyxymatch.yrcolumn = 3
    iraf.xyxymatch.separation = minsep

    xmin = 1
    xmax = 1024
    ymin = 1
    ymax = 1024

    fot = open(band + 'transummary.txt', 'w')
    fog = open(band + 'tran.txt', 'w')
    tfname = []
    xarr = []
    yarr = []
    rnum = []
    inum = []

    # need a progress bar here : ToDo 
    izero = 0
    timgref = ''
    f = open(band + 'xyoff.txt')
    for line in f:
        v = line[:-1].split()
        if v[0][:2] == '0.':
            imgdisp = v[0][2:]
        else:
            imgdisp = v[0]

        if izero == 0:

            imgref = v[0]+'.mag'
            timgref = v[0]+'.tmag'
            print >> fog, "%s 0.0 0.0 1.0 0.0 0.0 0.0 1.0 512 512 512 512 0.0 0.0 999" % v[0]
            print 'frame     rot      x (rms)       y (rms)  num  (rnum/inum)  dx    dy'
            print '%s : reference frame ' % imgdisp
            print >> fot, 'frame     rot      x (rms)       y (rms)  num  (rnum/inum)  dx    dy'
            print >> fot, '%s : reference frame ' % imgdisp
            izero = 1

        else:

            imgin = v[0]+'.mag'
            timgin = v[0]+'.tmag'

            xoff = float(v[1])
            yoff = float(v[2])

            refnum, innum = trimcoo(imgref, imgin, timgref, timgin, xoff, yoff, trimon)

            #print v[0], refnum, innum
            if refnum != 0 and innum != 0: 
                nmatch = 35
                if os.access('match.txt', os.R_OK):
                    os.remove('match.txt')
                iraf.xyxymatch(timgin, timgref, 'match.txt', 1, nmatch=nmatch, verbose='no')

                mnum = 0
                fin = open('match.txt')
                for line in fin:
                    if not line.startswith('#') and re.search('\S',line[:-1]):
                        mnum += 1
                fin.close()

                while mnum < 0.5 * min(refnum, innum) and nmatch < 61:

                    nmatch += 5

                    # print 'xyxymatch again with nmatch=%d for %s' % (nmatch, v[0])
                    if os.access('match.txt', os.R_OK):
                        os.remove('match.txt')
                    iraf.xyxymatch(timgin, timgref, 'match.txt', 1, nmatch=nmatch, verbose='no')

                    mnum = 0
                    fin = open('match.txt')
                    for line in fin:
                        if not line.startswith('#') and re.search('\S',line[:-1]):
                            mnum += 1
                    fin.close()

            else:
                print 'no common stars in the overlapped area of %s and %s' % (imgref[:-4], v[0])
                print 'reference = %d, input = %d' % (refnum, innum) 
                continue 

            if mnum == 0:
                smnum = sparsematch(timgref, timgin, xoff, yoff, searchrad)
                if smnum == 0:
                    print 'no star was matched for %s' % imgdisp
                    #os.remove(timgref)
                    os.remove(timgin)
                    os.remove('match.txt')
                    continue 
                else:
                    mnum = smnum

            else:
                fout = open('getgmap.coo', 'w')
                fin = open('match.txt')
                # 0:Xref 1:Yref 2:Xin 3:Yin
                for line in fin:
                    if not line.startswith('#') and re.search('\S',line[:-1]):
                        vin = line[:-1].split()
                        print >> fout, vin[2], vin[3], vin[0], vin[1]
                fin.close()
                fout.close()
                #shutil.move('match.txt', v[0]+'.match')
                os.remove('match.txt')

            #os.remove(timgref)
            os.remove(timgin)

            #
            # xin, yin, xref, yref in columnd 1 through 4 in getgmap.coo at this stage
            # because we need to know how the corners of a input frame move 
            # in the reference coordinate system at the 1st stage 
            #

            tfname.append(v[0])
            xarr.append(v[1])
            yarr.append(v[2])
            rnum.append(refnum)
            inum.append(innum)

            if mnum >= lstarnum:

                if mnum == 1:
                    fitgeom = 'shift'
                    # if the number of matched stars is one, only shift will be calculated 
                else:
                    fitgeom = 'rotate'
                    # if the number of matched stars is more than one, shift and rotate will be calculated 

                iraf.geomap('getgmap.coo', 'getgmap.db', xmin=1, xmax=1024, ymin=1, ymax=1024,
                            fitgeometry=fitgeom, maxiter=3, verbose='no', interactive='no')

                x0, x1, y0, y1, xrms, yrms = getedge()

                if xrms <= urms and yrms <= urms:
                    if x0 < xmin:
                        xmin = x0
                    if x1 > xmax:
                        xmax = x1
                    if y0 < ymin:
                        ymin = y0
                    if y1 > ymax:
                        ymax = y1

                shutil.move('getgmap.coo', v[0]+'.coo')
                os.remove('getgmap.db')
            
                # print '%.1f %.1f : %.1f %.1f' % (aa, xoffarr[i]-xdz, dd, yoffarr[i]-ydz)
                # xzeroarr.append(-1 * aa + xoffarr[i])
                # yzeroarr.append(-1 * dd + yoffarr[i])


    f.close() 
    os.remove(band + 'xyoff.txt')
    if os.access(timgref, os.R_OK):
        os.remove(timgref)

    if len(tfname) == 0:
        print 'No frame was matched.'
        fog.close()
        fot.close()
        return 1

    xzero = math.floor(xmin) * -1
    yzero = math.floor(ymin) * -1
    xsize = xzero + math.ceil(xmax)
    ysize = yzero + math.ceil(ymax)
    xc1 = xsize - 1024
    xc2 = 1024
    yc1 = ysize - 1024
    yc2 = 1024

    fo = open(band+'recominfo', 'w')
    print >> fo, "%d %d %d %d %d %d %d %d" % (xzero, yzero, xsize, ysize, xc1, xc2, yc1, yc2)
    fo.close()


    # the order reversed 
    # xref, yref, xin, yin in columnd 1 through 4 in getgmap.coo at this stage

    for i in range(len(tfname)):
        if tfname[i][:2] == '0.':
            imgdisp = tfname[i][2:]
        else:
            imgdisp = tfname[i]

        f = open(tfname[i]+'.coo')
        fo = open('getgmap.coo', 'w')
        mnum = 0
        for line in f:
            v = line[:-1].split()
            print >> fo, '%.2f %.2f %.2f %.2f' % (float(v[2])+xzero, float(v[3])+yzero, float(v[0])+xzero, float(v[1])+yzero)
            mnum += 1
        f.close()
        fo.close()

        os.remove(tfname[i]+'.coo')

        if mnum == 1:
            fitgeom = 'shift'
        elif mnum > 1:
            fitgeom = 'rotate'
            
        iraf.geomap('getgmap.coo', 'getgmap.db', xmin=1, xmax=xsize, ymin=1, ymax=ysize, 
                     fitgeometry=fitgeom, maxiter=3, verbose='no', interactive='no')
        gm = readgdb()

        os.remove('getgmap.coo')
        os.remove('getgmap.db')

        print >> fog, "%s %s %s %s %s %s %s %s %s %s %s %s %s %s %d" % (tfname[i], gm.rot, gm.aa, gm.bb, gm.cc, gm.dd, gm.ee, gm.ff, gm.xrefmean, gm.yrefmean, gm.xmean, gm.ymean, gm.xrms, gm.yrms, mnum)

        grot = float(gm.rot)
        if grot > 180:
            grot = grot - 360

        print '%s %6.2f %6.1f (%.2f) %6.1f (%.2f) %3d  (%d/%d)    %5.1f %5.1f' % (imgdisp, grot, float(gm.aa), float(gm.xrms), float(gm.dd), float(gm.yrms), mnum, rnum[i], inum[i], float(gm.aa) - float(xarr[i]), float(gm.dd) - float(yarr[i]))
        sys.stdout.flush()
        print >> fot, '%s %6.2f %6.1f (%.2f) %6.1f (%.2f) %3d  (%d/%d)    %5.1f %5.1f' % (imgdisp, grot, float(gm.aa), float(gm.xrms), float(gm.dd), float(gm.yrms), mnum, rnum[i], inum[i], float(gm.aa) - float(xarr[i]), float(gm.dd) - float(yarr[i]))


    # end of for i in range(len(fname)):

    fog.close()
    fot.close()

    return 0



def zeroshiftadjust(zeroarr):
    
    n = len(zeroarr)
    zeroarr.sort()
    if n % 2 == 0:
        zmed = 0.5 * (zeroarr[n/2-1] + zeroarr[n/2])
    else:
        zmed = zeroarr[n/2]
        
    return zmed


def getmatch(xc0, yc0, mag0, xc, yc, mag, xoff, yoff, searchrad):

    mxc1 = []
    myc1 = []
    mmg1 = []
    mxc0 = []
    myc0 = []
    mmg0 = []
    srad2 = searchrad * searchrad
    for i in range(len(xc0)):

        flag = 0
        for j in range(len(xc)):
            rr = (xc0[i] - xc[j]) * (xc0[i] - xc[j]) + (yc0[i] - yc[j]) * (yc0[i] - yc[j])
            if rr < srad2 and math.fabs(mag0[i] - mag[j]) < 2:
                xt = xc[j]
                yt = yc[j]
                mt = mag[j]
                flag = flag + 1

        if flag == 1:
            mxc1.append(xt)
            myc1.append(yt)
            mmg1.append(mt)
            mxc0.append(xc0[i])
            myc0.append(yc0[i])
            mmg0.append(mag0[i])
    

    if len(mxc1) == 1:
        mnum = 1
        dmag = mmg1[0] - mmg0[0]
        fo = open('getgmap.coo', 'w')
        print >> fo, mxc1[0] + xoff, myc1[0] + yoff, mxc0[0], myc0[0]
        fo.close()
    elif len(mxc1) == 2:
        ddx = math.fabs((mxc1[0] - mxc0[0]) - (mxc1[1] - mxc0[1]))
        ddy = math.fabs((myc1[0] - myc0[0]) - (myc1[1] - myc0[1]))
        if ddx < 1 and ddy < 1:
            fo = open('getgmap.coo', 'w')
            print >> fo, mxc1[0] + xoff, myc1[0] + yoff, mxc0[0], myc0[0]
            print >> fo, mxc1[1] + xoff, myc1[1] + yoff, mxc0[1], myc0[1] 
            fo.close()
            dmag = 0.5 * ((mmg1[0] - mmg0[0]) + (mmg1[1] - mmg0[1]))
            mnum = 2
        else:
            mnum = 0
            dmag = -999
    elif len(mxc1) > 2:
        mnum, dmag = clipave(mxc0, myc0, mmg0, mxc1, myc1, mmg1, xoff, yoff)

    else:
        dmag = -999
        mnum = 0

    return mnum, dmag


def clipave(mxc0, myc0, mmg0, mxc1, myc1, mmg1, xoff, yoff):

    n = len(mxc0)

    dx = []
    dy = []
    for i in range(n):
        dx.append(mxc1[i] - mxc0[i])
        dy.append(myc1[i] - myc0[i])

    dxs = sorted(dx)
    dys = sorted(dy)
    if n % 2 == 0:
        xmed = 0.5 * (dxs[n/2-1] + dxs[n/2])
        ymed = 0.5 * (dys[n/2-1] + dys[n/2])
    else:
        xmed = dxs[n/2]
        ymed = dys[n/2]                                

    xstdev = 0
    ystdev = 0
    for i in range(n):
        xstdev = xstdev + (dx[i] - xmed) * (dx[i] - xmed)
        ystdev = ystdev + (dy[i] - ymed) * (dy[i] - ymed)

    xstdev = math.sqrt(xstdev/n)
    ystdev = math.sqrt(ystdev/n)

    # print 'x1:', xmed, xstdev
    # print 'y1:', ymed, ystdev

    iloop = 0

    while True:
        
        iloop += 1

        cdx = []
        cdy = []
        for i in range(n):
            if math.fabs(dx[i] - xmed) < 3 * xstdev and math.fabs(dy[i] - ymed) < 3 * ystdev:
                cdx.append(dx[i])
                cdy.append(dy[i])

        cdx.sort()
        cdy.sort()
        nc = len(cdx)
        if nc%2 == 0:
            xmed2 = 0.5 * (cdx[nc/2-1] + cdx[nc/2])
            ymed2 = 0.5 * (cdy[nc/2-1] + cdy[nc/2])
        else:
            xmed2 = cdx[nc/2]
            ymed2 = cdy[nc/2]                                

        xstdev = 0
        ystdev = 0
        for i in range(nc):
            xstdev = xstdev + (cdx[i] - xmed2) * (cdx[i] - xmed2)
            ystdev = ystdev + (cdy[i] - ymed2) * (cdy[i] - ymed2)

        xstdev = math.sqrt(xstdev / nc)
        ystdev = math.sqrt(ystdev / nc)

        dxmed = math.fabs(xmed2-xmed)
        dymed = math.fabs(ymed2-ymed)

        if dxmed < 0.1 and dymed < 0.1 and iloop > 3:
            break
        else:
            xmed = xmed2
            ymed = ymed2

    # print 'x2:', xmed, xstdev
    # print 'y2:', ymed, ystdev

    fo = open('getgmap.coo', 'w')
    dmag = 0
    mnum = 0
    for i in range(n):
        # print dx[i], dy[i]
        if math.fabs(dx[i] - xmed) < 3 * xstdev and math.fabs(dy[i] - ymed) < 3 * ystdev:
            dmag = dmag + mmg1[i] - mmg0[i]
            print >> fo, mxc1[i] + xoff, myc1[i] + yoff, mxc0[i], myc0[i]
            mnum = mnum + 1l

    dmag = dmag / mnum
    fo.close()

    return mnum, dmag



def recominfo(band, urms, lstarnum):

    #
    # determine xzero, yzero, xsize, ysize and comarea
    #
    xmin = 2000
    xmax = -2000
    ymin = 2000
    ymax = -2000
    f = open(band + 'tran.txt')
    for line in f:
        value = line[:-1].split()
        xoff = -1 * float(value[2])
        yoff = -1 * float(value[5])
        xrms = float(value[12])
        yrms = float(value[13])
        starnum = int(value[14])
        if xrms <= urms and yrms <= urms and starnum >= lstarnum:
        
            if xoff < xmin:
                xmin = xoff
            if xoff > xmax:
                xmax = xoff
            if yoff < ymin:
                ymin = yoff
            if yoff > ymax:
                ymax = yoff

    f.close()

    if xmin > 0:
        xmin = 0
    if xmax < 0:
        xmax = 0
    if ymin > 0:
        ymin = 0
    if ymax < 0:
        ymax = 0
    
    xzero = math.ceil(xmax)
    yzero = math.ceil(ymax)
    
    print xzero, yzero

    xsize = xzero + 1024 - math.floor(xmin)
    ysize = yzero + 1024 - math.floor(ymin)
    xc1 = 1 + xzero - math.ceil(xmin)
    xc2 = 1 + xzero + 1024 - math.ceil(xmax)
    yc1 = 1 + yzero - math.ceil(ymin)
    yc2 = 1 + yzero + 1024 - math.ceil(ymax)
    
    fo = open(band+'recominfo', 'w')
    print >> fo, "%d %d %d %d %d %d %d %d" % (xzero, yzero, xsize, ysize, xc1, xc2, yc1, yc2)
    fo.close()


def dotran(band, urms, lstarnum):

    f = open(band+'recominfo')
    for line in f:
        val = line[:-1].split()
        xzero = int(val[0])
        yzero = int(val[1])
        xsize = int(val[2])
        ysize = int(val[3])
    f.close()

    iraf.imarith.unlearn()
    iraf.geotran.unlearn()
    iraf.imcopy.unlearn()
    iraf.imreplace.unlearn()
    iraf.imdelete.unlearn()

    iraf.geotran.geometry = 'linear'
    iraf.geotran.xmin = 1
    iraf.geotran.xmax = xsize
    iraf.geotran.ymin = 1
    iraf.geotran.ymax = ysize
    iraf.geotran.interpo = 'drizzle[0.5]'
    iraf.geotran.boundary = 'constant'
    iraf.geotran.constant = -9999
    iraf.geotran.fluxconserve = 'yes'
    iraf.geotran.nxblock = xsize
    iraf.geotran.nyblock = ysize
    iraf.geotran.verbose = 'no'

    #
    # gtran.coo for iraf.geotran.transform
    # it works even if it does not contain nothing.
    #
    fo = open('gtran.coo', 'w')
    print >> fo, 'dummy'
    fo.close()

    lnum = 0
    f = open(band+'tran.txt')
    for line in f:
        lnum = lnum + 1
    f.close()
    nstep = lnum / 10

    f = open(band+'tran.txt')
    i = 0
    pcnt = 0
    istep = 0
    for line in f:
        i = i + 1
        value = line[:-1] . split()
        farr = value[0].split('.')
        infits = '../' + farr[0] + '.ffiles/' + farr[1]
        xrms = float(value[12])
        yrms = float(value[13])
        starnum = int(value[14])
        ofits = value[0]

        if i == 1:
            iraf.geotran(infits, ofits, '', '', xshift=xzero, yshift=yzero)
        elif xrms <= urms and yrms <= urms and starnum >= lstarnum:
            iraf.geotran(infits, ofits, '', '', xshift=xzero, yshift=yzero)
            mkdb(value, xsize, ysize, xzero, yzero)
            iraf.imcopy(ofits, 'mask', verbose='no')
            iraf.imreplace('mask', -100000, imagina=0, lower='INDEF', upper=-100, radius=0)
            iraf.imreplace('mask', 0, imagina=0, lower=-100, upper='INDEF', radius=0)
            if not os.access('gtran.db', os.F_OK):
                print 'not found gtran.db'
            if not os.access('gtran.coo', os.F_OK):
                print 'not found gtran.coo'
            iraf.geotran(ofits, ofits, database='gtran.db', transforms='gtran.coo', xshift='INDEF', yshift='INDEF')
            iraf.geotran('mask', 'mask', database='gtran.db', transforms='gtran.coo', xshift='INDEF', yshift='INDEF')
            iraf.imreplace('mask', -100000, imagina=0, lower='INDEF', upper=-0.001, radius=0)
            iraf.imarith(ofits, '+', 'mask', ofits)
            iraf.imdelete('mask', verify='no')
            os.remove('gtran.db')

        istep = istep + 1
        if istep == nstep:
            pcnt = str(int(100 * float(i) / lnum))
            print pcnt + '%',
            sys.stdout.flush()
            istep = 0

    f.close()

    if pcnt == '100':
        print 'done'
    else:
        print '100% done'


def mkdb(coeff, xsize, ysize, xzero, yzero):

    xsize = str(xsize)
    ysize = str(ysize)

    xrefmean = float(coeff[8]) # - float(xzero)
    xrefmean = str(xrefmean)
    yrefmean = float(coeff[9]) # - float(yzero)
    yrefmean = str(yrefmean)
    
    xmean = float(coeff[10]) # - float(xzero)
    xmean = str(xmean)
    ymean = float(coeff[11]) # - float(yzero)
    ymean = str(ymean)
    
    if coeff[14] == 1:
        fitgeom = 'shift'
    else:
        fitgeom = 'rotate'

    outdb = 'begin\tgtran.coo\n\txrefmean\t' + xrefmean + '\n\tyrefmean\t' + yrefmean + '\n\txmean\t' + xmean + '\n\tymean\t' + ymean + '\n\tgeometry\t' + fitgeom + '\n\tfunction\tpolynomial\n\txshift\t' + coeff[2] + '\n\tyshift\t' + coeff[5] + '\n\txmag\t1.\n\tymag\t1.\n\txrotation\t' + coeff[1] + '\n\tyrotation\t' + coeff[1] + '\n\txrms\t' + coeff[12] + '\n\tyrms\t' + coeff[13] + '\n\tsurface1\t11\n\t\t\t3.\t3.\n\t\t\t2.\t2.\n\t\t\t2.\t2.\n\t\t\t0.\t0.\n\t\t\t1.\t1.\n\t\t\t' + xsize + '\t' + xsize + '\n\t\t\t1.\t1.\n\t\t\t' + ysize + '\t' + ysize + '\n\t\t\t' + coeff[2] + '\t' + coeff[5] + '\n' + '\t\t\t' + coeff[3] + '\t' + coeff[6] + '\n' + '\t\t\t' + coeff[4] + '\t' + coeff[7] + '\n\tsurface2\t0\n'
    
    fo = open('gtran.db', 'w')
    print >> fo, outdb
    fo.close()
    
    




if __name__ == "__main__":

    print 'gmaptran.py is a module repository.'





