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
import time
import numpy as np
#Ant   1 = EF       BX= -1451645.5791 BY=  3786340.9131 BZ=   862180.4454
#Ant   2 = JB       BX=  -986310.3578 BY=  3297830.8819 BZ=  1048035.5421
#Ant   3 = ON       BX= -1962418.3083 BY=  3307754.7647 BZ=  1311413.6547
#Ant   4 = MC       BX= -1631350.0182 BY=  4367326.7210 BZ=   411308.8375
#Ant   5 = NT       BX= -1762122.2367 BY=  4974036.2759 BZ=  -231765.8301
#Ant   6 = TR       BX= -2286225.5871 BY=  3784586.6227 BZ=  1038786.3816
#Ant   7 = WB       BX= -1511799.0894 BY=  3585450.3272 BZ=  1026671.2035
#Ant   8 = SC       BX=  3143280.5078 BY=  -290638.0226 BZ= -2105510.8099
#Ant   9 = HN       BX=  1678145.4776 BY=  -823808.3908 BZ=   284055.6816
#Ant  10 = NL       BX=  1211005.5588 BY= -2362743.9740 BZ=   188600.5313
#Ant  11 = FD       BX=  1150379.6097 BY= -3683594.4480 BZ=  -806288.0662
#Ant  12 = LA       BX=   776394.7075 BY= -3626040.9356 BZ=  -329126.6146
#Ant  13 = PT       BX=   721006.4035 BY= -3813261.9930 BZ=  -462838.6781
#Ant  14 = KP       BX=   573448.6086 BY= -4136623.6775 BZ=  -680922.4276
#Ant  15 = OV       BX=  -114287.4616 BY= -4237486.4097 BZ=  -199633.1275
#Ant  16 = BR       BX=  -655797.6047 BY= -3610676.7500 BZ=   688563.2252
#Ant  17 = AR       BX=  3108295.3693 BY=  -518451.9051 BZ= -2043529.9495

# Used for amp selfcal etc. We trust the VLBA.
vlba_antennas = [None, 8, 9, 10, 11, 12, 13, 14, 15, 16]

whattodo = {'load_data': True, # ->CL1
            'load_tables': True,
            'msort': True,
            'indxr': True,
            'preflagging': True,
            'copy_JIVE_CL': True, #-> CL2. 
            # This Cl Contains A priori AMP, Parr. angle. 
            # Also fixes factor of 2 in ampcal 
            # (from inspection) for ant 1 in beginning.
            'fring_ampcal' :True, #->SN1, CL3
            'bpass_ampcal': True, # BP 1
            'image_ampcal_1': True, 
            'selfcal_ampcal' : True, # -> SN2, CL4
            'image_ampcal_2': True, 
            'fring_phasecal' : True, #->SN3, CL5
            'clip_phasecal': True, #USE PREFLAGGING AS WELL TO CLEAN FG
            # Also clip target at the same time
            # Image and selfcal on pcal in two runs,
            # since antennas 1 and 17 require special attention
            #, i.e. their single run
            'image_phasecal_1':True,
            'selfcal_phasecal' : True, # -> SN4, 5, CL6
            'image_phasecal_2': True, # 
            'selfcal_phasecal_2' : True, # -> SN6, CL7
            'image_phasecal_3': True, # 
            'image_ARP220': True, # Phase error on AR, ant 17.
            # So, omit this antenna when making first images
            # Since the weight is so high.
            'selfcal_arp220': True, # ->SN7, CL8
            'image_ARP220_2': True, # Still omit AR
            # Now calibrate AR
            'selfcal_arp220_2': True, # ->SN8, CL9
            'image_ARP220_final': True,
            'fring_frcal' : True, #->SN9, CL10
            'image_frcal_1': True, 
            'selfcal_frcal' : True, # -> SN10, CL11
            'image_frcal_2': True, 
            'export_results': True,
            'save_calsols': True,
            }
 
########## Initialize observation data ##########
AIPS.userno = 1000
clint = 15.0/60 # Seconds, same as JIVE table
NAME = 'GC031A_C'
TABNAME = NAME
CLASS = 'UVDATA'
TABCLASS = 'TAB'
DISK = 1
AMPCALIM = NAME + 'AC'
PCALIM = NAME + 'PC'
TCALIM = NAME + 'TC'
TCALIM2 = TCALIM + '2'
FRCALIM = NAME + '_FC'
OUTPREFIX = NAME
target = 'ARP220'
ampcal = 'J1516+1932'
phasecal = 'J1532+2344'
frcal = 'J1613+3412'
sorted_class = 'MSORT'
logfile = 'log_'+OUTPREFIX+'_PTred.log'
refant = 2
uvrange = [None, 7000, 0]
#########^^^ 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/GC031A/gc031a_1_1.IDI1'
    fitld.outdata = outdata
    fitld.ncount = 1
    fitld.digicor = -1 # Not for JIVE
    fitld.clint = clint
    fitld.wtthresh = 0.3 # Else autoflag good data!
    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()

######### LOAD CAL TABLES ########
if whattodo['load_tables']:
    fitld = task('fitld')
    fitld.default()
    outdata = UV(TABNAME, TABCLASS, DISK, 1)
    fitld.datain = '/data1/eskil/RAWDATA/GC031A/gc031a.tasav.FITS'
    fitld.outdata = outdata
    fitld.ncount = 1
    if outdata.exists():
        print 'WARNING: Removing existing file ' + TABNAME + '.' + TABCLASS
        outdata.zap()
        print '         File removed. Proceeding with FITLD...'
    fitld.go()

if whattodo['msort']:
    msort = task('msort')
    data = UV(NAME, CLASS, DISK, 1)
    outdata = UV(NAME, sorted_class, DISK, 1)
    msort.default()
    msort.indata = data
    msort.outdata = outdata
    msort.sort = 'TB'
    if outdata.exists():
        print 'WARNING: Removing existing file ' + NAME + '.' + sorted_class
        outdata.zap()
        print '         File removed. Proceeding with FITLD...'
    msort.go()
    if data.exists():
        print 'WARNING: Removing existing file ' + NAME + '.' + CLASS
        data.zap()
        print '         File removed. Proceeding with FITLD...'

if whattodo['indxr']:
    indxr = task('indxr')
    indxr.default()
    data = UV(NAME, sorted_class, DISK, 1)
    indxr.indata = data
    indxr.cparm[3] = clint
    indxr.go()

########## PREFLAGGING ##########
#Flag data known to be bad (whole antennas etc.)
if whattodo['preflagging']:
    # Copy flag table provided from JIVE
    # This will flag when antennas off source etc.
    indata = UV(TABNAME, TABCLASS, DISK, 1)
    outdata = UV(NAME, sorted_class, DISK, 1)
    # Remove all FG tables
    outdata.zap_table('FG', -1)
    tacop = task('tacop')
    tacop.default()
    tacop.indata = indata
    tacop.outdata = outdata
    tacop.inext = 'FG'
    tacop.inver = 1
    tacop.outver = 1
    tacop.go()
    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 antennas known to be bad = Onsala (3) and PT (13)
   # NOTE: 4 has data, but very, very little. complicats cal.
   # Flag also ant 4
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 3, 13, 4]
    uvflg.reason = 'no data'
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag ant 5 NT if 2L since no solutions found
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 5]
    uvflg.bif = 2
    uvflg.eif = 2
    uvflg.stokes = 'LL'
    uvflg.reason = 'Weak, no sols found'
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 1]
    uvflg.timeran = [None, 0, 15, 0, 0, 0, 15, 10, 0]
    uvflg.sour = [None, ampcal]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 0]
    uvflg.timeran = [None, 0, 23, 0, 0, 0, 23, 30, 0]
    uvflg.sour = [None, ampcal]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 0]
    uvflg.timeran = [None, 1, 2, 30, 0, 1, 3, 0, 0]
    uvflg.sour = [None, ampcal]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 0]
    uvflg.timeran = [None, 1, 1, 10, 0, 1, 1, 30, 0]
    uvflg.sour = [None, ampcal]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 9]
    uvflg.timeran = [None, 0, 22, 30, 0, 0, 22, 40, 0]
    uvflg.sour = [None, ampcal]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 9]
    uvflg.timeran = [None, 1, 0, 50, 0, 1, 1, 10, 0]
    uvflg.sour = [None, ampcal]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 2]
    uvflg.timeran = [None, 1, 2, 0, 0, 1, 2, 10, 0]
    uvflg.bif = 4
    uvflg.eif = 4
    uvflg.stokes = 'RR'
    uvflg.sour = [None, ampcal]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 9]
    uvflg.timeran = [None, 1, 2, 30, 0, 1, 5, 0, 0]
    uvflg.bif = 4
    uvflg.eif = 4
    uvflg.stokes = 'RR'
    uvflg.sour = [None, ampcal]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 15]
    uvflg.timeran = [None, 0, 23, 30, 0, 0, 23, 40, 0]
    uvflg.sour = [None, ampcal]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 15]
    uvflg.bif = 3
    uvflg.eif = 3
    uvflg.timeran = [None, 1, 3, 30, 0, 1, 4, 10, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 15]
    uvflg.timeran = [None, 0, 0, 0, 0, 1, 0, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 14]
    uvflg.timeran = [None, 0, 22, 30, 0, 0, 23, 0, 0]
    uvflg.sour = [None, ampcal]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 14,15]
    uvflg.timeran = [None, 1,2, 0, 0, 1, 2, 30, 0]
    uvflg.sour = [None, ampcal]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antennas = [None, 17]
    uvflg.timeran = [None, 1,3,0,0,1,4,0,0]
    uvflg.sour = [None, ampcal]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan, delay pcal
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 1, 1, 50, 0, 1, 2, 10, 0]
    uvflg.bif = 4
    uvflg.eif = 4
    uvflg.stokes = 'RR'
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan, delay pcal
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 10]
    uvflg.timeran = [None, 1, 3, 30, 0, 1, 4, 10, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    # Quack all
    quack = task('quack')
    quack.default()
    quack.indata = data
    quack.opcode = 'BEG'
    quack.aparm[2] = 10.0/60
    quack.sour = [None, ampcal]
    quack.go()
    # Quack all
    quack = task('quack')
    quack.default()
    quack.indata = data
    quack.opcode = 'ENDB'
    quack.aparm[2] = 10.0/60
    quack.sour = [None, ampcal]
    quack.go()
   #Flag bad scan for JB
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 2]
    uvflg.timeran = [None, 0, 18, 42, 0, 0, 18, 44, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan for JB
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 2]
    uvflg.timeran = [None, 1, 2, 55, 0, 1, 2, 57, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan for JB
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 2]
    uvflg.timeran = [None, 0, 15, 25, 0, 0, 15, 32, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan for JB
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 2]
    uvflg.timeran = [None, 0, 23, 5, 0, 0, 23, 14, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad ampspikes
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 10]
    uvflg.timeran = [None, 0, 20, 30, 0, 0, 22, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 11]
    uvflg.timeran = [None, 0, 22, 30, 0, 0, 22, 44, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 17]
    uvflg.timeran = [None, 1, 1, 59, 10, 1, 2, 2, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.timeran = [None, 0, 23, 0, 0, 0, 23, 16, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 17]
    uvflg.timeran = [None, 1, 1, 19, 0, 1, 1, 20, 10]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 17]
    uvflg.timeran = [None, 1, 2, 55, 0, 1, 4, 0, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 17]
    uvflg.timeran = [None, 1, 2, 12, 0, 1, 2, 15, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 17]
    uvflg.timeran = [None, 1, 2, 20, 0, 1, 2, 25, 0]
    uvflg.opcode = 'FLAG'
    uvflg.go()
    # Quack AR
    quack = task('quack')
    quack.default()
    quack.indata = data
    quack.antenna = [None, 17]
    quack.opcode = 'BEG'
    quack.aparm[2] = 10.0/60
    quack.go()
    quack = task('quack')
    quack.default()
    quack.indata = data
    quack.antenna = [None, 17]
    quack.opcode = 'ENDB'
    quack.aparm[2] = 10.0/60
    quack.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 17]
    uvflg.timeran = [None, 1, 2, 27, 0, 1, 2, 31, 30]
    #uvflg.bif = 2
    #uvflg.eif = 3
    uvflg.opcode = 'FLAG'
    uvflg.go()
   #Flag bad scan
    data = UV(NAME, sorted_class, DISK, 1)
    uvflg = task('uvflg')
    uvflg.default()
    uvflg.indata = data
    uvflg.outfgver = outfgver
    uvflg.antenna = [None, 2]
    uvflg.timeran = [None, 1, 2, 20, 0, 2, 2, 40, 0]
    uvflg.bif = 4
    uvflg.eif = 4
    uvflg.opcode = 'FLAG'
    uvflg.go()
    # Quack Frcal
    quack = task('quack')
    quack.default()
    quack.indata = data
    quack.opcode = 'BEG'
    quack.aparm[2] = 40.0/60
    quack.sour = [None, frcal]
    quack.go()
    quack = task('quack')
    quack.default()
    quack.indata = data
    quack.sour = [None, frcal]
    quack.opcode = 'ENDB'
    quack.aparm[2] = 10.0/60
    quack.go()

########## Use a priori Amp Cal an Parallactic angle correction from Jive ##########
# => CL2
if whattodo['copy_JIVE_CL']:
    indata = UV(TABNAME, TABCLASS, DISK, 1)
    outdata = UV(NAME, sorted_class, DISK, 1)
    cloutver = 2
    # Remove all CL tables higher than version cloutver-1.
    for i in range(outdata.table_highver('CL'), cloutver-1, -1):
        outdata.zap_table('CL', i)
    tacop = task('tacop')
    tacop.default()
    tacop.indata = indata
    tacop.outdata = outdata
    tacop.inext = 'CL'
    tacop.inver = 2
    tacop.ncount = 1
    tacop.outver = cloutver
    tacop.go()
    # Fix gainjump in CL-table for antenna 1.
    data = UV(NAME, sorted_class, DISK, 1)
    clcor = task('clcor')
    clcor.default()
    clcor.clcorprm = [None, 0.5,0] # Reduce amps by factor of 2
    clcor.antenna = [None, 1, 0]
    clcor.gainver = cloutver
    clcor.gainuse = cloutver
    clcor.indata = data
    clcor.opcode = 'GAIN'
    clcor.timeran = [None, 0, 0, 0, 0, 0, 19, 25, 0]
    clcor.go()


#   FRING on AMPCAL
if whattodo['fring_ampcal']:
    clinver = 2
    cloutver = 3
    snoutver = 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)
    data = UV(NAME, sorted_class, DISK, 1)
    fring=task('fring')
    fring.default()
    fring.indata = data
    fring.docalib = 1
    fring.gainuse = clinver
    fring.calsour = [None, ampcal]
    fring.refant = refant
    fring.solint = 5 # Longer than scan
    fring.snver = snoutver
    fring.dparm[2] = 200 # ns
    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, ampcal]
    clcal.sour = [None, ''] # All sources
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.go()

if whattodo['bpass_ampcal']:
    clinver = 3
    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,ampcal]
    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_ampcal_1']:
    clinver = 3
    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.1e-3, 0.1e-3]
    imagr.imsize = [None, 512,512]
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.outname = imagename
    imagr.outdisk = imagedisk
    imagr.outseq = imageseq
    imagr.niter = 500
    imagr.doband = 1
    imagr.bpver = 1
    imagr.antenna = vlba_antennas
    imagr.baselin = imagr.antenna
    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_ampcal']:
    clinver = 3
    cloutver = 4
    snoutver = 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)
    # FIT ANTENNA 3, with proper timeran not to flag things
    data = UV(NAME, sorted_class, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.in2data = IM(AMPCALIM + '1', 'ICL001', 1, 1)
    calib.calsour = [None, ampcal]
    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[6] = 1 # Print level
    calib.weightit = 1
    calib.soltype = 'L1R'
    calib.doband = 1
    calib.bpver = 1
    calib.aparm[1] = 4 # Min no antennas
    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, ''] # Apply to all sources
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.go()

if whattodo['image_ampcal_2']:
    clinver = 4
    imagename = AMPCALIM+'2'
    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.1e-3, 0.1e-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.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()

#   FRING on PHASECAL
if whattodo['fring_phasecal']:
    clinver = 4 # With ampcal corrections
    cloutver = 5
    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, phasecal]
    fring.refant = refant
    fring.solint = 3 # Longer than scan
    fring.dparm[2] = 50#ns, delay win, already fitted bulk on ampcal
    fring.dparm[3] = 15#mHz, rate win
    #fring.aparm[3] = 1 # AVG RR,LL
    #fring.aparm[4] = 1 # AVG freqs in IFs
    #fring.aparm[5] = 1 # AVG IFs
    fring.snver = snoutver
    fring.doband = 1
    fring.bpver = 1
    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):
        print "WARNING: Deleting CL" + str(i)
        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, phasecal]
    clcal.sour = [None, phasecal, target]
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.go()

if whattodo['clip_phasecal']:
    outfgver = 2
    data = UV(NAME, sorted_class, DISK, 1)
    clip = task('clip')
    clip.default()
    clip.sour = [None, phasecal, target]
    clip.aparm[1] = 2.0 # Max Jy
    #clip.antenna = [None, 2]
    #clip.baselin = [None, 5]
    clip.docal = 1
    clip.flagver = outfgver
    clip.doband = 1
    clip.bpver = 1
    clip.indata = data
    clip.outfgver = outfgver
    clip.go()
    data = UV(NAME, sorted_class, DISK, 1)
    clip = task('clip')
    clip.default()
    clip.sour = [None, phasecal]
    clip.aparm[3] = 0.2 # Min Jy
    clip.antenna = [None, 1]
    clip.docal = 1
    clip.flagver = outfgver
    clip.doband = 1
    clip.bpver = 1
    clip.indata = data
    clip.outfgver = outfgver
    clip.go()

if whattodo['image_phasecal_1']:
    clinver = 5
    imagename = PCALIM + '1'
    imagedisk = 1
    imageseq = 1
    data = UV(NAME, sorted_class, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, phasecal]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.stokes = 'I'
    imagr.cellsize = [None, 0.1e-3, 0.1e-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.uvrang = uvrange
    imagr.antenna = [None, -1, -17]
    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_phasecal']:
    clinver = 5
    cloutver = 6
    snoutver = 4 # and 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):
        print "WARNING: Deleting SN" + str(i)
        data.zap_table('SN', i)
    data = UV(NAME, sorted_class, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.in2data = IM(PCALIM + '1', 'ICL001', 1, 1)
    calib.calsour = [None, phasecal]
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.flagver = 0
    calib.snver = snoutver
    calib.solmode = 'A&P'
    calib.solint = 3 # Longer than scan
    calib.aparm[1] = 4 # Minant
    calib.aparm[7] = 5 # SNR
    #calib.aparm[3] = 1 # AVG RR,LL, 
    calib.aparm[6] = 1 # Print level
    #calib.aparm[5] = 1 # AVG ifs
    calib.weightit = 1
    calib.soltype = 'L1R'
    calib.antenna = [None, -17]
    calib.doband = 1
    calib.bpver = 1
    calib.go()

    # CLIP solutions
    data = UV(NAME, sorted_class, DISK, 1)
    snsmo = task('snsmo')
    snsmo.default()
    snsmo.indata = data
    snsmo.samptype = 'MWF'
    snsmo.cparm[1] = 2 # hours, clipping time ampl
    snsmo.cparm[6] = 0.2 # Max deviation, ampl
    snsmo.inver = snoutver
    snsmo.outver = snoutver + 1
    snsmo.smotype = 'AMPL' # 
    snsmo.refant = refant
    snsmo.doblank = -1
    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):
        print "WARNING: Deleting CL" + str(i)
        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 + 1
    clcal.invers = snoutver + 1
    clcal.calsour = [None, phasecal]
    clcal.sour = [None, phasecal, target] # Apply to all sources
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.go()

if whattodo['image_phasecal_2']:
    clinver = 6
    imagename = PCALIM + '2'
    imagedisk = 1
    imageseq = 1
    data = UV(NAME, sorted_class, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, phasecal]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.stokes = 'I'
    imagr.cellsize = [None, 0.1e-3, 0.1e-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
    imagr.antenna = [None, -17]
    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_phasecal_2']:
    clinver = 6
    cloutver = 7
    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):
        print "WARNING: Deleting SN" + str(i)
        data.zap_table('SN', i)
    data = UV(NAME, sorted_class, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.in2data = IM(PCALIM + '1', 'ICL001', 1, 1)
    calib.calsour = [None, phasecal]
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.flagver = 0
    calib.snver = snoutver
    calib.solmode = 'A&P'
    calib.solint = 3 # Longer than scan
    calib.aparm[1] = 4 # Minant
    calib.aparm[7] = 5 # SNR
    #calib.aparm[3] = 1 # AVG RR,LL, 
    calib.aparm[6] = 1 # Print level
    #calib.aparm[5] = 1 # AVG ifs
    calib.aparm[9] = 1 # Needed here since AR only small timeran
    calib.weightit = 1
    calib.soltype = 'L1R'
    calib.dofit = [None, 17]
    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):
        print "WARNING: Deleting CL" + str(i)
        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 + 1
    clcal.invers = snoutver + 1
    clcal.calsour = [None, phasecal]
    clcal.sour = [None, phasecal, target] # Apply to all sources
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.go()

if whattodo['image_phasecal_3']:
    clinver = 7
    imagename = PCALIM + '3'
    imagedisk = 1
    imageseq = 1
    data = UV(NAME, sorted_class, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, phasecal]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.stokes = 'I'
    imagr.cellsize = [None, 0.1e-3, 0.1e-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.go()

############### IMAGE ARP220 ######################
# Load these outside if to be available also for export later
clinver = 7
arpfilename = TCALIM
arpfiledisk = 1
arpfileseq = 1
arpfileclass = 'ICL001'
arpfileclass2 = 'ICL002'
if whattodo['image_ARP220']:
    # 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(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. 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, 4096,2048]
    imagr.cellsize = [None, 0.2e-3, 0.2e-3]
    imagr.stokes = 'I'
    imagr.nfield = 2
    imagr.overlap = 1
    imagr.do3dimag = 1
    imagr.rashift = [None, 0.6, -0.35]
    imagr.decshift = [None, 0.02, 0.18]
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.niter = 500
    imagr.gain = 0.1
    imagr.uvrange = uvrange # remove large-scale disturbances
    imagr.robust = 0.5
    imagr.antenna = [None, -17]
    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.nchav = 512
    imagr.doband = 1
    imagr.bpver = 1
    imagr.imsize = [None, 4096,2048]
    imagr.cellsize = [None, 0.2e-3, 0.2e-3]
    imagr.stokes = 'I'
    imagr.nfield = 2
    imagr.overlap = 1
    imagr.do3dimag = 1
    imagr.rashift = [None, 0.6, -0.35]
    imagr.decshift = [None, 0.02, 0.18]
    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.antenna = [None, -17]
    imagr.go()

if whattodo['selfcal_arp220']:
    clinver = 7
    cloutver = 8
    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):
        print "WARNING: Deleting SN" + str(i)
        data.zap_table('SN', i)
    data = UV(NAME, sorted_class, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    # Use blanked image
    calib.in2data = IM(TCALIM, 'ICL001', 1, 1)
    calib.calsour = [None, target]
    calib.nmaps = 2
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.flagver = 0
    calib.snver = snoutver
    calib.solmode = 'P'
    calib.solint = 10 # Longer than scan
    calib.aparm[1] = 3 # min No. of antennas to include first 45 min.
    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.antenna = [None, -17] # Ignore AR for now
    calib.cmethod = 'DFT'
    calib.weightit = 1
    calib.soltype = 'L1R'
    calib.doband = 1
    calib.bpver = 1
    calib.uvrange = uvrange
    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):
        print "WARNING: Deleting CL" + str(i)
        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] # 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
clinver = 8
arpfilename = TCALIM2
arpfiledisk = 1
arpfileseq = 1
arpfileclass = 'ICL001'
arpfileclass2 = 'ICL002'
if whattodo['image_ARP220_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()
    # Clean with latest gainuse
    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. 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, 4096,2048]
    imagr.cellsize = [None, 0.2e-3, 0.2e-3]
    imagr.stokes = 'I'
    imagr.nfield = 2
    imagr.overlap = 1
    imagr.do3dimag = 1
    imagr.rashift = [None, 0.6, -0.35]
    imagr.decshift = [None, 0.02, 0.18]
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.niter = 500
    imagr.gain = 0.1
    imagr.uvrange = uvrange # remove large-scale disturbances
    imagr.robust = 0.5
    imagr.antenna = [None, -17]
    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.nchav = 512
    imagr.doband = 1
    imagr.bpver = 1
    imagr.imsize = [None, 4096,2048]
    imagr.cellsize = [None, 0.2e-3, 0.2e-3]
    imagr.stokes = 'I'
    imagr.nfield = 2
    imagr.overlap = 1
    imagr.do3dimag = 1
    imagr.rashift = [None, 0.6, -0.35]
    imagr.decshift = [None, 0.02, 0.18]
    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.antenna = [None, -17]
    imagr.go()

if whattodo['selfcal_arp220_2']:
    clinver = 8
    cloutver = 9
    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):
        print "WARNING: Deleting SN" + str(i)
        data.zap_table('SN', i)
    data = UV(NAME, sorted_class, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    # Use blanked image
    calib.in2data = IM(TCALIM2, 'ICL001', 1, 1)
    calib.calsour = [None, target]
    calib.nmaps = 2
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.flagver = 0
    calib.snver = snoutver
    calib.solmode = 'P'
    calib.solint = 10 # Longer than scan
    calib.aparm[1] = 3 # min No. of antennas to include first 45 min.
    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.aparm[9] = 1 # Need when fitting only AR
    calib.dofit = [None, 17]
    calib.cmethod = 'DFT'
    calib.weightit = 1
    calib.soltype = 'L1R'
    calib.doband = 1
    calib.bpver = 1
    calib.uvrange = uvrange
    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):
        print "WARNING: Deleting CL" + str(i)
        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] # 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 = OUTPREFIX + '_FIN'
arpfiledisk = 1
arpfileseq = 1
arpfileclass = 'ICL001'
arpfileclass2 = 'ICL002'
if whattodo['image_ARP220_final']:
    # 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(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. To clean (for later removal) of the strongest sources
    imagr.gainuse = 0
    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, 0.6, -0.35]
    imagr.decshift = [None, 0.02, 0.18]
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.niter = 500
    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(NAME, sorted_class, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, target]
    imagr.gainuse = 0
    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, 0.6, -0.35]
    imagr.decshift = [None, 0.02, 0.18]
    imagr.docalib = 1
    imagr.dotv = -1
    imagr.outname = arpfilename
    imagr.outdisk = arpfiledisk
    imagr.outseq = arpfileseq
    imagr.outver = 1
    imagr.niter = 3000
    imagr.gain = 0.1
    imagr.bcomp = [None, 100000, 100000]
    imagr.uvrange = uvrange # remove large-scale disturbances
    imagr.robust = 0.5
    imagr.go()

#   FRING on FRCAL
if whattodo['fring_frcal']:
    clinver = 9
    cloutver = 10
    snoutver = 9
    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, frcal]
    fring.refant = refant
    fring.solint = 10 # Longer than scan
    fring.snver = snoutver
    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, frcal]
    clcal.sour = [None, frcal]
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.go()

if whattodo['image_frcal_1']:
    clinver = 10
    imagename = FRCALIM + '1'
    imagedisk = 1
    imageseq = 1
    data = UV(NAME, sorted_class, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, frcal]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.stokes = 'I'
    imagr.cellsize = [None, 0.1e-3, 0.1e-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.uvrange = uvrange
    imagr.robust = 0.5
    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.go()

if whattodo['selfcal_frcal']:
    clinver = 10
    cloutver = 11
    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)
    # FIT ANTENNA 3, with proper timeran not to flag things
    data = UV(NAME, sorted_class, DISK, 1)
    calib = task('calib')
    calib.default()
    calib.indata = data
    calib.in2data = IM(FRCALIM + '1', 'ICL001', 1, 1)
    calib.calsour = [None, frcal]
    calib.refant = refant
    calib.docalib = 1
    calib.gainuse = clinver
    calib.flagver = 0
    calib.snver = snoutver
    calib.solmode = 'A&P'
    calib.solint = 1 # 
    calib.aparm[7] = 5 # SNR
    calib.cmethod = 'DFT'
    calib.aparm[6] = 1 # Print level
    calib.aparm[9] = 1 # Pass on failed sols, for scans without these ants
    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, frcal]
    clcal.sour = [None, frcal]
    clcal.gainver = clinver
    clcal.gainuse = cloutver
    clcal.refant = refant
    clcal.go()

if whattodo['image_frcal_2']:
    clinver = 11
    imagename = FRCALIM+'2'
    imagedisk = 1
    imageseq = 1
    data = UV(NAME, sorted_class, DISK, 1)
    imagr = task('imagr')
    imagr.default()
    imagr.indata = data
    imagr.sources = [None, frcal]
    imagr.gainuse = clinver
    imagr.flagver = 0
    imagr.nchav = 512
    imagr.stokes = 'I'
    imagr.cellsize = [None, 0.1e-3, 0.1e-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.uvrange = uvrange
    imagr.robust = 0.5
    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.go()

############### EXPORT RESULTS ######################
if whattodo['export_results']:
    # Export EAST
    fittp = task('fittp')
    fittp.default()
    #fittp.indata = IM(NAME+'_TC','ICL001', 1, 1)
    fittp.indata = IM(NAME+'_FIN','ICL001', 1, 1)
    fittp.dataout = 'PWD:'+OUTPREFIX+'_EAST_IMAGE.FITS'
    if os.path.exists(fittp.dataout[4:]):
     os.system('rm ' + fittp.dataout[4:])
    fittp.go()
    # Export WEST
    fittp = task('fittp')
    fittp.default()
    #fittp.indata = IM(NAME+'_TC','ICL002', 1, 1)
    fittp.indata = IM(NAME+'_FIN','ICL002', 1, 1)
    fittp.dataout = 'PWD:'+OUTPREFIX+'_WEST_IMAGE.FITS'
    if os.path.exists(fittp.dataout[4:]):
     os.system('rm ' + fittp.dataout[4:])
    fittp.go()
    
    # Export FRCAL
    im = IM(NAME+'_FC2', 'ICL001', 1, 1)
    fittp = task('fittp')
    fittp.default()
    fittp.indata = im
    fittp.dataout = 'PWD:'+NAME+'_J1613+3412_IMAGE.FITS'
    if os.path.exists(fittp.dataout[4:]):
     os.system('rm ' + fittp.dataout[4:])
    fittp.go()
    # Export ACAL
    im = IM(NAME+'AC2', 'ICL001', 1, 1)
    fittp = task('fittp')
    fittp.default()
    fittp.indata = im
    fittp.dataout = 'PWD:'+NAME+'_J1516+1932_IMAGE.FITS'
    if os.path.exists(fittp.dataout[4:]):
     os.system('rm ' + fittp.dataout[4:])
    fittp.go()
    # Export PCAL
    im = IM(NAME+'PC3', 'ICL001', 1, 1)
    fittp = task('fittp')
    fittp.default()
    fittp.indata = im
    fittp.dataout = 'PWD:'+NAME+'_J1532+2344_IMAGE.FITS'
    if os.path.exists(fittp.dataout[4:]):
     os.system('rm ' + fittp.dataout[4:])
    fittp.go()
    
    fittp = task('fittp')
    fittp.default()
    fittp.indata = IM(NAME+'_FIN','IBM001', 1, 1)
    fittp.dataout = 'PWD:'+NAME+'_EAST_BEAM.FITS'
    if os.path.exists(fittp.dataout[4:]):
     os.system('rm ' + fittp.dataout[4:])
    fittp.go()
    fittp = task('fittp')
    fittp.default()
    fittp.indata = IM(NAME+'_FIN','IBM002', 1, 1)
    fittp.dataout = 'PWD:'+NAME+'_WEST_BEAM.FITS'
    if os.path.exists(fittp.dataout[4:]):
     os.system('rm ' + fittp.dataout[4:])
    fittp.go()

if whattodo['save_calsols']:
    snver = 7
    # Remove all PL tables
    data = UV(NAME, sorted_class, DISK, 1)

    data.zap_table('PL', -1)
    snplt = task('snplt')
    snplt.indata = data
    snplt.bif = 1
    snplt.eif = 1
    snplt.stokes = 'RR'
    snplt.optype = 'PHAS'
    snplt.sour = [None, target]
    snplt.inext = 'SN'
    snplt.inver = snver
    snplt.nplots = 6
    #snplt.pixrange = [None, -180,180]
    snplt.dotv = -1
    snplt.go()
    outname = NAME+'_ARP220_SELFCAL_SOLS.EPS'
    if os.path.exists(outname):
        os.system('rm ' + outname)
    lwpla = task('lwpla')
    lwpla.indata = data
    lwpla.plver = 1
    lwpla.inver = 99
    lwpla.outfile = 'PWD:'+outname
    #lwpla.docolor = 1
    lwpla.go()

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

