import numpy as np

def read_res ( resfil ):
  """ Return contents of MORSE .res file

  Version
    06JUL26 AD Read MWCODE as fixed substring within michdr
    10APR26 AD New format file includes original measurements
    28APR25 AD Original

  Parameters
    resfil  str  :  Name of .res file

  Returns
    {hdr}  :  Dictionary of file-level variables
    {pix}  :  Dictionary of lists, each of size hdr['npix']   
  """

# Define structure of hdr dictionary
  hdr = { 'npix':0,   # No. pixels/profile locations in file
          'nset':0,   # No. retrieval sets per pixel (usually 1)
          'nprf':0,   # No. different profiles per pixel
          'nlev':0,   # Max. no. levels in any profile
        'labgrd':'',  # Profile grid type, '*PRE', '*HGT' or '*HGT_NOM'
        'levgrd':[],  # (nlev) List of pressure [hPa] or altitude [km] levels
        'labprf':[],  # (nprf) List of profile species etc
        'nlvprf':{},  # For each labprf, No. profile levels
        'levprf':{},  # For each labprf, a list of nlvprf indices (1=lowest)
          'rfmt':0.0, # .rtv file format identifier
         'igeom':0,   # Viewing geometry, 1=limb emission, 2=limb trans, 3=nadir
    'instrument':'',  # Instrument identification
     'satellite':'',  # Satellite identification
        'ymdsta':0,   # Year, month, day of start of data (yyyymmdd)
        'daysta':0,   # Day# since 1 Jan 2000 (=0) of start of data
        'hmssta':0,   # Hours, minutes, seconds of start of data (hhmmss)
        'orbsta':0,   # Orbit# of start of data
        'ymdend':0,   # Year, month, day of end of data (yyyymmdd)
        'dayend':0,   # Day# since 1 Jan 2000 (=0) of end of data
        'hmsend':0,   # Hours, minutes, seconds of start of data (hhmmss)
        'orbend':0,   # Orbit# of end of data
           'set':'' } # Set header (not filled if hdr_only=True)

# Executable code ------------------------------------------------------------

  first = True

  with open(resfil) as f:
    hdr['hdr1'] = f.readline()
    hdr['hdr2'] = f.readline()
    rec = '!'
    while rec[0] == '!': rec = f.readline()   # Skip further header records

    flds = rec.split()
    npix = int(flds[0])
    nmic = int(flds[1])
    pix = []

    for ipix in range(npix):
      rec = f.readline()
      flds = rec.split()
      idx = int(flds[0])

      rec = f.readline()    # headers
      rec = f.readline()
      flds = rec.split()
      ymd = int(flds[0])
      hms = int(flds[1])
      msc = int(flds[2])
      lat = float(flds[3])
      lon = float(flds[4])
      lst = float(flds[5])
      sza = float(flds[6])
 
      mic = {}
      for imic in range(nmic):
        rec = f.readline() 
        flds = rec.split()
        nswp = int(flds[1])
        npts = int(flds[2])
        use_masks = int(flds[3]) 
        michdr = f.readline()
        mwcode = michdr[4:12]
        flds = michdr.split()  # split header into fields
        wno1 = float(flds[3])
        wno2 = float(flds[4])
        res = np.zeros((nswp,npts))
        spc = np.zeros((nswp,npts))
        if use_masks: msk = np.zeros((nswp,npts))
        for iswp in range(nswp):
          rec = f.readline()    # sweep index
          if use_masks:
            mskswp = np.fromfile ( f, dtype=bool,  count=npts, sep=' ')
            msk[iswp,:] = mskswp
          resswp = np.fromfile ( f, dtype=float, count=npts, sep=' ')
          spcswp = np.fromfile ( f, dtype=float, count=npts, sep=' ')
          res[iswp,:] = resswp
          spc[iswp,:] = spcswp
        micdat = {'hdr':michdr, 'mwcode':mwcode, 'nswp':nswp, 
                  'npts':npts, 'wno1':wno1, 'wno2':wno2 }
        if nswp == 1: 
          micdat['res'] = resswp
          micdat['spc'] = spcswp
          if use_masks: micdat['msk'] = mskswp
        else: 
          micdat['res'] = res
          micdat['spc'] = spc
          if use_masks: micdat['msk'] = msk
        mic[mwcode] = micdat
      pix.append ( {'idx':idx, 'ymd':ymd, 'hms':hms, 'msc':msc, 'lat':lat, 
                    'lon':lon, 'lst':lst, 'sza':sza, 'mic':mic } )

  return { 'hdr':hdr, 'npix':npix, 'nmic':nmic, 'pix':pix }

# --------------
