# Acquire information of the fit to the model of secondary
fit_pack = mu.model_secondary(if1='secondary_uvfmeas_7700_log.txt',
                              if2='secondary_uvfmeas_9500_log.txt')

# Now move things into a directory structure
mu.mv_uv('notsys')

# Reload the data with Tsys and use model as reference flux model
for index, freq in enumerate(FREQS):
    ifsel = index + 1
    primary = f"{mu.primary}.{freq}"
    secondary = f"{mu.secondary}.{freq}"
    mosaic = f"{mu.science}.{freq}"

    # Obtain mflux string from the fitpack information
    mfflux = mu.mfcal_flux(fit_pack, ifcal=ifsel)

    # Load in the data
    atlod = m(f"atlod in=raw/*C3171 options=rfiflag,birdie,xycorr,noauto "\
              f"ifsel={ifsel} out=data{ifsel}.uv").run()
    logger.log(logging.INFO, atlod)

    # Flag the known bad channels out
    if ifsel == 1:
        mu.uvflag(atlod.out, mu.flags_7)
    else:
        mu.uvflag(atlod.out, mu.flags_9)

    # Split the data up
    uvsplit = m(f"uvsplit vis={atlod.out} options=mosaic ").run()
    logger.log(logging.INFO, uvsplit)
print(uvsplit)

# Automated flagging
pgflag = mu.mirstr(f"pgflag vis={secondary} command='<b' stokes=i,q,u,v flagpar=8,5,5,3,6,3 options=nodisp").run()
print(pgflag)

pgflag = mu.mirstr(f"pgflag vis={secondary} command='<b' stokes=i,v,q,u flagpar=8,2,2,3,6,3  options=nodisp").run()
print(pgflag)

pgflag = mu.mirstr(f"pgflag vis={secondary} command='<b' stokes=i,v,u,q flagpar=8,2,2,3,6,3  options=nodisp").run()
print(pgflag)



sec_model = mu.model_secondary()
mfflux = mu.mfcal_flux(sec_model, ifcal=1)

print(mfflux)

# Primary calibration
mfcal = mu.mirstr(f'mfcal vis={secondary} flux={mfflux} interval=0.1').run()
gpcal = mu.mirstr(f"gpcal vis={secondary} interval=0.1 nfbin={NFBIN} flux={mfflux.split(',')[0]} spec={mfflux.split(',')[1]},{mfflux.split(',')[2]} options=xyvary,qusolve").run()

print(mfcal)
print(gpcal)

# Automated flagging
pgflag = mu.mirstr(f"pgflag vis={secondary} command='<b' stokes=i,q,u,v flagpar=8,5,5,3,6,3 options=nodisp").run()
print(pgflag)

pgflag = mu.mirstr(f"pgflag vis={secondary} command='<b' stokes=i,v,q,u flagpar=8,2,2,3,6,3  options=nodisp").run()