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

vlba_antennas = [None, 7, 8, 9, 10, 11, 12, 15, 16, 17, 18]
non_vlba_antennas = [None, 1,2,3,4,5,6, 13, 14]
#Ant   1 = EB       BX= -3147194.1798 BY=  4061072.1147 BZ=  1059263.5923
#Ant   2 = JB       BX= -2545993.0806 BY=  3754908.4885 BZ=  1245118.6859
#Ant   3 = MC       BX= -3509711.9779 BY=  4549353.8368 BZ=   608391.9811
#Ant   4 = TR       BX= -3933785.9058 BY=  3782145.0336 BZ=  1235869.5313
#Ant   5 = WB       BX= -3137189.0113 BY=  3851607.6300 BZ=  1223754.3492
#Ant   6 = GB       BX=  1722024.0713 BY=   122794.4478 BZ=   102562.0960
#Ant   7 = HN       BX=  1336449.2821 BY=   752596.7257 BZ=   481138.8547
#Ant   8 = SC       BX=  2541227.2291 BY=  1742243.7844 BZ= -1908427.6647
#Ant   9 = FD       BX=  1788767.8133 BY= -2120088.6234 BZ=  -609204.8661
#Ant  10 = LA       BX=  1416904.8413 BY= -2190053.2058 BZ=  -132043.4156
#Ant  11 = NL       BX=  1407124.0802 BY=  -854122.7619 BZ=   385683.7210
#Ant  12 = PT       BX=  1426863.1133 BY= -2385041.4668 BZ=  -265755.4771
#Ant  13 = Y        BX=  1459760.2076 BY= -2349869.8534 BZ=  -286291.6579
#Ant  14 = AR       BX=  2583915.8702 BY=  1515746.9744 BZ= -1846446.8082
#Ant  15 = BR       BX=    60958.8507 BY= -2651378.8512 BZ=   885646.4306
#Ant  16 = KP       BX=  1395117.2567 BY= -2739058.8138 BZ=  -483839.2248
#Ant  17 = OV       BX=   779955.3120 BY= -3062678.8666 BZ=    -2549.9327
#Ant  18 = MK       BX= -1645193.7723 BY= -5780176.5929 BZ= -1692870.1954

# 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.
# IF1 has LowerEdge at 1634 MHz with 32 channels covering 8MHz. This means that 
# masers are in middle 16 channels 9 to 24. These 16 channels cover
# 4MHz in bandwidth, i.e. from 1634 to 1638 MHz. 
# From possm we see that peak is mostly in channel 17, but from iterative
# selfcal the elongated structure is best seen if using ch 18.
#masercal_bchan = 17
#masercal_echan = 17
masercal_bchan = 18
masercal_echan = 18
masercal_bif = 1
masercal_eif = 1
masercal_nchav = 512


whattodo = {'load_data': False, # ->CL1
            'preflagging': False,
            'ion_corr': False, # ->CL2
            'eops_corr': False, # ->CL3
            'par_ang_cor': False, # ->CL4
            'apriori_ampcal' : False, # SN1,CL5,
            # Flat (1.0) ampcal for antennas 2,6,13
            # technically, JB is in antab file but 
            # the antab records are crap (also said in the antab file)
            # So antab here ignores JB. 6,13 can be fixed later while ants 1-5 are ignored since no way to calibrate these was found.
            'fring_ampcal+ff' : False, #->SN3, CL6
            'bpass_ff': False, # BP 1
            'image_ff_1': False, 
            'selfcal_ff' : False, # -> SN5, CL7 # Correct VLBA
            'image_ff_2': False, 
            'selfcal_ff_2' : False, # -> SN6, CL8 # Correct ants 6,13,14
            'image_ff_3': False,
            'selfcal_ff_3' : False, # -> SN7, CL9 # Correct ants 1,2,3,4,5
            # NOTE: 1613+341 did not correct 1,2,3,4,5 properly. Need to do this better with maser later.
            # Check UVplot of 1613+341 to see the problem, mostly below 10000 klambda.
            'image_ff_4': False, 
            # Make image of J1516+1932 for reference to other epochs. 
            # First need phasecal.
            'selfcal_ampcal' : False, # -> SN8, CL10 # pcal only
            'image_ampcal_1': False, 
            # Phase cal of maser
            'selfcal_target_maser' : False, # -> SN9, CL11. USING POINT MODEL. 
            'image_ARP220_maser_1': False,
            'selfcal_target_maser_2' : False, # -> SN10, CL12 Using image model, PHASE ONLY, 1min
            'image_ARP220_maser_2': False,
            'selfcal_target_maser_3' : False, # -> SN11, . AMP + PHASE. Using model 2, 5min.
            'apply_maser_ampcal': False, # _> SN12, CL13
            'image_ARP220_maser_3': False,
            'split': False,
            'fixwt': False,
            'multi': False,
            'calculate_shifts': True, # Calculate shifts for Arp220 imaging. MUST be enabled to set variables used by imaging.
            'flag_maser': False,
            'image_ARP220': False, 
            'selfcal_arp220': False, # ->SN1, CL2
            'image_ARP220_V': False,
            ######
            'image_ARP220_final': False,
            'export_results': True,
            }

########## Initialize observation data ##########
AIPS.userno = 1000
clint = 1.0/60 # Seconds
NAME = '017B_L'
CLASS = 'UVDATA'
WTCLASS = 'WTMAX'
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 = 10
#########^^^ 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, CLASS, DISK, 1)
    fitld.datain = '/data1/eskil/RAWDATA/GD017B/GD017B_P1_4IF.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 + '.' + CLASS
        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()
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 1]
    uvflg.timeran = [None, 1, 4, 55, 0, 1, 5, 10, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 8]
    uvflg.sour = [None, ff]
    uvflg.timeran = [None, 1, 12, 0, 0, 1, 14, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 8]
    uvflg.sour = [None, '']
    uvflg.timeran = [None, 1, 15, 0, 0, 1, 18, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 13]
    uvflg.stokes = 'LL'
    uvflg.bif = 4
    uvflg.eif = 4
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 6,13]
    uvflg.sour = [None, ff]
    uvflg.timeran = [None, 1, 0, 0, 0, 1, 6, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 1, 2]
    uvflg.sour = [None, ff]
    uvflg.timeran = [None, 1, 3, 48, 0, 1, 4, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 4,5]
    uvflg.sour = [None, ff]
    uvflg.timeran = [None, 1, 5, 0, 0, 1, 5, 10, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 4]
    uvflg.sour = [None, ff]
    uvflg.timeran = [None, 0, 22, 0, 0, 1, 0, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 2]
    uvflg.sour = [None, ff]
    uvflg.timeran = [None, 1,5,0,0,1,5,10,0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 2]
    uvflg.sour = [None, ff]
    uvflg.timeran = [None, 1,5,0,0,1,5,10,0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 2,5]
    uvflg.sour = [None, ff]
    uvflg.timeran = [None, 0, 0, 0, 0, 0, 22, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 13]
    uvflg.bif = 4
    uvflg.eif = 4
    uvflg.sour = [None, ampcal]
    uvflg.timeran = [None, 1, 8, 30, 0, 1, 9, 30, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 14]
    uvflg.sour = [None, ampcal]
    uvflg.timeran = [None, 1, 6, 30, 0, 1, 7, 30, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    #uvflg.antenna = [None, 14, 1]
    uvflg.sour = [None, ampcal]
    uvflg.timeran = [None, 1, 8, 40, 0, 1, 8, 52, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 13]
    uvflg.sour = [None, ampcal]
    uvflg.timeran = [None, 1, 8, 30, 0, 1, 9, 30, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Quack
    quack = task('quack')
    quack.default()
    quack.indata = data
    quack.opcode = 'BEG'
    quack.antenna = [None, 14]
    quack.aparm[2] = 30.0/60
    quack.go()
    quack = task('quack')
    quack.default()
    quack.indata = data
    quack.antenna = [None, 14]
    quack.opcode = 'ENDB'
    quack.aparm[2] = 30.0/60
    quack.go()
    
    # Flag if with no fringes to FF
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 4]
    uvflg.bif = 2
    uvflg.eif = 2
    uvflg.stokes = 'RR'
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag scan with relatively high delay to not extrapolate this to the early times
    # since FRING fails with this source earlier than 1 5 0 0
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 3]
    uvflg.sour = [None, ff]
    uvflg.timeran = [None, 1, 5, 0, 0, 1, 5, 10, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    # Flag all data before 1 5 0 0 since no good delays here
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 0, 0, 0, 0, 1, 5, 0, 0]
    uvflg.opcode = 'FLAG'
    #uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 6, 7]
    uvflg.timeran = [None, 1, 14, 10, 0, 1, 14, 32, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 6]
    uvflg.baselin = [None, 7]
    uvflg.timeran = [None, 1, 13, 50, 0, 1, 13, 55, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 9]
    uvflg.timeran = [None, 1, 15, 50, 0, 1, 16, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 11]
    uvflg.timeran = [None, 1, 14, 30, 0, 1, 15, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 7]
    uvflg.baselin = [None, 8]
    uvflg.timeran = [None, 1, 7, 20, 0, 1, 7, 25, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 6]
    uvflg.baselin = [None, 18]
    uvflg.timeran = [None, 1, 17, 0, 0, 2, 0, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 6]
    uvflg.timeran = [None, 1, 16, 20, 0, 1, 16, 30, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 9,16]
    uvflg.timeran = [None, 1, 6, 5, 0, 1, 6, 15, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 10,12]
    uvflg.timeran = [None, 1, 15, 40, 0, 1, 15, 50, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 15,16]
    uvflg.timeran = [None, 1, 10, 5, 0, 1, 10, 16, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 16,17]
    uvflg.timeran = [None, 1, 8, 7, 0, 1, 8, 12, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 1, 5, 55, 0, 1, 5, 57, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 1, 17, 15, 30, 1, 17, 16, 30]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 1, 15, 13, 0, 1, 15, 15, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 1, 14, 54, 0, 1, 15, 1, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 1, 15, 48, 0, 1, 15, 49, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 5]
    uvflg.timeran = [None, 1, 7, 54, 0, 1, 8, 24, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    
    # Flag bad scan
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 14]
    uvflg.timeran = [None, 0, 0, 0, 0, 1, 7, 40, 0]
    uvflg.opcode = 'FLAG'
    uvflgsour = [None, target]
    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 6-MAR-2005. 
    # According to http://mistupid.com/calendar/dayofyear.htm
    # This means day of the year DDD=65
    # Fetch and uncompress file for this day
    doy = '065'
    year = str(2005)
    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 = '066'
    year = str(2005)
    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 = '065'
    year = str(2005)
    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 # and 2
    tyinver = 1
    tyoutver = 2
    gcinver = 1
    gcoutver = 2
    # First calibrate those antennas included with FITS file in GC and TY, 
    # i.e. VLBA + EB.
    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)
    # 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 = 1
    apcal.gcver = 1
    apcal.snver = snoutver
    apcal.invers = 1 # WX table version
    apcal.solint = 2 
    apcal.opcode = ''
    apcal.freqid = 1
    apcal.sources = [None, '']
    apcal.antenna = vlba_antennas + [1,]
    apcal.go()

    
    # Then, calibrate the other antennas present in the antab file found
    # from google.
    antab = task('antab')
    data = UV(NAME, sorted_class, DISK, 1)
    antab.indata = data
    antab.calin = 'PWD:gd017b.antab_noEB_noJB'
    antab.tyver = tyoutver
    antab.gcver = gcoutver
    antab.blver = -1
    antab.offset = 0.5
    antab.go()
    apcal = task('apcal')
    apcal.indata = data
    apcal.tyver = tyoutver
    apcal.gcver = gcoutver
    apcal.snver = snoutver+1
    apcal.invers = 1 # WX table version
    apcal.solint = 2 
    apcal.opcode = ''
    apcal.freqid = 1
    apcal.sources = [None, '']
    apcal.antenna = [None, 2,3,4,5,6,13,14]
    apcal.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
    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.uvrange = uvrange
    #fring.aparm[1] = 2 #Minant
    #fring.aparm[7] = 3 #SNR
    fring.timeran = [None, 1, 5, 0, 0, 2, 0, 0, 0]
    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)
    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 = 1
    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.4e-3, 0.4e-3]
    imagr.imsize = [None, 1024, 1024]
    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.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']:
    clinver = 6
    cloutver = 7
    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 + '1', 'ICL001', 1, 1)
    calib.calsour = [None, ff]
    calib.refant = 9
    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.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 = 10
    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.4e-3, 0.4e-3]
    imagr.imsize = [None, 1024, 1024]
    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 = 6
    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 = 10
    calib.docalib = 1
    calib.gainuse = clinver
    calib.flagver = 0
    calib.snver = snoutver
    calib.solmode = 'A&P'
    calib.solint = 5 # 
    calib.aparm[1] = 4 # Min no antennas
    calib.aparm[7] = 5 # SNR
    calib.cmethod = 'DFT'
    calib.aparm[6] = 1 # Print level
    calib.antenna = vlba_antennas + [6, 13, 14]
    calib.dofit = [None, 6,13,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, 6, 13, 14]
    clcal.calsour = [None, ff] # Use sols from Ampcal 
    clcal.sour = [None, ''] # Apply to all sources
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = 10
    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.4e-3, 0.4e-3]
    imagr.imsize = [None, 1024, 1024]
    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 + [6, 13,14]
    imagr.baselin = imagr.antenna
    imagr.uvrange = 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.go()

if whattodo['selfcal_ff_3']:
    clinver = 8
    cloutver = 9
    snoutver = 7
    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 + '3', 'ICL001', 1, 1)
    calib.calsour = [None, ff]
    calib.refant = 10
    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] = 3 # SNR
    calib.cmethod = 'DFT'
    calib.aparm[6] = 1 # Print level
    #calib.aparm[9] = 1 # Pass on failed sols, for vlba only scans
    #calib.antenna = vlba_antennas + [2, 5, 6, 13, 14]
    calib.dofit = [None, 1,2,3,4,5]
    calib.doband = 1
    calib.bpver = 1
    #calib.uvrange = uvrange
    calib.timeran = [None, 1, 5, 0, 0, 1, 11, 0, 0]
    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, 1,2,3,4,5]
    clcal.calsour = [None, ff] # Use sols from Ampcal 
    clcal.sour = [None, ''] # Apply to all sources
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = 10
    clcal.go()
#
if whattodo['image_ff_4']:
    clinver = 9
    imagename = FFCALIM+'4'
    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.4e-3, 0.4e-3]
    imagr.imsize = [None, 1024, 1024]
    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 = [None, 10000, 0]
    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_ampcal']:
    clinver = 9
    cloutver = 10
    snoutver = 8
    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.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.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.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 = 10
    imagename = AMPCALIM+'1'
    imagedisk = 1
    imageseq = 1
    data = UV(NAME, sorted_class, 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.4e-3, 0.4e-3]
    imagr.imsize = [None, 1024, 1024]
    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.go()

if whattodo['selfcal_target_maser']:
    clinver = 10
    cloutver = 11
    snoutver = 9
    bpinver = 1

    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)
        print "Deleting SN "+str(i)
    data = UV(NAME, sorted_class, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.calsour = [None, target]
    calib.refant = 6
    calib.docalib = 1
    calib.gainuse = clinver
    calib.doband = 1
    calib.bpver = bpinver
    calib.snver = snoutver
    calib.ichansel[1] = [None, masercal_bchan, masercal_echan, 1, masercal_bif]
    calib.solmode = 'P'
    calib.soltype = 'L1R'
    calib.weightit = 1
    calib.solint = 1
    calib.aparm[1] = 3 # Min no of antennas
    calib.aparm[7] = 1 # 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(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, 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'
    bpinver = 1
    clinver = 11
    # 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(NAME, sorted_class, 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.doband = 1
    imagr.bpver = bpinver
    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.antenna = [None, -14]
    #imagr.antenna = vlba_antennas
    #imagr.baselin = imagr.antenna
    imagr.go()
    # CLEAN WITH LARGE (NO) BOXES
    arpboxfile = ''
    data = UV(NAME, sorted_class, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.doband = 1
    imagr.bpver = bpinver
    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 = 300
    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.antenna = vlba_antennas
    #imagr.baselin = imagr.antenna
    imagr.antenna = [None, -14]
    imagr.go()

if whattodo['selfcal_target_maser_2']:
    clinver = 10
    cloutver = 12
    bpinver = 1
    snoutver = 10

    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)
        print "Deleting SN "+str(i)
    data = UV(NAME, sorted_class, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.calsour = [None, target]
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.doband = 1
    calib.bpver = bpinver
    calib.snver = snoutver
    calib.ichansel[1] = [None, masercal_bchan, masercal_echan, 1, masercal_bif]
    calib.solmode = 'P'
    calib.soltype = 'L1R'
    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] = 1# 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(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, 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'
    bpinver = 1
    clinver = 12
    # 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(NAME, sorted_class, 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.doband = 1
    imagr.bpver = bpinver
    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.antenna = [None, -14]
    imagr.go()
    # CLEAN WITH LARGE (NO) BOXES
    arpboxfile = ''
    data = UV(NAME, sorted_class, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.doband = 1
    imagr.bpver = bpinver
    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 = 300
    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.antenna = [None, -14]
    imagr.go()

if whattodo['selfcal_target_maser_3']:
    clinver = 12
    bpinver = 1
    snoutver = 11

    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)
        print "Deleting SN "+str(i)
    data = UV(NAME, sorted_class, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.calsour = [None, target]
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.doband = 1
    calib.bpver = bpinver
    calib.snver = snoutver
    calib.ichansel[1] = [None, masercal_bchan, masercal_echan, 1, masercal_bif]
    calib.solmode = 'A&P'
    calib.soltype = 'L1R'
    calib.weightit = 1
    calib.in2data = IM(NAME + 'MAS2', 'ICL001', 1, 1)
    calib.nmaps = 1
    calib.solint = 10
    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()
    
if whattodo['apply_maser_ampcal']:
    cloutver = 13
    clinver = 12
    sninver = 11
    snoutver = 12
    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)
        print "Deleting SN "+str(i)
    data = UV(NAME, sorted_class, DISK, 1)
    snsmo = task('snsmo')
    snsmo.indata = data
    snsmo.inver = sninver
    snsmo.outver = snoutver
    snsmo.smotype = 'BOTH'
    snsmo.bparm[1] = 2.0 # Smoothing time in hours
    snsmo.bparm[2] = 2.0 # Smoothing time in hours
    snsmo.cparm[1] = 2.0 # MWF filter width in hours
    snsmo.cparm[6] = 1 # Max amp deviation, MWF 
    snsmo.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, 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'
    bpinver = 1
    clinver = 13
    # 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(NAME, sorted_class, 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.doband = 1
    imagr.bpver = bpinver
    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.antenna = [None, -14]
    imagr.go()
    # CLEAN WITH LARGE (NO) BOXES
    arpboxfile = ''
    data = UV(NAME, sorted_class, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.doband = 1
    imagr.bpver = bpinver
    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 = 300
    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.antenna = [None, -14]
    imagr.go()

if whattodo['split']:
    clinver = 13
    fginver = 0
    data = UV(NAME, sorted_class, DISK, 1)
    split = task('split')
    split.default()
    split.indata = data
    split.docal = 1
    split.doband = 1
    split.bpver = 1
    split.sour = [None, target]
    split.gainuse =clinver
    split.flagver = fginver
    split.outclass = 'SP'
    tdata = UV(target, split.outclass, 1, 1)
    if tdata.exists():
        tdata.zap()
    split.go()

if whattodo['fixwt']:
    idata = UV(target, 'SP', 1, 1)
    odata = UV(target, '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']:
    idata = UV(target, 'FIXWT', 1, 1)
    odata = UV(target, 'MULTI', 1, 1)
    multi = task('multi')
    multi.default()
    multi.indata = idata
    multi.outdata = odata
    if odata.exists():
        odata.zap()
    multi.go()
    indxr = task('indxr')
    indxr.default()
    data = UV(target, 'MULTI', DISK, 1)
    indxr.indata = data
    indxr.cparm[3] = clint
    indxr.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, 'MULTI', 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, 'MULTI', 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 = 1
    # 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, 'MULTI', 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.doband = -1
    imagr.bpver = 1
    imagr.imsize = [None, 1024,512]
    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, 'MULTI', DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.doband = -1
    imagr.bpver = 1
    imagr.imsize = [None, 1024,512]
    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 = 500
    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 = 1
    cloutver = 2
    snoutver = 1
    data = UV(target, 'MULTI', 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, 'MULTI', 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, 'MULTI', 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, 'MULTI', 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 = 2
    # 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, 'MULTI', DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.doband = -1
    imagr.bpver = 1
    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.antenna = [None, -14] # Skip AR
    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 = 2
    # 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, 'MULTI', 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.doband = -1
    imagr.bpver = 1
    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.go()
    # CLEAN WITH LARGE (NO) BOXES
    arpboxfile = ''
    data = UV(target, 'MULTI', DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.doband = -1
    imagr.bpver = 1
    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 = 500
    imagr.gain = 0.1
    imagr.bcomp = [None, 100000, 100000]
    imagr.uvrange = uvrange # remove large-scale disturbances
    imagr.robust = 0.5
    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 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'

