#Convert CASA images to FITS format
# To be run from inside casapy.
# Run it in the directory where the image files are sitting.
# Will place the FITS images in the user defined OUTDIR (hardcoded).
#
# Divya 15Apr2013

import glob, os, sys

#The old data location
#if sys.platform == 'darwin': BASEDIR='/Users/kamen/ubuntu_share/MWA_DATA/'
#if sys.platform == 'linux2': BASEDIR='/mnt/ubuntu_share/MWA_DATA/'
#The new data location
if sys.platform == 'darwin': BASEDIR='/Volumes/MyPassport/MWA_DATA/'
if sys.platform == 'linux2': BASEDIR='/mnt/MWA_DATA/'
CHANNELS = ['084-085','069-070','103-104','113-114','125-126','139-140','153-154'] # ['093-094','062-063','076-077','084-085']
CHANNELS = ['062-063','069-070','076-077','084-085','093-094','113-114','139-140','153-154','169-170','187-188','103-104']
CHANNELS = ['103-104']
#OBSIDS=['1130643840']
OBSIDS=['1130642640','1130642936','1130643240','1130643536','1130643840','1130644136','1130644440','1130644736','1130645040']
#OBSIDS=['1130642640','1130642936','1130643240','1130643536','1130643840','1130644136','1130644440','1130644736','1130645040']

for CHANNEL in CHANNELS:
        for OBSID in OBSIDS:
                INDIR=BASEDIR+CHANNEL+'/'+OBSID+'/'
                print INDIR
                img_list = glob.glob(INDIR+'*.image')
                if len(img_list)==0:
                        print "#### Found No image matching the search criterion ####";
                for IMG in img_list:
                        NAME = IMG.split('.image')      
                        OUT_NAME = NAME[0]+'.fits'
                        if not os.path.exists(OUT_NAME):
                                print IMG,OUT_NAME
                                exportfits(imagename=IMG, fitsimage=OUT_NAME, 
                                        bitpix=-32, minpix=0, maxpix=-1, overwrite=False, dropstokes=False,
                                        stokeslast=True)
        

