import os, sys
from AIPS import AIPS
from AIPSTask import AIPSTask as task
from AIPSData import AIPSUVData as UV
from AIPSData import AIPSImage as IM
from Wizardry.AIPSData import AIPSUVData as WUV
import time
import numpy as np
from astropy.io import fits

#Ant   1 = EB
#Ant   2 = JB
#Ant   3 = MC
#Ant   4 = NT
#Ant   5 = WB
#Ant   6 = GB
#Ant   7 = HN
#Ant   8 = SC
#Ant   9 = FD
#Ant  10 = KP
#Ant  11 = LA
#Ant  12 = NL
#Ant  13 = PT
#Ant  14 = Y 
#Ant  15 = AR
#Ant  16 = BR
#Ant  17 = MK
#Ant  18 = OV

vlba_antennas = [None, 7, 8, 9, 10, 11, 12, 13, 16, 17, 18]

# Note regarding maser calibration:
# Earth rotation is 0.3km/s. 
# At Lband this means maximum relative difference of the
# antennas of (0.3km/s / speed of light) * 1650MHz=1.65Khz.
# this is nothing compared to the continuum channel width of 250kHz. 
# For finding rates, phases and amps, we do not need CVEL.
# Maser lines are found by inspection in POSSM to be in channel range 13-20.
# This is consistent with theory:
# Rest frame freqs of maser lines are 1665 and 1667 MHz, 
# Redshift translates to -30MHz, so measured is 1635 and 1637 MHz.
# From possm we see that peak is mostly in channel 17.
masercal_bchan = 17
masercal_echan = 17
masercal_bif = 1
masercal_eif = 1
masercal_nchav = 512

# Initialize TV
from AIPSTV import AIPSTV # Needed for TV 
tv = AIPSTV()
#tv.start() 

whattodo = {'load_data': True, # ->CL1
            'preflagging':True,
            'ion_corr': True, # ->CL2
            'eops_corr': True, # ->CL3
            'par_ang_cor': True, # ->CL4
            'apriori_ampcal' : True, # SN1,2 CL5,
            'fring_ampcal+ff' : True, #->SN3, CL6
            'bpass_ff': True, # BP 1
            'image_ff_1': True, 
            'selfcal_ff' : True, # -> SN4, CL7 # Correct VLBA
            'image_ff_2': True, 
            'selfcal_ff_2' : True, # -> SN5, CL8 # Correct 14
            'image_ff_3': True,
            'split': True,
            'fixwt': True,
            'multi': True,

            # Make image of J1516+1932 for reference to other epochs. 
            # First need phasecal.
            'selfcal_ampcal' : True, # -> SN1, CL2
            'image_ampcal_1': True, 

            # Selfcal Arp220, phae only on strongest OH channel
            'flag_arp220': True,
            'selfcal_target_maser' : True, # -> SN1, CL2. USING POINT MODEL
            'image_ARP220_maser_1': True,
            'selfcal_target_maser_2' : True, # -> SN2 P
            'image_ARP220_maser_2': True,
            'selfcal_target_maser_3' : True, # -> SN3 P
            'image_ARP220_maser_3': True,

            'calculate_shifts': True, # Calculate shifts for Arp220 imaging. MUST be enabled to set variables used by imaging.
            'flag_maser': True, # If excluding the maser from final images
            'image_ARP220': True,
            'selfcal_arp220': True, # ->SN4, CL5
            'image_ARP220_V': True,
            ######
            'image_ARP220_final': True,
            'export_results': True,
            }

########## Initialize observation data ##########
AIPS.userno = 1000
clint = 1.0/60 # Seconds
NAME = '017A_L'
RAWCLASS = 'UVDATA'
CLASS = 'UVDATA'
MCLASS = NAME
DISK = 1
AMPCALIM = NAME + '_AC'
FFCALIM = NAME + '_FC'
PCALIM = NAME + '_PC'
TCALIM = NAME + '_TC'
TCALIM2 = TCALIM + '2'
target = 'ARP220'
ampcal = '1516+193'
ff = '1613+341'
uvrange = [None, 5000, 0]
sorted_class = CLASS
logfile = 'log_'+NAME+'_PTred.log'
refant = 1
#########^^^ END OF CONFIG VARIABLES ^^^################
tic = time.time()
########## Initialize Log file ##########
try:
 os.system('cp ' + logfile + ' ' + logfile + '.old')
 os.system('rm -f ' + logfile)
except:
 pass
AIPS.log = open(logfile, 'a')
AIPS.log.write('whattodo = '+repr(whattodo)+'\n')

########## LOAD DATA ##########
if whattodo['load_data']:
    fitld = task('fitld')
    fitld.default()
    outdata = UV(NAME, RAWCLASS, DISK, 1)
    fitld.datain = '/data1/eskil/RAWDATA/GD017A/VLBA_GD017A_PASS1.UVDATA.1.UVFITS'
    fitld.outdata = outdata
    fitld.ncount = 1
    fitld.digicor = 1
    fitld.clint = clint
    fitld.wtthresh = 0.7
    fitld.doconcat = 1
    fitld.douvcomp = -1
    if outdata.exists():
        print 'WARNING: Removing existing file ' + NAME + '.' + RAWCLASS
        outdata.zap()
        print '         File removed. Proceeding with FITLD...'
    fitld.go()

########## PREFLAGGING ##########
#Flag data known to be bad (whole antennas etc.)
if whattodo['preflagging']:
    data = UV(NAME, sorted_class, DISK, 1)
    infgver = 1
    outfgver = 2
    # Remove all FG tables higher than infgver.
    for i in range(data.table_highver('FG'), infgver, -1):
     data.zap_table('FG', i)
    data = UV(NAME, sorted_class, DISK, 1)
    # Copy flag table 1 to flagtable 2
    tacop = task('tacop')
    tacop.default()
    tacop.indata = data
    tacop.inext = 'FG'
    tacop.inver = infgver
    tacop.ncount = 1
    tacop.outdata = data
    tacop.outvers = outfgver
    tacop.go()
   #Flag antenna 5 before 06:00 fringefinder scan since is rubbish
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 5]
    uvflg.timeran = [None, 0, 0, 0, 0, 0, 6, 0, 0]
    uvflg.sour = [None, '']
    uvflg.reason = 'NO fringes'
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag antenna 5, high amplitudes in vplot
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 5]
    uvflg.timeran = [None, 0, 7, 20, 0, 0, 7, 50, 0]
    uvflg.sour = [None, '']
    uvflg.reason = 'Amp Spike'
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag antenna 5, high amplitudes in vplot
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 5]
    uvflg.timeran = [None, 0, 8, 30, 0, 0, 9, 0, 0]
    uvflg.sour = [None, '']
    uvflg.reason = 'Amp Spike'
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag antenna 5, high amplitudes in vplot
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 5]
    uvflg.timeran = [None, 0, 9, 40, 0, 0, 9,48, 0]
    uvflg.sour = [None, '']
    uvflg.reason = 'Amp Spike'
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag antenna 5, high amplitudes in vplot
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 5]
    uvflg.timeran = [None, 0, 11, 55, 0, 0, 12, 16, 0]
    uvflg.sour = [None, '']
    uvflg.reason = 'Amp Spike'
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag antenna 5, high amplitudes in vplot
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 5]
    uvflg.timeran = [None, 0, 12, 34, 0, 0, 12, 40, 0]
    uvflg.sour = [None, '']
    uvflg.reason = 'Amp Spike'
    uvflg.opcode = 'FLAG'
    uvflg.go()
   
   #Flag antenna 9, high amplitudes in vplot
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 9]
    uvflg.timeran = [None, 0, 22, 36, 0, 0, 22, 40, 0]
    uvflg.sour = [None, '']
    uvflg.reason = 'Amp Spike'
    uvflg.opcode = 'FLAG'
    uvflg.go()
   
    # The VLA amp solution is not good before 18 UT.
    # After 18 is also the range when most of the other VLBA
    # is online. So flag VLA before.
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 14]
    uvflg.timeran = [None, 0, 0, 0, 0, 0, 18, 0, 0]
    uvflg.sour = [None, '']
    uvflg.reason = 'BAD AMP sols'
    uvflg.opcode = 'FLAG'
    #uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 1, 1, 35, 0, 1, 1, 38, 0]
    uvflg.sour = [None, ff]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 6]
    uvflg.timeran = [None, 0, 13, 31, 55, 0, 13, 32, 3]
    uvflg.sour = [None, ff]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 18]
    uvflg.timeran = [None, 0, 16, 55,0, 0, 17, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 15]
    #uvflg.timeran = [None, 0, 16, 52, 0, 0, 16, 54, 30]
    uvflg.timeran = [None, 0, 16, 52, 0, 0, 17, 0, 0]
    #uvflg.bif = 1
    #uvflg.eif = 1
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 10]
    uvflg.baselin = [None, 9]
    uvflg.timeran = [None, 0, 13, 50, 0, 0, 14, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 6]
    uvflg.baselin = [None, 8]
    uvflg.timeran = [None, 0, 13, 30, 0, 0, 13, 40, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 0, 8, 0, 0, 0, 8, 1, 30]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 0, 16, 37, 50, 0, 16, 38, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 0, 19, 44, 0, 0, 19, 46, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 0, 16, 2, 10, 0, 16, 2, 15]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 0, 18, 1, 0, 0, 18, 2, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 0, 8, 30, 0, 0, 8, 34, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 5]
    uvflg.timeran = [None, 0, 9, 48, 0, 0, 9, 50, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 5]
    uvflg.timeran = [None, 0, 17, 55, 0, 0, 18, 05, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 7]
    uvflg.timeran = [None, 1, 0, 0, 0, 1, 1, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    
    
    
    # Quack
    quack = task('quack')
    quack.default()
    quack.indata = data
    #quack.antenna = [None, 1, 2]
    quack.opcode = 'BEG'
    quack.aparm[2] = 1
    quack.go()
    quack = task('quack')
    quack.default()
    quack.indata = data
    #quack.antenna = [None, 1, 2]
    quack.opcode = 'ENDB'
    quack.aparm[2] = 0.5
    quack.go()
    
    # Flag VLA since poor phase coherence, see also Lonsdale 2006.
    # Seems to be signal here...but does not improve image much. Ignore for now.
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 14]
    uvflg.sour = [None, target]
    uvflg.opcode = 'FLAG'
    #uvflg.go()
    
    # Flag edge channels
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.bchan = 1
    uvflg.echan = 2
    uvflg.opcode = 'FLAG'
    uvflg.antenna = [None, 1] # Antenna 1=EB
    uvflg.go()
    # Flag edge channels
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.bchan = 28
    uvflg.echan = 32
    uvflg.opcode = 'FLAG'
    uvflg.antenna = [None, 1] # Antenna 1=EB
    #uvflg.go()
    
    # Flag bad baseline with 1-2Jy flux for Arp220 ch 17 compared to 0.5 Jy for others. Also spiks just below 5MLambda.
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 3]
    uvflg.baselin = [None, 4]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 2]
    uvflg.timeran = [None, 0, 11, 0, 0, 0, 11, 30, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 4]
    uvflg.timeran = [None, 0, 18, 5, 0, 0, 18, 30, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag very sensitive baseline
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 15]
    uvflg.baselin = [None, 6]
    uvflg.opcode = 'FLAG'
    #uvflg.go()
    
########## IONOSPHERIC CORRECTIONS ##########
# => CL2
if whattodo['ion_corr']:
    clinver = 1
    cloutver = 2
    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all CL tables higher than cloutver-1.
    for i in range(data.table_highver('CL'), cloutver-1, -1):
        data.zap_table('CL', i)
    data = UV(NAME, sorted_class, DISK, 1)
    tecor = task('tecor')
    tecor.default()
    tecor.indata = data
    tecor.gainver = clinver
    tecor.gainuse = cloutver
    # Observation was 9-NOV-2003. 
    # According to http://mistupid.com/calendar/dayofyear.htm
    # This means day of the year DDD=313, but also 314 since long obs.
    # Fetch and uncompress file for this day
    doy = str(313)
    year = str(2003)
    tecfile = 'jplg' + doy + '0.'+year[-2:]+'i'
    if not os.path.exists(tecfile):
        os.system('wget ftp://cddis.gsfc.nasa.gov/gps/products/ionex/'+year+'/'+doy+'/' + tecfile + '.Z')
        os.system('gunzip ' + tecfile+ '.Z')
    doy = str(314)
    year = str(2003)
    tecfile = 'jplg' + doy + '0.'+year[-2:]+'i'
    if not os.path.exists(tecfile):
        os.system('wget ftp://cddis.gsfc.nasa.gov/gps/products/ionex/'+year+'/'+doy+'/' + tecfile + '.Z')
        os.system('gunzip ' + tecfile+ '.Z')
    #Reset name to first file for input to tecor 
    doy = str(313)
    year = str(2003)
    tecfile = 'jplg' + doy + '0.'+year[-2:]+'i'
    tecor.infile = 'PWD:' + tecfile
    tecor.nfiles = 2
    tecor.go()
########## EARTH ORIENTATION PARAMETERS CORRECTION ##########
# => CL3
if whattodo['eops_corr']:
    clinver = 2
    cloutver = 3
    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all CL tables higher than cloutver-1.
    for i in range(data.table_highver('CL'), cloutver-1, -1):
        data.zap_table('CL', i)
    data = UV(NAME, sorted_class, DISK, 1)
    clcor = task('clcor')
    clcor.default()
    clcor.indata = data
    clcor.gainver = clinver
    clcor.gainuse = cloutver
    clcor.opcode = 'EOPS'
    clcor.clcorprm = [None, 1, 0] 
    if not os.path.exists('./usno_finals.erp'):
        os.system('wget http://gemini.gsfc.nasa.gov/solve_save/usno_finals.erp')
    clcor.infile = 'PWD:usno_finals.erp'
    clcor.go()
 
########## PARALLACTIC ANGLE CORRECTION ##########
# => CL4
if whattodo['par_ang_cor']:
    clinver = 3
    cloutver = 4
    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all CL tables higher than cloutver-1.
    for i in range(data.table_highver('CL'), cloutver-1, -1):
        data.zap_table('CL', i)
    data = UV(NAME, sorted_class, DISK, 1)
    clcor = task('clcor')
    clcor.default()
    clcor.indata = data
    clcor.gainver = clinver
    clcor.gainuse = cloutver
    clcor.opcode = 'PANG'
    clcor.clcorprm = [None, 1, 0] 
    if not os.path.exists('./usno_finals.erp'):
     os.system('wget http://gemini.gsfc.nasa.gov/solve_save/usno_finals.erp')
    clcor.infile = 'PWD:usno_finals.erp'
    clcor.go()

############# AMPLITUDE calibration ##############
if whattodo['apriori_ampcal']:
    # Define initial versionnumbers, increased further down
    clinver = 4
    cloutver = 5
    snoutver = 1
    tyinver = 1
    tyoutver = 2
    gcinver = 1
    gcoutver = 2
    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all SN tables higher than version snoutver-1.
    for i in range(data.table_highver('SN'), snoutver-1, -1):
        data.zap_table('SN', i)
    # Remove all TY tables higher than version tyoutver-1.
    for i in range(data.table_highver('TY'), tyoutver-1, -1):
        data.zap_table('TY', i)
    # Remove all GC tables higher than version gcoutver-1.
    for i in range(data.table_highver('GC'), gcoutver-1, -1):
        data.zap_table('GC', i)
    data = UV(NAME, sorted_class, DISK, 1)
    tacop = task('tacop')
    tacop.default()
    tacop.indata = data
    tacop.inext = 'TY'
    tacop.inver = tyinver
    tacop.ncount = 1
    tacop.outdata = data
    tacop.outvers = tyoutver
    tacop.go()
    tacop = task('tacop')
    tacop.default()
    tacop.indata = data
    tacop.inext = 'GC'
    tacop.inver = gcinver
    tacop.ncount = 1
    tacop.outdata = data
    tacop.outvers = gcoutver
    tacop.go()

    antab = task('antab')
    data = UV(NAME, sorted_class, DISK, 1)
    antab.indata = data
    antab.calin = 'PWD:gd017a.antab_noEB'
    antab.tyver = tyoutver
    antab.gcver = gcoutver
    antab.blver = -1
    antab.offset = 0.5
    antab.go()

    # Run APCAL 
    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all SN tables higher than version snoutver-1.
    for i in range(data.table_highver('SN'), snoutver-1, -1):
        data.zap_table('SN', i)
    apcal = task('apcal')
    apcal.indata = data
    apcal.tyver = tyoutver
    apcal.gcver = gcoutver
    apcal.snver = snoutver
    apcal.invers = 1 # WX table version
    apcal.solint = 2 
    apcal.opcode = ''
    apcal.freqid = 1
    apcal.sources = [None, '']
    apcal.go()
    
    snsmo = task('snsmo')
    snsmo.indata = data
    snsmo.inver = snoutver
    snsmo.outver = snoutver+1
    snsmo.smotype = 'AMPL'
    snsmo.bparm[1] = 1.0/3600 # Smoothing in time in seconds to ensure no smoothing
    # DO NOT SMOOTH; INSTEAD CLIP WITH MWF
    snsmo.cparm[1] = 15.0/60 #in hours
    snsmo.cparm[6] = 0.5 # Max amp deviation
    snsmo.doblank = -1 # Since cannot be used with AMPL
    snsmo.antenna = [None, -6,-7,-8]
    snsmo.go()

    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all CL tables higher than version cloutver-1.
    for i in range(data.table_highver('CL'), cloutver-1, -1):
        data.zap_table('CL', i)
    # Make CL table
    clcal = task('clcal') 
    clcal.sources = [None, '']
    clcal.indata = data
    clcal.timeran = [None, 0]
    clcal.samptype = 'BOX'
    clcal.bparm = [None, 0.00001]
    clcal.doblank = 1
    clcal.snver = snoutver+1
    clcal.invers = snoutver+1
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.interpol = 'SELF'
    clcal.go()

if whattodo['fring_ampcal+ff']:
    clinver = 5
    cloutver = 6
    snoutver = 3
    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all SN tables higher than version snoutver-1.
    for i in range(data.table_highver('SN'), snoutver-1, -1):
        data.zap_table('SN', i)
    data = UV(NAME, sorted_class, DISK, 1)
    fring=task('fring')
    fring.default()
    fring.indata = data
    fring.docalib = 1
    fring.gainuse = clinver
    fring.calsour = [None, ff, ampcal]
    fring.refant = refant
    fring.solint = 0.5
    fring.snver = snoutver
    #fring.dparm[8] = 5 # Zero rates and phases
    fring.dparm[9] = 1 # Do not fit rate
    fring.go()

    # Apply SN-table
    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all CL tables higher than version cloutver-1.
    for i in range(data.table_highver('CL'), cloutver-1, -1):
        data.zap_table('CL', i)
    data = UV(NAME, sorted_class, DISK, 1)
    # Make CL table
    clcal = task('clcal') 
    clcal.default()
    clcal.indata = data
    clcal.snver = snoutver
    clcal.invers = snoutver
    clcal.calsour = [None, ff, ampcal]
    clcal.sour = [None, ''] # All sources
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.go()

if whattodo['bpass_ff']:
    clinver = 6
    bpoutver = 1
    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all BP tables higher than version bpoutver-1.
    for i in range(data.table_highver('BP'), bpoutver-1, -1):
        data.zap_table('BP', i)
    data = UV(NAME, sorted_class, DISK, 1)
    bpass = task('bpass')
    bpass.default()
    bpass.indata = data
    bpass.calsour = [None,ff]
    bpass.timeran = [None, 0] # Use all scans to get all ants
    bpass.gainuse = clinver
    bpass.docal = 1
    bpass.refant = refant
    bpass.solint = -1 # Whole timerange
    bpass.flagver = 0
    bpass.outvers = bpoutver
    bpass.doband = -1
    bpass.bpassprm[10]=1 # Normalize amps using all channels
    bpass.go()

if whattodo['image_ff_1']:
    clinver = 6
    imagename = FFCALIM + '1'
    imagedisk = 1
    imageseq = 1
    data = UV(NAME, sorted_class, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, ff]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.stokes = 'I'
    imagr.cellsize = [None, 0.2e-3, 0.2e-3]
    imagr.imsize = [None, 512,512]
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.outname = imagename
    imagr.outdisk = imagedisk
    imagr.outseq = imageseq
    imagr.niter = 300
    imagr.doband = 1
    imagr.bpver = 1
    imagr.antenna = vlba_antennas
    imagr.baselin = imagr.antennas
    if imagr.niter == 0:
        imageclass = 'IIM001'
    else:
        imageclass = 'ICL001'
    # Remove previous old image
    image = IM(imagename, imageclass, imagedisk, imageseq)
    if image.exists():
     image.zap()
    # Also remove old beam image
    image = IM(imagename, 'IBM001', imagedisk, imageseq)
    if image.exists():
     image.zap()
    imagr.robust = 0.5
    imagr.go()


if whattodo['selfcal_ff']:
    clinver = 6
    cloutver = 7
    snoutver = 4
    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all SN tables higher than version snoutver-1.
    for i in range(data.table_highver('SN'), snoutver-1, -1):
        data.zap_table('SN', i)
    data = UV(NAME, sorted_class, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.in2data = IM(FFCALIM + '1', 'ICL001', 1, 1)
    calib.calsour = [None, ff]
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.flagver = 0
    calib.snver = snoutver
    calib.solmode = 'A&P'
    calib.solint = 5 # 
    calib.aparm[7] = 5 # SNR
    calib.cmethod = 'DFT'
    calib.aparm[1] = 4 # Min no antenna
    calib.aparm[6] = 1 # Print level
    calib.antenna = vlba_antennas
    calib.timeran = [None, 0, 13, 30, 0, 2, 0, 0, 0] # Ignore first scans
    calib.doband = 1
    calib.bpver = 1
    calib.go()
    # Apply SN-table
    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all CL tables higher than version cloutver-1.
    for i in range(data.table_highver('CL'), cloutver-1, -1):
        data.zap_table('CL', i)
    data = UV(NAME, sorted_class, DISK, 1)
    # Make CL table
    clcal = task('clcal') 
    clcal.default()
    clcal.indata = data
    clcal.snver = snoutver
    clcal.invers = snoutver
    clcal.antenna = vlba_antennas
    clcal.calsour = [None, ff] # Use sols from Ampcal 
    clcal.sour = [None, ''] # Apply to all sources
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.go()

if whattodo['image_ff_2']:
    clinver = 7
    imagename = FFCALIM+'2'
    imagedisk = 1
    imageseq = 1
    data = UV(NAME, sorted_class, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, ff]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.stokes = 'I'
    imagr.cellsize = [None, 0.2e-3, 0.2e-3]
    imagr.imsize = [None, 512,512]
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.doband = 1
    imagr.bpver = 1
    imagr.outname = imagename
    imagr.outdisk = imagedisk
    imagr.outseq = imageseq
    imagr.niter = 300
    imagr.antenna = vlba_antennas
    imagr.baselin = imagr.antenna
    if imagr.niter == 0:
        imageclass = 'IIM001'
    else:
        imageclass = 'ICL001'
    # Remove previous old image
    image = IM(imagename, imageclass, imagedisk, imageseq)
    if image.exists():
     image.zap()
    # Also remove old beam image
    image = IM(imagename, 'IBM001', imagedisk, imageseq)
    if image.exists():
     image.zap()
    imagr.robust = 0.5
    imagr.go()

if whattodo['selfcal_ff_2']:
    clinver = 7
    cloutver = 8
    snoutver = 5
    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all SN tables higher than version snoutver-1.
    for i in range(data.table_highver('SN'), snoutver-1, -1):
        data.zap_table('SN', i)
    data = UV(NAME, sorted_class, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.in2data = IM(FFCALIM + '2', 'ICL001', 1, 1)
    calib.calsour = [None, ff]
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.flagver = 0
    calib.snver = snoutver
    calib.solmode = 'A&P'
    calib.solint = 5 # 
    calib.aparm[1] = 3 # Min no antennas
    calib.aparm[7] = 5 # SNR
    calib.cmethod = 'DFT'
    calib.aparm[6] = 1 # Print level
    #calib.aparm[9] = 1 # Pass on failed sols, for vlba only scans
    calib.antenna = [None, 0] # All antennas
    calib.dofit = [None, 14]
    calib.doband = 1
    calib.bpver = 1
    calib.go()
    # Apply SN-table
    data = UV(NAME, sorted_class, DISK, 1)
    # Remove all CL tables higher than version cloutver-1.
    for i in range(data.table_highver('CL'), cloutver-1, -1):
        data.zap_table('CL', i)
    data = UV(NAME, sorted_class, DISK, 1)
    # Make CL table
    clcal = task('clcal') 
    clcal.default()
    clcal.indata = data
    clcal.snver = snoutver
    clcal.invers = snoutver
    clcal.antenna = [None, 14] # Non-VLBA
    clcal.calsour = [None, ff] # Use sols from Ampcal 
    clcal.sour = [None, ''] # Apply to all sources
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.go()


if whattodo['image_ff_3']:
    clinver = 8
    imagename = FFCALIM+'3'
    imagedisk = 1
    imageseq = 1
    data = UV(NAME, sorted_class, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, ff]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.stokes = 'I'
    imagr.cellsize = [None, 0.2e-3, 0.2e-3]
    imagr.imsize = [None, 512,512]
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.doband = 1
    imagr.bpver = 1
    imagr.outname = imagename
    imagr.outdisk = imagedisk
    imagr.outseq = imageseq
    imagr.niter = 300
    imagr.uvran = uvrange
    if imagr.niter == 0:
        imageclass = 'IIM001'
    else:
        imageclass = 'ICL001'
    # Remove previous old image
    image = IM(imagename, imageclass, imagedisk, imageseq)
    if image.exists():
     image.zap()
    # Also remove old beam image
    image = IM(imagename, 'IBM001', imagedisk, imageseq)
    if image.exists():
     image.zap()
    imagr.robust = 0.5
    #imagr.antenna = [None, -1,-2,-3,-4,-5,-6,-14,-15]
    #imagr.baselin = imagr.antenna
    #imagr.antenna = vlba_antennas + [1,]
    #imagr.baselin = vlba_antennas + [1,]
    #imagr.antenna = [None, -15]
    imagr.go()

if whattodo['split']:
    clinver = 8
    bpinver = 1
    fginver = 2 
    
    data = UV(NAME, sorted_class, DISK, 1)
    split = task('split')
    split.default()
    split.indata = data
    split.docal = 1
    split.gainuse =clinver
    split.doband = 1
    split.bpver = 1
    split.flagver = fginver
    split.outclass = NAME
    for s in [target, ff, ampcal]:
        tdata = UV(s, NAME, 1, 1)
        if tdata.exists():
            tdata.zap()
    split.go()

if whattodo['fixwt']:
    for s in [target, ff, ampcal]:
        idata = UV(s, NAME, 1, 1)
        odata = UV(s, 'FIXWT', 1, 1)
        fixwt = task('fixwt')
        fixwt.default()
        fixwt.indata = idata
        fixwt.outdata = odata
        fixwt.solint = 5
        if odata.exists():
            odata.zap()
        fixwt.go()

if whattodo['multi']:
    for s in [target, ff, ampcal]:
        idata = UV(s, 'FIXWT', 1, 1)
        odata = UV(s, MCLASS, 1, 1)
        multi = task('multi')
        multi.default()
        multi.indata = idata
        multi.outdata = odata
        if odata.exists():
            odata.zap()
        multi.go()


if whattodo['selfcal_ampcal']:
    clinver = 1
    cloutver = 2
    snoutver = 1
    data = UV(ampcal, MCLASS, DISK, 1)
    # Remove all SN tables higher than version snoutver-1.
    for i in range(data.table_highver('SN'), snoutver-1, -1):
        data.zap_table('SN', i)
    data = UV(ampcal, MCLASS, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.calsour = [None, ampcal]
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.flagver = 0
    calib.snver = snoutver
    calib.solmode = 'P'
    calib.solint = 5 # 
    calib.aparm[1] = 3 # Min no antennas
    calib.aparm[7] = 5 # SNR
    calib.cmethod = 'DFT'
    calib.aparm[6] = 1 # Print level
    calib.go()
    # Apply SN-table
    data = UV(ampcal, MCLASS, DISK, 1)
    # Remove all CL tables higher than version cloutver-1.
    for i in range(data.table_highver('CL'), cloutver-1, -1):
        data.zap_table('CL', i)
    data = UV(ampcal, MCLASS, DISK, 1)
    # Make CL table
    clcal = task('clcal') 
    clcal.default()
    clcal.indata = data
    clcal.snver = snoutver
    clcal.invers = snoutver
    clcal.calsour = [None, ampcal] # Use sols from Ampcal 
    clcal.sour = [None, ampcal] # Apply to all sources
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.go()

if whattodo['image_ampcal_1']:
    clinver = 2
    imagename = AMPCALIM+'1'
    imagedisk = 1
    imageseq = 1
    data = UV(ampcal, MCLASS, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, ampcal]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.stokes = 'I'
    imagr.cellsize = [None, 0.2e-3, 0.2e-3]
    imagr.imsize = [None, 512,512]
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.outname = imagename
    imagr.outdisk = imagedisk
    imagr.outseq = imageseq
    imagr.niter = 300
    imagr.uvran = uvrange
    if imagr.niter == 0:
        imageclass = 'IIM001'
    else:
        imageclass = 'ICL001'
    # Remove previous old image
    image = IM(imagename, imageclass, imagedisk, imageseq)
    if image.exists():
     image.zap()
    # Also remove old beam image
    image = IM(imagename, 'IBM001', imagedisk, imageseq)
    if image.exists():
     image.zap()
    imagr.robust = 0.5
    imagr.antenna = [None, -14]
    imagr.go()

if whattodo['flag_arp220']:
    data = UV(target, MCLASS, DISK, 1)
    infgver = 0
    outfgver = 1
    # Remove all FG tables higher than infgver.
    for i in range(data.table_highver('FG'), infgver, -1):
     data.zap_table('FG', i)
    data = UV(target, MCLASS, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = 1
    uvflg.opcode = 'FLAG'
    uvflg.antenna = [None, 10, 18]
    uvflg.timeran = [None, 0, 15, 54, 0, 0, 15, 57, 0]
    uvflg.go()
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = 1
    uvflg.opcode = 'FLAG'
    uvflg.antenna = [None, 14]
    uvflg.timeran = [None, 0, 17, 35, 0, 0, 18, 5, 0]
    uvflg.go()
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = 1
    uvflg.opcode = 'FLAG'
    uvflg.antenna = [None, 9, 13]
    uvflg.timeran = [None, 0, 15, 20, 0, 0, 15, 24, 0]
    uvflg.go()
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = 1
    uvflg.opcode = 'FLAG'
    uvflg.antenna = [None, 2]
    uvflg.timeran = [None, 0, 6, 24, 0, 0, 6, 28, 0]
    uvflg.go()

    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = 1
    uvflg.opcode = 'FLAG'
    uvflg.antenna = [None, 10,11,13]
    uvflg.bif = 2
    uvflg.eif = 2
    uvflg.bchan = 23
    uvflg.echan = 23
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = 1
    uvflg.opcode = 'FLAG'
    uvflg.antenna = [None, 14]
    uvflg.bif = 2
    uvflg.eif = 2
    uvflg.bchan = 19
    uvflg.echan = 23
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = 1
    uvflg.opcode = 'FLAG'
    uvflg.antenna = [None, 13,14]
    uvflg.bif = 1
    uvflg.eif = 1
    uvflg.bchan = 28
    uvflg.echan = 32
    uvflg.go()



    # Flag weird RFI in antenna 3
    chans = [5,9, 13, 17, 21, 25, 29]
    for ch in chans:
        uvflg = task('uvflg')
        uvflg.default()
        uvflg.indata = data
        uvflg.bchan = ch
        uvflg.echan = ch
        uvflg.bif = 2
        uvflg.eif = 4
        uvflg.antenna = [None, 3]
        uvflg.opcode = 'FLAG'
        uvflg.go()
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = 1
    uvflg.opcode = 'FLAG'
    uvflg.antenna = [None, 3]
    uvflg.bif = 2
    uvflg.eif = 2
    uvflg.bchan = 31
    uvflg.echan = 32
    uvflg.go()
    
    # Finally clip high amps
    clip = task('clip')
    clip.default()
    clip.aparm[1] = 0.8 # Flag amp spikes
    clip.sources = [None, target]
    clip.docal = -1
    clip.flagver = outfgver
    clip.indata = data
    clip.outfgver = outfgver
    clip.timeran = [None, 0, 0, 0, 0, 0, 12, 0, 0]
    clip.go()
    clip = task('clip')
    clip.default()
    clip.aparm[1] = 3 # Flag amp spikes
    clip.sources = [None, target]
    clip.docal = -1
    clip.flagver = outfgver
    clip.indata = data
    clip.outfgver = outfgver
    clip.timeran = [None, 0, 12, 0, 0, 1, 12, 0, 0]
    clip.go()

    #Flag high weights
    clip = task('clip')
    clip.default()
    clip.aparm[6] = 10e3 # Flag very sensitive baselines
    clip.sources = [None, target]
    clip.docal = -1
    clip.flagver = outfgver
    clip.indata = data
    clip.outfgver = outfgver
    #clip.go()
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.opcode = 'FLAG'
    uvflg.antenna = [None, 15]
    uvflg.baselin = [None, 6]
    #uvflg.go()
    
    # Flag timeran with many failed sols
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.opcode = 'FLAG'
    uvflg.timeran = [None, 1, 0, 0, 0, 1, 2, 0, 0]
    uvflg.go()


if whattodo['selfcal_target_maser']:
    clinver = 1
    cloutver = 2
    snoutver = 1

    data = UV(target, MCLASS, DISK, 1)
    # Remove all SN tables higher than version snoutver-1.
    for i in range(data.table_highver('SN'), snoutver-1, -1):
        data.zap_table('SN', i)
        print "Deleting SN "+str(i)
    data = UV(target, MCLASS, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.calsour = [None, target]
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.snver = snoutver
    calib.ichansel[1] = [None, masercal_bchan, masercal_echan, 1, masercal_bif]
    calib.solmode = 'P'
    calib.soltype = 'L1'
    calib.weightit = 1
    calib.solint = 2
    calib.aparm[1] = 3 # Min no of antennas
    calib.aparm[7] = 2 # SNR
    calib.aparm[3] = 1 # AVG RR,LL, 
    calib.aparm[6] = 3 # Print level
    calib.uvrange = uvrange
    calib.go()

    # replace if 2-4 sols with if1
    sncor = task('sncor')
    sncor.indata = data
    sncor.opcode = 'CPSN'
    sncor.sncorprm[1] = 1 # maser IF
    sncor.bif = 2
    sncor.eif = 4
    sncor.snver = snoutver
    sncor.go()
    
    # Apply SN-table
    data = UV(target, MCLASS, DISK, 1)
    # Remove all CL tables higher than version cloutver-1.
    for i in range(data.table_highver('CL'), cloutver-1, -1):
        data.zap_table('CL', i)
    data = UV(target, MCLASS, DISK, 1)
    # Make CL table
    clcal = task('clcal') 
    clcal.default()
    clcal.indata = data
    clcal.snver = snoutver
    clcal.invers = snoutver
    clcal.calsour = [None, target]
    clcal.sour = [None, target]
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.opcode = 'CALP'
    clcal.go()

if whattodo['image_ARP220_maser_1']:
    arpfilename = NAME + 'MAS1'
    arpfiledisk = 1
    arpfileseq = 1
    arpfileclass = 'ICL001'
    clinver = 2
    # FIRST CLEAN WITH SMALL BOXES
    # Remove previous old images
    image = IM(arpfilename, arpfileclass, arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    # Also remove old beam images
    image = IM(arpfilename, 'IBM001', arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    data = UV(target, MCLASS, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.im2parm = [None, 1, 5.0, 10.0, 0] # Require island to have 
                                           # SNR 5 and peak SNR10.
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = masercal_nchav
    imagr.stokes = 'I'
    imagr.nfield = 1
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.uvrange = uvrange
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.niter = 100
    imagr.cellsize = [None, 0.40e-3, 0.40e-3]
    imagr.imsize =[None, 1024,1024]  
    imagr.gain = 0.1
    imagr.bchan = masercal_bchan
    imagr.echan = masercal_echan
    imagr.bif = masercal_bif
    imagr.eif = masercal_eif
    imagr.go()
    # CLEAN WITH LARGE (NO) BOXES
    arpboxfile = ''
    data = UV(target, MCLASS, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = masercal_nchav
    imagr.stokes = 'I'
    imagr.nfield = 1
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.uvrange = uvrange
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.outver = 1
    imagr.niter = 500
    imagr.cellsize = [None, 0.40e-3, 0.40e-3]
    imagr.imsize =[None, 1024,1024]  
    imagr.gain = 0.1
    imagr.bcomp = [None, 100000, 100000]
    imagr.bchan = masercal_bchan
    imagr.echan = masercal_echan
    imagr.bif = masercal_bif
    imagr.eif = masercal_eif
    imagr.go()

if whattodo['selfcal_target_maser_2']:
    clinver = 1
    cloutver = 3
    snoutver = 2

    data = UV(target, MCLASS, DISK, 1)
    # Remove all SN tables higher than version snoutver-1.
    for i in range(data.table_highver('SN'), snoutver-1, -1):
        data.zap_table('SN', i)
        print "Deleting SN "+str(i)
    data = UV(target, MCLASS, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.calsour = [None, target]
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.snver = snoutver
    calib.ichansel[1] = [None, masercal_bchan, masercal_echan, 1, masercal_bif]
    #calib.solmode = 'A&P'
    calib.solmode = 'P'
    calib.soltype = 'L1'
    calib.weightit = 1
    calib.in2data = IM(NAME + 'MAS1', 'ICL001', 1, 1)
    calib.nmaps = 1
    calib.solint = 1
    calib.aparm[1] = 3 # Min no of antennas
    calib.aparm[7] = 2# SNR
    calib.aparm[3] = 1 # AVG RR,LL, 
    calib.aparm[6] = 1 # Print level
    calib.uvrange = uvrange
    calib.go()
    
    # replace if 2-4 sols with if1
    sncor = task('sncor')
    sncor.indata = data
    sncor.opcode = 'CPSN'
    sncor.sncorprm[1] = 1 # maser IF
    sncor.bif = 2
    sncor.eif = 4
    sncor.snver = snoutver
    sncor.go()
    
    # Apply SN-table
    data = UV(target, MCLASS, DISK, 1)
    # Remove all CL tables higher than version cloutver-1.
    for i in range(data.table_highver('CL'), cloutver-1, -1):
        data.zap_table('CL', i)
    data = UV(target, MCLASS, DISK, 1)
    # Make CL table
    clcal = task('clcal') 
    clcal.default()
    clcal.indata = data
    #clcal.snver = snoutver+1
    #clcal.invers = snoutver+1
    clcal.snver = snoutver
    clcal.invers = snoutver
    clcal.calsour = [None, target]
    clcal.sour = [None, target]
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.opcode = 'CALP'
    clcal.go()

if whattodo['image_ARP220_maser_2']:
    arpfilename = NAME + 'MAS2'
    arpfiledisk = 1
    arpfileseq = 1
    arpfileclass = 'ICL001'
    clinver = 3
    # FIRST CLEAN WITH SMALL BOXES
    # Remove previous old images
    image = IM(arpfilename, arpfileclass, arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    # Also remove old beam images
    image = IM(arpfilename, 'IBM001', arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    data = UV(target, MCLASS, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.im2parm = [None, 1, 5.0, 10.0, 0] # Require island to have 
                                           # SNR 5 and peak SNR10.
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = masercal_nchav
    imagr.stokes = 'I'
    imagr.nfield = 1
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.uvrange = uvrange
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.niter = 100
    imagr.cellsize = [None, 0.40e-3, 0.40e-3]
    imagr.imsize =[None, 1024,1024]  
    imagr.gain = 0.1
    imagr.bchan = masercal_bchan
    imagr.echan = masercal_echan
    imagr.bif = masercal_bif
    imagr.eif = masercal_eif
    imagr.go()
    # CLEAN WITH LARGE (NO) BOXES
    arpboxfile = ''
    data = UV(target, MCLASS, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = masercal_nchav
    imagr.stokes = 'I'
    imagr.nfield = 1
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.uvrange = uvrange
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.outver = 1
    imagr.niter = 500
    imagr.cellsize = [None, 0.40e-3, 0.40e-3]
    imagr.imsize =[None, 1024,1024]  
    imagr.gain = 0.1
    imagr.bcomp = [None, 100000, 100000]
    imagr.bchan = masercal_bchan
    imagr.echan = masercal_echan
    imagr.bif = masercal_bif
    imagr.eif = masercal_eif
    imagr.go()

if whattodo['selfcal_target_maser_3']:
    clinver = 1
    cloutver = 4
    snoutver = 3

    data = UV(target, MCLASS, DISK, 1)
    # Remove all SN tables higher than version snoutver-1.
    for i in range(data.table_highver('SN'), snoutver-1, -1):
        data.zap_table('SN', i)
        print "Deleting SN "+str(i)
    data = UV(target, MCLASS, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.calsour = [None, target]
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.snver = snoutver
    calib.ichansel[1] = [None, masercal_bchan, masercal_echan, 1, masercal_bif]
    #calib.solmode = 'A&P'
    calib.solmode = 'P'
    calib.soltype = 'L1'
    calib.weightit = 1
    calib.in2data = IM(NAME + 'MAS2', 'ICL001', 1, 1)
    calib.nmaps = 1
    calib.solint = 1
    calib.aparm[1] = 3 # Min no of antennas
    calib.aparm[7] = 2# SNR
    calib.aparm[3] = 1 # AVG RR,LL, 
    calib.aparm[6] = 1 # Print level
    calib.uvrange = uvrange
    calib.go()
    
    # replace if 2-4 sols with if1
    sncor = task('sncor')
    sncor.indata = data
    sncor.opcode = 'CPSN'
    sncor.sncorprm[1] = 1 # maser IF
    sncor.bif = 2
    sncor.eif = 4
    sncor.snver = snoutver
    sncor.go()
    
    #snsmo = task('snsmo')
    #snsmo.indata = data
    #snsmo.inver = snoutver
    #snsmo.outver = snoutver+1
    #snsmo.smotype = 'AMPL'
    #snsmo.bparm[1] = 1.0/3600 # Smoothing in time in seconds to ensure no smoothing
    ## DO NOT SMOOTH; INSTEAD CLIP WITH MWF
    #snsmo.cparm[1] = 30.0/60 #in hours
    #snsmo.cparm[6] = 1.0 # Max amp deviation
    #snsmo.doblank = -1 # Since cannot be used with AMPL
    #snsmo.go()
    
    # Apply SN-table
    data = UV(target, MCLASS, DISK, 1)
    # Remove all CL tables higher than version cloutver-1.
    for i in range(data.table_highver('CL'), cloutver-1, -1):
        data.zap_table('CL', i)
    data = UV(target, MCLASS, DISK, 1)
    # Make CL table
    clcal = task('clcal') 
    clcal.default()
    clcal.indata = data
    #clcal.snver = snoutver+1
    #clcal.invers = snoutver+1
    clcal.snver = snoutver
    clcal.invers = snoutver
    clcal.calsour = [None, target]
    clcal.sour = [None, target]
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.opcode = 'CALP'
    clcal.go()

if whattodo['image_ARP220_maser_3']:
    arpfilename = NAME + 'MAS3'
    arpfiledisk = 1
    arpfileseq = 1
    arpfileclass = 'ICL001'
    clinver = 4
    # FIRST CLEAN WITH SMALL BOXES
    # Remove previous old images
    image = IM(arpfilename, arpfileclass, arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    # Also remove old beam images
    image = IM(arpfilename, 'IBM001', arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    data = UV(target, MCLASS, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.im2parm = [None, 1, 5.0, 10.0, 0] # Require island to have 
                                           # SNR 5 and peak SNR10.
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = masercal_nchav
    imagr.stokes = 'I'
    imagr.nfield = 1
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.uvrange = uvrange
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.niter = 100
    imagr.cellsize = [None, 0.40e-3, 0.40e-3]
    imagr.imsize =[None, 1024,1024]  
    imagr.gain = 0.1
    imagr.bchan = masercal_bchan
    imagr.echan = masercal_echan
    imagr.bif = masercal_bif
    imagr.eif = masercal_eif
    imagr.go()
    # CLEAN WITH LARGE (NO) BOXES
    arpboxfile = ''
    data = UV(target, MCLASS, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = masercal_nchav
    imagr.stokes = 'I'
    imagr.nfield = 1
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.uvrange = uvrange
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.outver = 1
    imagr.niter = 500
    imagr.cellsize = [None, 0.40e-3, 0.40e-3]
    imagr.imsize =[None, 1024,1024]  
    imagr.gain = 0.1
    imagr.bcomp = [None, 100000, 100000]
    imagr.bchan = masercal_bchan
    imagr.echan = masercal_echan
    imagr.bif = masercal_bif
    imagr.eif = masercal_eif
    imagr.go()

#if whattodo['split2']:
#    clinver = 4
#    fginver = 0
#    data = UV(target, MCLASS, DISK, 1)
#    split = task('split')
#    split.default()
#    split.indata = data
#    split.docal = 1
#    split.gainuse =clinver
#    split.flagver = fginver
#    split.outclass = 'SP2T'
#    tdata = UV(target, split.outclass, 1, 1)
#    if tdata.exists():
#        tdata.zap()
#    split.go()
#    idata = UV(target, 'SP2T', 1, 1)
#    odata = UV(target, 'SP2', 1, 1)
#    multi = task('multi')
#    multi.default()
#    multi.indata = idata
#    multi.outdata = odata
#    if odata.exists():
#        odata.zap()
#    multi.go()

#if whattodo['wtmod']:
#    data = UV(target, 'SP2', 1, 1)
#    tdata = UV(target, 'WTMAX', 1, 1)
#    wtmod = task('wtmod')
#    wtmod.default()
#    wtmod.indata = data
#    wtmod.outdata = tdata
#    wtmod.aparm = [None, 0, 0.5, 50]
#    if tdata.exists():
#        tdata.zap()
#    wtmod.go()

if whattodo['calculate_shifts']:
    # The maser self-calibration align the position to the wrong place, since
    # the maser was supposed to be in the wrong place. We fix this by changing
    # the coordinates of the output FITS images when saving to disk.  But, we
    # need to calculate the shifts from the "wrong" maser position here, to get
    # the images aligned pixelwise.
    # From the phase-referenced epoch BB297A we get the maser peak position as
    # R.A. 15h34m57s.22435
    # Dec. 23d30'11''.6644
    # which in decimal degrees, for AIPS, means
    maser_ra_bb297 = (15.0+34.0/60.0+57.22435/3600.0)*360.0/24 # degrees
    maser_dec_bb297 = 23+30.0/60.0+11.6644/3600.0 # degrees
    # Self-cal on maser will set the maser position to the source position in
    # the UVFITS header.
    # From AIPS memo 117, the UVFITS coordinates are defined as
    # RAAPP Source apparent equatorial position RA coordinate
    # DECAPP Source apparent equatorial position DEC coordinate
    # RAEPO Source J2000 equatorial position RA coordinate
    # DECPO Source J2000 equatorial position DEC coordinate
    # RAOBS Pointing right ascension of equinox
    # RADEC Pointing declination of equinox

    # We want to compare the RAEPO, DECEPO pair with the maser coordinates.
    # For the phased-referenced epochs, Arp 220 pointing is set between the
    # two nuclei at 15:34:57.2500  23:30:11.330, or in decimal deg
    # from BP129_C header:
    arp220_ra_bb297 = 233.73854166666666287711
    arp220_dec_bb297 = 23.50314722222221419656
    # Relative to these coordinates, we use the shifts 
    arp220_rashifts_bb297 = np.array([0.6, -0.35]) # in arcsec
    arp220_decshifts_bb297 = np.array([0.02, 0.18]) # in arcsec
    # to image the two Arp220 nuclei.
    # What are the corresponding shift for this epoch, i.e.
    # what would be the relative shifts with respect to the maser?

    # First, get the current maser coordinates
    wdata = WUV(target, MCLASS, 1, 1)
    sutab = wdata.table('SU',1)
    for row in sutab:
        if 'ARP220' in row.source:
            this_ra = row.raepo
            this_dec = row.decepo
    sutab.close()
    # this_ra, and this_dec are now the coordinates of the maser in this 
    # epoch. 
    # Then, calculate the difference between the actual maser position,
    # not the one in this epoch, and the point between the two nuclei
    #dmas_ra = maser_ra_bb297-this_ra
    #dmas_dec = maser_dec_bb297-this_dec
    dra = arp220_ra_bb297-maser_ra_bb297
    ddec = arp220_dec_bb297-maser_dec_bb297
    # now convert this to arcseconds, to have same unit as IMAGR wants
    # i.e. units of shifts given above
    dra_arcsec = dra*np.cos((np.pi/180.0)*arp220_dec_bb297)*3600 # scale with cos(DEC)
    ddec_arcsec = ddec*3600

    masercal_rashift = arp220_rashifts_bb297 + dra_arcsec
    masercal_decshift = arp220_decshifts_bb297 + ddec_arcsec
    # Convert to right type for imagr
    masercal_rashift = [float(i) for i in masercal_rashift]
    masercal_decshift = [float(i) for i in masercal_decshift]

if whattodo['flag_maser']:
    # FLAG maser for final imaging
    data = UV(target, MCLASS, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = 1
    uvflg.bif = masercal_bif
    uvflg.eif = masercal_eif
    uvflg.reason = 'Away with maser'
    uvflg.opcode = 'FLAG'
    uvflg.bchan = 10
    uvflg.echan = 20
    uvflg.go()

############### IMAGE ARP220 ######################
# Load these outside if to be available also for export later
arpfilename = TCALIM
arpfiledisk = 1
arpfileseq = 1
arpfileclass = 'ICL001'
arpfileclass2 = 'ICL002'
if whattodo['image_ARP220']:
    clinver = 4
    # FIRST CLEAN WITH SMALL BOXES
    # Remove previous old images
    image = IM(arpfilename, arpfileclass, arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    image = IM(arpfilename, arpfileclass2, arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    # Also remove old beam images
    image = IM(arpfilename, 'IBM001', arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    image = IM(arpfilename, 'IBM002', arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    data = UV(target, MCLASS, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.im2parm = [None, 1, 5.0, 10.0, 0] # Require island to have SNR 5 and peak SNR10. To clean (for later removal) of the strongest sources
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.imsize = [None, 2048,1024]
    imagr.cellsize = [None, 0.5e-3, 0.5e-3]
    imagr.stokes = 'I'
    imagr.nfield = 2
    imagr.overlap = 1
    imagr.do3dimag = 1
    imagr.rashift = [None,] + masercal_rashift
    imagr.decshift = [None,] + masercal_decshift
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.niter = 300
    imagr.gain = 0.1
    imagr.uvrange = uvrange # remove large-scale disturbances
    imagr.robust = 0.5
    imagr.bif = 1
    imagr.eif = 1
    imagr.go()
    # CLEAN WITH LARGE (NO) BOXES
    arpboxfile = ''
    data = UV(target, MCLASS, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.imsize = [None, 2048,1024]
    imagr.cellsize = [None, 0.5e-3, 0.5e-3]
    imagr.stokes = 'I'
    imagr.nfield = 2
    imagr.overlap = 1
    imagr.do3dimag = 1
    imagr.rashift = [None,] + masercal_rashift
    imagr.decshift = [None,] + masercal_decshift
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.outver = 1
    imagr.niter = 1000
    imagr.gain = 0.1
    imagr.bcomp = [None, 100000, 100000]
    imagr.uvrange = uvrange # remove large-scale disturbances
    imagr.robust = 0.5
    imagr.bif = 1
    imagr.eif = 1
    imagr.go()

if whattodo['selfcal_arp220']:
    clinver = 4
    cloutver = 5
    snoutver = 4
    data = UV(target, MCLASS, DISK, 1)
    # Remove all SN tables higher than version snoutver-1.
    for i in range(data.table_highver('SN'), snoutver-1, -1):
        print "WARNING: Deleting SN" + str(i)
        data.zap_table('SN', i)
    data = UV(target, MCLASS, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    # Do not use any model, just a point works fine for phasecal
    calib.in2data = IM(TCALIM, 'ICL001', 1, 1)
    calib.calsour = [None, target]
    calib.nmaps = 2
    calib.refant = 5
    calib.docalib = 1
    calib.gainuse = clinver
    calib.flagver = 0
    calib.snver = snoutver
    calib.solmode = 'P'
    calib.solint = 5
    #calib.aparm[1] = 3 # min No. of antennas
    calib.aparm[7] = 2 # SNR
    calib.aparm[3] = 1 # AVG RR,LL, 
    calib.aparm[6] = 1 # Print level
    #calib.aparm[5] = 1 # AVG ifs
    #calib.cmethod = 'DFT'
    calib.weightit = 1
    calib.soltype = 'L1'
    #calib.doband = 1
    #calib.bpver = 1
    calib.uvrange = uvrange
    calib.go()
    
    # Apply SN-table
    data = UV(target, MCLASS, DISK, 1)
    # Remove all CL tables higher than version cloutver-1.
    for i in range(data.table_highver('CL'), cloutver-1, -1):
        print "WARNING: Deleting CL" + str(i)
        data.zap_table('CL', i)
    data = UV(target, MCLASS, DISK, 1)
    # Make CL table
    clcal = task('clcal') 
    clcal.default()
    clcal.indata = data
    clcal.snver = snoutver
    clcal.invers = snoutver
    clcal.calsour = [None, target]
    clcal.sour = [None, target] # Apply to target
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.go()

############### IMAGE ARP220 ######################
# Load these outside if to be available also for export later
arpfilename = TCALIM+'V'
arpfiledisk = 1
arpfileseq = 1
arpfileclass = 'VCL001'
arpfileclass2 = 'VCL002'
if whattodo['image_ARP220_V']:
    clinver = 5
    # FIRST CLEAN WITH SMALL BOXES
    # Remove previous old images
    image = IM(arpfilename, arpfileclass, arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    image = IM(arpfilename, arpfileclass2, arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    # Also remove old beam images
    image = IM(arpfilename, 'VBM001', arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    image = IM(arpfilename, 'VBM002', arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    # CLEAN WITH LARGE (NO) BOXES
    arpboxfile = ''
    data = UV(target, MCLASS, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.imsize = [None, 2048,1024]
    imagr.cellsize = [None, 0.4e-3, 0.4e-3]
    imagr.stokes = 'V'
    imagr.nfield = 2
    imagr.overlap = 1
    imagr.do3dimag = 1
    imagr.rashift = [None,] + masercal_rashift
    imagr.decshift = [None,] + masercal_decshift
    imagr.docalib = -1
    imagr.dotv = -1
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.outver = 1
    imagr.niter = 1
    imagr.gain = 0.1
    imagr.uvrange = uvrange # remove large-scale disturbances
    imagr.robust = 0.5
    imagr.go()


############### IMAGE ARP220 ######################
# Load these outside if to be available also for export later
arpfilename = NAME + '_FIN'
arpfiledisk = 1
arpfileseq = 1
arpfileclass = 'ICL001'
arpfileclass2 = 'ICL002'
if whattodo['image_ARP220_final']:
    clinver = 5
    # FIRST CLEAN WITH SMALL BOXES
    # Remove previous old images
    image = IM(arpfilename, arpfileclass, arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    image = IM(arpfilename, arpfileclass2, arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    # Also remove old beam images
    image = IM(arpfilename, 'IBM001', arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    image = IM(arpfilename, 'IBM002', arpfiledisk, arpfileseq)
    if image.exists():
        image.zap()
    # Clean with latest gainuse
    data = UV(target, MCLASS, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.im2parm = [None, 1, 5.0, 10.0, 0] # Require island to have SNR5 and peak SNR10. To clean the strongest sources
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.imsize = [None, 8192, 8192]
    imagr.cellsize = [None, 0.1e-3, 0.1e-3]
    imagr.stokes = 'I'
    imagr.nfield = 2
    imagr.overlap = 1
    imagr.do3dimag = 1
    imagr.rashift = [None,] + masercal_rashift
    imagr.decshift = [None,] + masercal_decshift
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.niter = 300
    imagr.gain = 0.1
    imagr.uvrange = uvrange # remove large-scale disturbances
    imagr.robust = 0.5
    #imagr.robust = 5
    #imagr.antenna = [None, -14]
    imagr.go()
    # CLEAN WITH LARGE (NO) BOXES
    arpboxfile = ''
    data = UV(target, MCLASS, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.imsize = [None, 8192, 8192]
    imagr.cellsize = [None, 0.1e-3, 0.1e-3]
    imagr.stokes = 'I'
    imagr.nfield = 2
    imagr.overlap = 1
    imagr.do3dimag = 1
    imagr.rashift = [None,] + masercal_rashift
    imagr.decshift = [None,] + masercal_decshift
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.outver = 1
    imagr.niter = 1200
    imagr.gain = 0.1
    imagr.bcomp = [None, 100000, 100000]
    imagr.uvrange = uvrange # remove large-scale disturbances
    #imagr.antenna = vlba_antennas
    imagr.robust = 0.5
    #imagr.robust = 5
    #imagr.antenna = [None, -14]
    #imagr.bif = 2
    #imagr.eif = 2
    imagr.go()

############### EXPORT RESULTS ######################
if whattodo['export_results']:
    east = IM(arpfilename, arpfileclass, arpfiledisk, arpfileseq)
    west = IM(arpfilename, arpfileclass2, arpfiledisk, arpfileseq)
   
    # Export EAST
    fittp = task('fittp')
    fittp.default()
    fittp.indata = east
    fittp.dataout = 'PWD:'+NAME+'_EAST_IMAGE.FITS'
    if os.path.exists(fittp.dataout[4:]):
     os.system('rm ' + fittp.dataout[4:])
    fittp.go()
    # Change coordinates of file based on BB297A maser reference position
    f = fits.open(NAME+'_EAST_IMAGE.FITS', mode='update')
    hdr = f[0].header
    hdr['CRVAL1'] = arp220_ra_bb297+arp220_rashifts_bb297[0]/(3600.0*np.cos(arp220_dec_bb297*np.pi/180))
    hdr['CRVAL2'] = arp220_dec_bb297+arp220_decshifts_bb297[0]/(3600.0)
    f.flush()
    f.close()

    # Export WEST
    fittp = task('fittp')
    fittp.default()
    fittp.indata = west
    fittp.dataout = 'PWD:'+NAME+'_WEST_IMAGE.FITS'
    if os.path.exists(fittp.dataout[4:]):
     os.system('rm ' + fittp.dataout[4:])
    fittp.go()
    # Change coordinates of file based on BB297A maser reference position
    f = fits.open(NAME+'_WEST_IMAGE.FITS', mode='update')
    hdr = f[0].header
    hdr['CRVAL1'] = arp220_ra_bb297+arp220_rashifts_bb297[1]/(3600.0*np.cos(arp220_dec_bb297*np.pi/180))
    hdr['CRVAL2'] = arp220_dec_bb297+arp220_decshifts_bb297[1]/(3600.0)
    f.flush()
    f.close()
    
    # Export J1516
    fittp = task('fittp')
    fittp.default()
    fittp.indata = IM(AMPCALIM+'1', 'ICL001', 1, 1)
    fittp.dataout = 'PWD:'+NAME+'_J1516_IMAGE.FITS'
    if os.path.exists(fittp.dataout[4:]):
     os.system('rm ' + fittp.dataout[4:])
    fittp.go()
    
    # Export MASER
    masim = IM(NAME+'MAS3', 'ICL001', 1, 1)
    fittp = task('fittp')
    fittp.default()
    fittp.indata = masim
    fittp.dataout = 'PWD:'+NAME+'_MASER_IMAGE.FITS'
    if os.path.exists(fittp.dataout[4:]):
     os.system('rm ' + fittp.dataout[4:])
    fittp.go()
    # Change coordinates of file based on BB297A maser reference position
    f = fits.open(NAME+'_MASER_IMAGE.FITS', mode='update')
    hdr = f[0].header
    hdr['CRVAL1'] = maser_ra_bb297
    hdr['CRVAL2'] = maser_dec_bb297
    f.flush()
    f.close()

    

tac = time.time()
processtime = tac-tic
print 'OVERALL PROCESS TIME: ',processtime,' SECONDS. or ', processtime/60.0, 'minutes'

