""" Test script for PyMidas - just runs a few tasks from both IRAF
    and MIDAS.

      Richard Hook, July 2005
      Revised and extended, September 2005

Note - start PyMidas from somewhere which has an IRAF login.cl
file.
                                        """
# Load both PyMidas and PyRAF Python packages
from pymidas import midas
from pyraf import iraf
import os

# Main module
def run(image=None):

    # Default IRAF image of M51 if none specified
    if image == None:
       os.system('rm test*.fits')
       iraf.imcopy('dev$pix','test.fits')
       image='test.fits'

    # Get image stats from both MIDAS and IRAF
    midas.do('stat/image '+image)
    iraf.images()
    iraf.imstat(image)

    # Create the MIDAS image display
    midas.createDisp()

    # Quickly load the input image
    midas.loadImag(image,'cuts=0,1000')

    # Load appropriate IRAF and STSDAS packages
    iraf.stsdas()
    iraf.analysis()
    iraf.toolbox()
    iraf.imgtools()
    iraf.dither()

    # Set some names for output files
    outdr='test_drz.fits'
    outwt='test_wht.fits'

    # Loop over a range of angles
    for angle in range(36):

       print ""
       print ""
       print " ***** Angle is: ",angle*5.0," ******"
       print ""
       print ""

       # Rotate the image using drizzle in IRAF/STSDAS
       iraf.drizzle(image,outdr,outweig=outwt,scale=1.0+angle/10.,kernel="turbo",rot=angle*5.0,outnx=512,outny=512)

       # Add an offset value using MIDAS
       midas.computeImag(outdr+' = '+outdr+'+'+str(angle*20.))

       # Get the value of a pixel using both MIDAS and IRAF
#### The MIDAS version is broken at present.
####       v=midas.getPix(outdr,10,10)
####       print "Pixel value: ",v
       iraf.listpix(outdr+'[10:10,10:10]')

       # Load the image with MIDAS
       midas.loadImag(outdr,'cuts=0,1000')

       # Delete the temporary files using Python OS methods
       os.remove(outdr)
       os.remove(outwt)

# the rest are test methods, not used above.
def getKey(keyword):
    t=midas.readKeyw(keyword)
    print t
    return(t[2])

def RNHgetPix(image,xp,yp):
    t=midas.readImag(image+' @'+str(xp)+',@'+str(xp)+',1')
    return(float(t[13]))

def getDesc(image,descr):
    t=midas.readDesc(image,descr)
    return(t[7])

run()
