import os
from ..time_format import forday, dayfor

def bool_str(value):
    if value:
        vstr = 'T'
    else:
        vstr = 'F'
    return vstr

def namelist(m, time, forecast_period, run_dir='.'):
    """
    Generate namelists for TP4 runs,
    Inputs:
    - m: Model object with configs
    - time: datetime obj for the starting time of the run
    - forecast_period: forecast period in hours for the run
    - run_dir: path to the run directory
    """
    nmlstr =  f"ECWMF forcing; flx-s14w; LWcorr; precip+2mm; SSSrlx; FCT2 tsadvc.; 0-tracer.\n"
    nmlstr += f"Sigma0; GDEM3 init; KPP mixed layer; SeaWiFS mon KPAR; nested in ATLd0.08 2.6;\n"
    nmlstr += f"S-Z(15-11): dp00/f/x/i=3m/1.125/12m/1m; ds=1m/1.125/4m; src_2.2.12;\n"
    nmlstr += f"12345678901234567890123456789012345678901234567890123456789012345678901234567890\n"
    nmlstr += f"{m.iversn:4d}      'iversn' = hycom version number x10\n"
    nmlstr += f" {m.iexpt:03d}      'iexpt ' = experiment number x10\n"
    nmlstr += f"{m.idm:4d}      'idm   ' = longitudinal array size\n"
    nmlstr += f"{m.jdm:4d}      'jdm   ' = latitudinal  array size\n"
    nmlstr += f"{m.itest:4d}      'itest ' = grid point where detailed diagnostics are desired\n"
    nmlstr += f"{m.jtest:4d}      'jtest ' = grid point where detailed diagnostics are desired\n"
    nmlstr += f"{m.kdm:4d}      'kdm   ' = number of layers\n"
    nmlstr += f"{m.nhybrd:4d}      'nhybrd' = number of hybrid levels (0=all isopycnal)\n"
    nmlstr += f"{m.nsigma:4d}      'nsigma' = number of sigma  levels (nhybrd-nsigma z-levels)\n"
    nmlstr += f"{str(m.dp00):^8s}  'dp00  ' = deep    z-level spacing minimum thickness (m)\n"
    nmlstr += f"{str(m.dp00x):^8s}  'dp00x ' = deep    z-level spacing maximum thickness (m)\n"
    nmlstr += f"{str(m.dp00f):^8s}  'dp00f ' = deep    z-level spacing stretching factor (1.0=const.space)\n"
    nmlstr += f"{str(m.ds00):^8s}  'ds00  ' = shallow z-level spacing minimum thickness (m)\n"
    nmlstr += f"{str(m.ds00x):^8s}  'ds00x ' = shallow z-level spacing maximum thickness (m)\n"
    nmlstr += f"{str(m.ds00f):^8s}  'ds00f ' = shallow z-level spacing stretching factor (1.0=const.space)\n"
    nmlstr += f"{str(m.dp00i):^8s}  'dp00i ' = deep iso-pycnal spacing minimum thickness (m)\n"
    nmlstr += f"{str(m.isotop):^8s}  'isotop' = shallowest depth for isopycnal layers     (m, <0 from file)\n"
    nmlstr += f"{str(m.saln0):^8s}  'saln0 ' = initial salinity value (psu), only used for iniflg<2\n"
    nmlstr += f"{str(m.locsig):^8s}  'locsig' = locally-referenced pot. density for stability (0=F,1=T)\n"
    nmlstr += f"{str(m.kapref):^8s}  'kapref' = thermobaric ref. state (-1=input,0=none,1,2,3=constant)\n"
    nmlstr += f"{str(m.thflag):^8s}  'thflag' = reference pressure flag (0=Sigma-0, 2=Sigma-2)\n"
    nmlstr += f"{str(m.thbase):^8s}  'thbase' = reference density (sigma units)\n"
    nmlstr += f"{str(m.vsigma):^8s}  'vsigma' = spacially varying isopycnal target densities (0=F,1=T)\n"
    for k in range(m.kdm):
        nmlstr += f"{str(m.sigma[k]):^8s}  'sigma ' = layer  {k+1}  density (sigma units)\n"
    nmlstr += f"{str(m.iniflg):^8s}  'iniflg' = initial state flag (0=levl, 1=zonl, 2=clim)\n"
    nmlstr += f"{str(m.jerlv0):^8s}  'jerlv0' = initial jerlov water type (1 to 5; 0 to use KPAR)\n"
    nmlstr += f"{str(m.yrflag):^8s}  'yrflag' = days in year flag   (0=360,  1=366,  2=366J1, 3=actual)\n"
    nmlstr += f"{str(m.sshflg):^8s}  'sshflg' = diagnostic SSH flag (0=SSH,1=SSH&stericSSH)\n"
    nmlstr += f"{str(m.dsurfq):^8s}  'dsurfq' = number of days between model diagnostics at the surface\n"
    nmlstr += f"{str(m.diagfq):^8s}  'diagfq' = number of days between model diagnostics\n"
    nmlstr += f"{str(m.proffq):^8s}  'proffq' = number of days between model diagnostics at selected locs\n"
    nmlstr += f"{str(m.tilefq):^8s}  'tilefq' = number of days between model diagnostics on selected tiles\n"
    nmlstr += f"{str(m.meanfq):^8s}  'meanfq' = number of days between model diagnostics (time averaged)\n"
    nmlstr += f"{str(m.rstrfq):^8s}  'rstrfq' = number of days between model restart output\n"
    nmlstr += f"{str(m.bnstfq):^8s}  'bnstfq' = number of days between baro nesting archive input\n"
    nmlstr += f"{str(m.nestfq):^8s}  'nestfq' = number of days between 3-d  nesting archive input\n"
    nmlstr += f"{str(m.cplifq):^8s}  'cplifq' = number of days (or time steps) between sea ice coupling\n"
    nmlstr += f"{str(m.baclin):^8s}  'baclin' = baroclinic time step (seconds), int. divisor of 86400\n"
    nmlstr += f"{str(m.batrop):^8s}  'batrop' = barotropic time step (seconds), int. div. of baclin/2\n"
    nmlstr += f"{str(m.incflg):^8s}  'incflg' = incremental update flag (0=no, 1=yes, 2=full-velocity)\n"
    nmlstr += f"{str(m.incstp):^8s}  'incstp' = no. timesteps for full update (1=direct insertion)\n"
    nmlstr += f"{str(m.incupf):^8s}  'incupf' = number of days of incremental updating input\n"
    nmlstr += f"{str(m.wbaro ):^8s}  'wbaro ' = barotropic time smoothing weight\n"
    nmlstr += f"{str(m.btrlfr):^8s}  'btrlfr' = leapfrog barotropic time step (0=F,1=T)\n"
    nmlstr += f"{str(m.btrmas):^8s}  'btrmas' = barotropic is mass conserving (0=F,1=T)\n"
    nmlstr += f"{str(m.hybrlx):^8s}  'hybrlx' = HYBGEN: inverse relaxation coefficient (time steps)\n"
    nmlstr += f"{str(m.hybiso):^8s}  'hybiso' = HYBGEN: Use PCM if layer is within hybiso of target density\n"
    nmlstr += f"{str(m.hybmap):^8s}  'hybmap' = hybrid   remapper  flag (0=PCM, 1=PLM,  2=PPM)\n"
    nmlstr += f"{str(m.hybflg):^8s}  'hybflg' = hybrid   generator flag (0=T&S, 1=th&S, 2=th&T)\n"
    nmlstr += f"{str(m.advflg):^8s}  'advflg' = thermal  advection flag (0=T&S, 1=th&S, 2=th&T)\n"
    nmlstr += f"{str(m.advtyp):^8s}  'advtyp' = scalar   advection type (0=PCM,1=MPDATA,2=FCT2,4=FCT4)\n"
    nmlstr += f"{str(m.momtyp):^8s}  'momtyp' = momentum advection type (2=2nd order, 4=4th order)\n"
    nmlstr += f"{str(m.slip  ):^8s}  'slip  ' = +1 for free-slip, -1 for non-slip boundary conditions\n"
    nmlstr += f"{str(m.visco2):^8s}  'visco2' = deformation-dependent Laplacian  viscosity factor\n"
    nmlstr += f"{str(m.visco4):^8s}  'visco4' = deformation-dependent biharmonic viscosity factor\n"
    nmlstr += f"{str(m.facdf4):^8s}  'facdf4' =       speed-dependent biharmonic viscosity factor\n"
    nmlstr += f"{str(m.veldf2):^8s}  'veldf2' = diffusion velocity (m/s) for Laplacian  momentum dissip.\n"
    nmlstr += f"{str(m.veldf4):^8s}  'veldf4' = diffusion velocity (m/s) for biharmonic momentum dissip.\n"
    nmlstr += f"{str(m.thkdf2):^8s}  'thkdf2' = diffusion velocity (m/s) for Laplacian  thickness diffus.\n"
    nmlstr += f"{str(m.thkdf4):^8s}  'thkdf4' = diffusion velocity (m/s) for biharmonic thickness diffus.\n"
    nmlstr += f"{str(m.temdf2):^8s}  'temdf2' = diffusion velocity (m/s) for Laplacian  temp/saln diffus.\n"
    nmlstr += f"{str(m.temdfc):^8s}  'temdfc' = temp diffusion conservation (0.0,1.0 all dens,temp resp.)\n"
    nmlstr += f"{str(m.vertmx):^8s}  'vertmx' = diffusion velocity (m/s) for momentum at MICOM M.L.base\n"
    nmlstr += f"{str(m.cbar  ):^8s}  'cbar  ' = rms flow speed     (m/s) for linear bottom friction\n"
    nmlstr += f"{str(m.cb    ):^8s}  'cb    ' = coefficient of quadratic bottom friction\n"
    nmlstr += f"{str(m.drglim):^8s}  'drglim' = limiter for explicit friction (1.0 none, 0.0 implicit)\n"
    nmlstr += f"{str(m.drgscl):^8s}  'drgscl' = scale factor for tidal drag   (0.0 for no tidal drag)\n"
    nmlstr += f"{str(m.thkdrg):^8s}  'thkdrg' = thickness of bottom boundary layer for tidal drag (m)\n"
    nmlstr += f"{str(m.thkbot):^8s}  'thkbot' = thickness of bottom boundary layer (m)\n"
    nmlstr += f"{str(m.sigjmp):^8s}  'sigjmp' = minimum density jump across interfaces  (kg/m**3)\n"
    nmlstr += f"{str(m.tmljmp):^8s}  'tmljmp' = equivalent temperature jump across mixed-layer (degC)\n"
    nmlstr += f"{str(m.thkmls):^8s}  'thkmls' = reference mixed-layer thickness for SSS relaxation (m)\n"
    nmlstr += f"{str(m.thkmlt):^8s}  'thkmlt' = reference mixed-layer thickness for SST relaxation (m)\n"
    nmlstr += f"{str(m.thkriv):^8s}  'thkriv' = nominal thickness of river inflow (m)\n"
    nmlstr += f"{str(m.thkfrz):^8s}  'thkfrz' = maximum thickness of near-surface freezing zone (m)\n"
    nmlstr += f"{str(m.iceflg):^8s}  'iceflg' = sea ice model flag (0=none,1=energy loan,2=coupled/esmf)\n"
    nmlstr += f"{str(m.tfrz_0):^8s}  'tfrz_0' = ENLN: ice melting point (degC) at S=0psu\n"
    nmlstr += f"{str(m.tfrz_s):^8s}  'tfrz_s' = ENLN: gradient of ice melting point (degC/psu)\n"
    nmlstr += f"{str(m.ticegr):^8s}  'ticegr' = ENLN: temp. grad. inside ice (deg/m); =0 use surtmp\n"
    nmlstr += f"{str(m.hicemn):^8s}  'hicemn' = ENLN: minimum ice thickness (m)\n"
    nmlstr += f"{str(m.hicemx):^8s}  'hicemx' = ENLN: maximum ice thickness (m)\n"
    nmlstr += f"{str(m.ntracr):^8s}  'ntracr' = number of tracers (0=none,negative to initialize)\n"
    nmlstr += f"{str(m.trcflg):^8s}  'trcflg' = tracer flags      (one digit per tr, most sig. replicated)\n"
    nmlstr += f"{str(m.tsofrq):^8s}  'tsofrq' = number of time steps between anti-drift offset calcs\n"
    nmlstr += f"{str(m.tofset):^8s}  'tofset' = temperature anti-drift offset (degC/century)\n"
    nmlstr += f"{str(m.sofset):^8s}  'sofset' = salnity     anti-drift offset  (psu/century)\n"
    nmlstr += f"{str(m.mlflag):^8s}  'mlflag' = mixed layer flag  (0=none,1=KPP,2-3=KT,4=PWP,5=MY,6=GISS)\n"
    nmlstr += f"{str(m.pensol):^8s}  'pensol' = KT:      activate penetrating solar rad.   (0=F,1=T)\n"
    nmlstr += f"{str(m.dtrate):^8s}  'dtrate' = KT:      maximum permitted m.l. detrainment rate  (m/day)\n"
    nmlstr += f"{str(m.thkmin):^8s}  'thkmin' = KT/PWP:  minimum mixed-layer thickness (m)\n"
    nmlstr += f"{str(m.dypflg):^8s}  'dypflg' = KT/PWP:  diapycnal mixing flag (0=none, 1=KPP, 2=explicit)\n"
    nmlstr += f"{str(m.mixfrq):^8s}  'mixfrq' = KT/PWP:  number of time steps between diapycnal mix calcs\n"
    nmlstr += f"{str(m.diapyc):^8s}  'diapyc' = KT/PWP:  diapycnal diffusivity x buoyancy freq. (m**2/s**2)\n"
    nmlstr += f"{str(m.rigr  ):^8s}  'rigr  ' = PWP:     critical gradient richardson number\n"
    nmlstr += f"{str(m.ribc  ):^8s}  'ribc  ' = PWP:     critical bulk     richardson number\n"
    nmlstr += f"{str(m.rinfty):^8s}  'rinfty' = KPP:     maximum  gradient richardson number (shear inst.)\n"
    nmlstr += f"{str(m.ricr  ):^8s}  'ricr  ' = KPP:     critical bulk     richardson number\n"
    nmlstr += f"{str(m.bldmin):^8s}  'bldmin' = KPP:     minimum surface boundary layer thickness (m)\n"
    nmlstr += f"{str(m.bldmax):^8s}  'bldmax' = K-PROF:  maximum surface boundary layer thickness (m)\n"
    nmlstr += f"{str(m.cekman):^8s}  'cekman' = KPP/KT:  scale factor for Ekman depth\n"
    nmlstr += f"{str(m.cmonob):^8s}  'cmonob' = KPP:     scale factor for Monin-Obukov depth\n"
    nmlstr += f"{str(m.bblkpp):^8s}  'bblkpp' = KPP:     activate bottom boundary layer    (0=F,1=T)\n"
    nmlstr += f"{str(m.shinst):^8s}  'shinst' = KPP:     activate shear instability mixing (0=F,1=T)\n"
    nmlstr += f"{str(m.dbdiff):^8s}  'dbdiff' = KPP:     activate double diffusion  mixing (0=F,1=T)\n"
    nmlstr += f"{str(m.nonloc):^8s}  'nonloc' = KPP:     activate nonlocal b. layer mixing (0=F,1=T)\n"
    nmlstr += f"{str(m.botdiw):^8s}  'botdiw' = GISS:    activate bot.enhan.int.wav mixing (0=F,1=T)\n"
    nmlstr += f"{str(m.difout):^8s}  'difout' = K-PROF:  output visc/diff coffs in archive (0=F,1=T)\n"
    nmlstr += f"{str(m.difsmo):^8s}  'difsmo' = K-PROF:  activate horiz smooth diff coeffs (0=F,1=T)\n"
    nmlstr += f"{str(m.difm0):^8s}  'difm0 ' = KPP:     max viscosity   due to shear instability (m**2/s)\n"
    nmlstr += f"{str(m.difs0):^8s}  'difs0 ' = KPP:     max diffusivity due to shear instability (m**2/s)\n"
    nmlstr += f"{str(m.difmiw):^8s}  'difmiw' = KPP:     background/internal wave viscosity       (m**2/s)\n"
    nmlstr += f"{str(m.difsiw):^8s}  'difsiw' = KPP:     background/internal wave diffusivity     (m**2/s)\n"
    nmlstr += f"{str(m.dsfmax):^8s}  'dsfmax' = KPP:     salt fingering diffusivity factor        (m**2/s)\n"
    nmlstr += f"{str(m.rrho0):^8s}  'rrho0 ' = KPP:     salt fingering rp=(alpha*delT)/(beta*delS)\n"
    nmlstr += f"{str(m.cs):^8s}  'cs    ' = KPP:     value for nonlocal flux term\n"
    nmlstr += f"{str(m.cstar):^8s}  'cstar ' = KPP:     value for nonlocal flux term\n"
    nmlstr += f"{str(m.cv):^8s}  'cv    ' = KPP:     buoyancy frequency ratio (0.0 to use a fn. of N)\n"
    nmlstr += f"{str(m.c11):^8s}  'c11   ' = KPP:     value for turb velocity scale\n"
    nmlstr += f"{str(m.hblflg):^8s}  'hblflg' = KPP:     b. layer interp. flag (0=const.,1=linear,2=quad.)\n"
    nmlstr += f"{str(m.niter):^8s}  'niter ' = KPP:     iterations for semi-implicit soln. (2 recomended)\n"
    nmlstr += f"{str(m.fltflg):^8s}  'fltflg' = FLOATS: synthetic float flag (0=no; 1=yes)\n"
    nmlstr += f"{str(m.nfladv):^8s}  'nfladv' = FLOATS: advect every nfladv bacl. time steps (even, >=4)\n"
    nmlstr += f"{str(m.nflsam):^8s}  'nflsam' = FLOATS: output (0=every nfladv steps; >0=no. of days)\n"
    nmlstr += f"{str(m.intpfl):^8s}  'intpfl' = FLOATS: horiz. interp. (0=2nd order+n.n.; 1=n.n. only)\n"
    nmlstr += f"{str(m.iturbv):^8s}  'iturbv' = FLOATS: add horiz. turb. advection velocity (0=no; 1=yes)\n"
    nmlstr += f"{str(m.ismpfl):^8s}  'ismpfl' = FLOATS: sample water properties at float (0=no; 1=yes)\n"
    nmlstr += f"{str(m.tbvar):^8s}  'tbvar ' = FLOATS: horizontal turb. vel. variance scale (m**2/s**2)\n"
    nmlstr += f"{str(m.tdecri):^8s}  'tdecri' = FLOATS: inverse decorrelation time scale (1/day)\n"
    nmlstr += f"{str(m.lbflag):^8s}  'lbflag' = lateral barotropic bndy flag (0=none, 1=port, 2=input)\n"
    nmlstr += f"{str(m.tidflg):^8s}  'tidflg' = TIDES: tidal forcing flag    (0=none,1=open-bdy,2=bdy&body)\n"
    nmlstr += f"{str(m.tidcon):^8s}  'tidcon' = TIDES: 1 digit per (Q1K2P1N2O1K1S2M2), 0=off,1=on\n"
    nmlstr += f"{str(m.tidsal):^8s}  'tidsal' = TIDES: scalar self attraction and loading factor (<0: file)\n"
    nmlstr += f"{str(m.tidgen):^8s}  'tidgen' = TIDES: generic time (0=F,1=T)\n"
    nmlstr += f"{str(m.tidrmp):^8s}  'tidrmp' = TIDES:            ramp time (days)\n"
    nmlstr += f"{str(m.tid_t0):^8s}  'tid_t0' = TIDES: origin for ramp time (model day)\n"
    nmlstr += f"{str(m.clmflg):^8s}  'clmflg' = climatology frequency flag   (6=bimonthly, 12=monthly)\n"
    nmlstr += f"{str(m.wndflg):^8s}  'wndflg' = wind stress input flag (0=none,1=u/v-grid,2,3=p-grid)\n"
    nmlstr += f"{str(m.ustflg):^8s}  'ustflg' = ustar forcing     flag        (3=input,1,2=wndspd,4=stress)\n"
    nmlstr += f"{str(m.flxflg):^8s}  'flxflg' = thermal forcing   flag (0=none,3=net-flux,1,2,4=sst-based,99=thermf_nersc)\n"
    nmlstr += f"{str(m.empflg):^8s}  'empflg' = E-P     forcing   flag (0=none,3=net_E-P, 1,2,4=sst-bas_E)\n"
    nmlstr += f"{str(m.dswflg):^8s}  'dswflg' = diurnal shortwave flag (0=none,1=daily to diurnal corr.)\n"
    nmlstr += f"{str(m.sssflg):^8s}  'sssflg' = SSS relaxation flag (0=none,1=clim)\n"
    nmlstr += f"{str(m.lwflag):^8s}  'lwflag' = longwave (SST) flag (0=none,1=clim,2=atmos)\n"
    nmlstr += f"{str(m.sstflg):^8s}  'sstflg' = SST relaxation flag (0=none,1=clim,2=atmos,3=observed)\n"
    nmlstr += f"{str(m.icmflg):^8s}  'icmflg' = ice mask       flag (0=none,1=clim,2=atmos,3=obs/coupled)\n"
    nmlstr += f"{str(m.flxoff):^8s}  'flxoff' = net flux offset flag                 (0=F,1=T)\n"
    nmlstr += f"{str(m.flxsmo):^8s}  'flxsmo' = smooth surface fluxes                (0=F,1=T)\n"
    nmlstr += f"{str(m.relax):^8s}  'relax ' = activate lateral boundary nudging    (0=F,1=T)\n"
    nmlstr += f"{str(m.trcrlx):^8s}  'trcrlx' = activate lat. bound. tracer nudging  (0=F,1=T)\n"
    nmlstr += f"{str(m.priver):^8s}  'priver' = rivers as a precipitation bogas      (0=F,1=T)\n"
    nmlstr += f"{str(m.epmass):^8s}  'epmass' = treat evap-precip as a mass exchange (0=F,1=T)\n"
    with open(os.path.join(run_dir, 'blkdat.input'), 'wt') as f:
        f.write(nmlstr)

    refyear = time.year
    day1 = int(time.strftime('%j'))
    hour1 = int(time.strftime('%H'))
    day2 = day1 + int(forecast_period / 24)
    hour2 = (hour1 + forecast_period) % 24

    nmlstr =  f"3.1          # version of inputfile (limits.dat)            DO NOT CHANGE\n"
    nmlstr += f"TP4          # (rungen)   Version number of run\n"
    nmlstr += f"{refyear}         # Reference year for simulation  (365. for spinup)\n"
    nmlstr += f" {day1:03d} {hour1:02d}      # (nday1)    First day of integration NOTE FORMAT F9.2\n"
    nmlstr += f" {day2:03d} {hour2:02d}      # (nday2)    Last day of integration  NOTE FORMAT F9.2\n"
    nmlstr += f"{m.forcing_frc:5s} {m.forcing_clm:5s}  # forcing option, month, ecmwf, ncepr, ecmo, ecnc\n"
    nmlstr += f"{m.temp_relax_tscale:6.1f}       # temperature relaxation time scale (F in blkdat.input)\n"
    nmlstr += f"{m.saln_relax_tscale:6.1f}       # salinity    relaxation time scale\n"
    nmlstr += f"{bool_str(m.accum_avg)}  {m.accum_avg_intv_h}         # laverage n Accumulate monthly averages every n hours\n"
    nmlstr += f"T  T         # Switch on and accumulate (T) or overwrite (F) daily averages \n"
    nmlstr += f"{bool_str(m.nestoflag)}  6         # lnesto, nestdto - saves nesting bnd cond at nestdto intervals\n"
    nmlstr += f"{bool_str(m.nestiflag)}  6         # lnesti, nestdti - read and apply nesting bnd cond at nestdto intervals\n"
    nmlstr += f"{bool_str(m.tideflag)} {m.tidechoice} F F    # Tides (true,  CSR/FES, apply currents)\n"
    nmlstr += f"{bool_str(m.gpflag)}            # lgridp     Activate storage of gridpoint information\n"
    nmlstr += f"# Days     Assi  Diagno.  Restart            (1992 for first synoptic experiment)\n"
    nmlstr += f"{day1:9.2f}  F     T        T\n"
    nmlstr += f"{day2:9.2f}  F     T        T\n"
    with open(os.path.join(run_dir, 'infile.in'), 'wt') as f:
        f.write(nmlstr)

    nmlstr =  f"{str(m.fversn):^8s} 'fversn' = version of inputfile (infile2.in)\n"
    nmlstr += f"{str(m.randf):^8s} 'randf ' = 1=random forcing, 0= no random forcing\n"
    nmlstr += f"{str(m.seed):^8s} 'seed  ' = Random forcing seed\n"
    nmlstr += f"{str(m.vslp):^8s} 'vslp  ' = Variance in slp\n"
    nmlstr += f"{str(m.vtaux):^8s} 'vtaux ' = Variance in tau_x\n"
    nmlstr += f"{str(m.vtauy):^8s} 'vtauy ' = Variance in tau_y\n"
    nmlstr += f"{str(m.vwspd):^8s} 'vwspd ' = Variance in tau_y\n"
    nmlstr += f"{str(m.vcloud):^8s} 'vcloud' = Variance in clouds\n"
    nmlstr += f"{str(m.vtair):^8s} 'vtair ' = Variance in air temperature\n"
    nmlstr += f"{str(m.vprcp):^8s} 'vprcp ' = Variance in precipitation\n"
    nmlstr += f"{str(m.vrlhum):^8s} 'vrlhum' = Variance in relative humidity\n"
    nmlstr += f"{str(m.scorr):^8s} 'scorr ' = Horizontal radius of correlation (meters)\n"
    nmlstr += f"{str(m.tcorr):^8s} 'tcorr ' = Temporal radius of correlation (days)\n"
    nmlstr += f"{str(m.prsflg):^8s} 'prsflg' = 0 uncorr wind/slp, 1= wind from slp, 2=wind from slp limited by wndspd\n"
    with open(os.path.join(run_dir, 'infile2.in'), 'wt') as f:
        f.write(nmlstr)

    fdtime = dayfor(m.yrflag, refyear, day1+1, hour1)
    ldtime = dayfor(m.yrflag, refyear, day2+1, hour2)
    nmlstr = "{:14.5f} {:14.5f}".format(fdtime, ldtime)
    with open(os.path.join(run_dir, 'limits'), 'wt') as f:
        f.write(nmlstr)

    nmlstr =  f"{str(m.nports):^8s} 'nports   ' = number of ports\n"
    nmlstr += f"{str(m.pefold):^8s} 'pefold   ' = port transport e-folding time in days\n"
    for i in range(m.nports):
        nmlstr += f"{str(m.kdport[i]):^8s} 'kdport   ' = port orientation (1=N, 2=S, 3=E, 4=W)\n"
        nmlstr += f"{str(m.ifport[i]):^8s} 'ifport   ' = first i-index\n"
        nmlstr += f"{str(m.ilport[i]):^8s} 'ilport   ' = last  i-index (=ifport for east/west port)\n"
        nmlstr += f"{str(m.jfport[i]):^8s} 'jfport   ' = first j-index\n"
        nmlstr += f"{str(m.jlport[i]):^8s} 'jlport   ' = last  j-index (=jfport for north/south port)\n"
        nmlstr += f"{str(m.svpnow[i]):^8s} 'svpnow   ' = existing port transport in Sv (+ve towards E or S)\n"
        nmlstr += f"{str(m.svport[i]):^8s} 'svport   ' = target   port transport in Sv (+ve towards E or S)\n"
    with open(os.path.join(run_dir, 'ports.input'), 'wt') as f:
        f.write(nmlstr)

    nmlstr =  f"1.1      # File version\n"
    nmlstr += f"{str(m.evp_time_step):^8s} # EVP time step\n"
    nmlstr += f"{str(m.evp_ice_strength):^8s} # EVP ice strength\n"
    nmlstr += f"{str(m.evp_sic_fac):^8s} # EVP ice concentration factor\n"
    nmlstr += f"{str(m.evp_n_subcycles):^8s} # EVP nb of subcycles=elastic_tstep/dyn_tstep\n"
    with open(os.path.join(run_dir, 'infile.evp'), 'wt') as f:
        f.write(nmlstr)

    nmlstr =  f"1.1      # FILE    : Version number of this file\n"
    nmlstr += f"{str(m.albedo_melt_ice):^8s} # ALBEDO  : Albedo value of melting ice []\n"
    nmlstr += f"{str(m.albedo_dry_ice):^8s} # ALBEDO  : Albedo value of dry ice []\n"
    nmlstr += f"{str(m.albedo_snow_min):^8s} # ALBEDO  : Minimum albedo value of snow []\n"
    nmlstr += f"{str(m.albedo_snow_max):^8s} # ALBEDO  : Maximum albedo value of snow []\n"
    nmlstr += f"{str(m.frozen_ice_thick):^8s} # FREEZE  : Initial thickness of frozen ice [m]\n"
    nmlstr += f"{str(m.lead_max_sic):^8s} # LEAD    : Maximum value for ice concentration []\n"
    nmlstr += f"{str(m.snow_limit):^8s} # SNWLIM  : Maximum allowed snow thickness [m]\n"
    nmlstr += f"{str(m.qstore):^8s} # QSTORE  : Max heat store in frac. of ice latent heat []\n"
    nmlstr += f"{str(m.lateral_melt):^8s} # LATERAL MELT: 0=none, 1=standard (Drange94), 2=Hakkinen & Mellor\n"
    with open(os.path.join(run_dir, 'infile.icestate'), 'wt') as f:
        f.write(nmlstr)

