# ----------------------------------------------------------------------
# Read data and calculate indices

# Precipitation
precip = precipdat.read_cmap(pcpfile, yearmin=min(years), yearmax=max(years))
pcp_box = atm.mean_over_geobox(precip, lat1, lat2, lon1, lon2)
# -- Interpolate to daily resolution
days = np.arange(1, 367)
pcp_i = np.nan * np.ones((len(years), len(days)))
for y, year in enumerate(years):
    pcp_i[y] = np.interp(days, pcp_box['day'], pcp_box[y])
coords = {'day' : days, 'year' : years}
pcp = xray.DataArray(pcp_i, dims=['year', 'day'], coords=coords)

# Monsoon onset, retreat indices
index = utils.get_onset_indices(onset_nm, indfiles, years)
mfc = atm.rolling_mean(index['ts_daily'], nroll, center=True)
onset = index['onset']
ssn_length=index['length'].mean(dim='year')

data = {}
data['MFC'] = utils.daily_rel2onset(mfc, onset, npre, npost)
data[pcp_nm] = utils.daily_rel2onset(pcp, onset, npre, npost)
data['MFC_ACC'] = utils.daily_rel2onset(index['tseries'], onset, npre, npost)

for nm in varnms:
    print('Loading ' + relfiles[nm])
    with xray.open_dataset(relfiles[nm]) as ds:
        if nm == 'PSI':
            data[nm] = atm.streamfunction(ds['V'])
            psimid = atm.subset(data[nm], {'plev' : (pmid, pmid)},
# ----------------------------------------------------------------------
# Read data and calculate indices

# MFC and precip over SASM region
nroll = 7
tseries = utils.get_mfc_box(mfcfiles, precipfiles, None, years, nroll, lat1, lat2,
                            lon1, lon2)

# Monsoon onset day and index timeseries
if onset_nm.startswith('CHP'):
    # Use precip/MFC already loaded
    data = tseries[onset_nm.split('_')[1] + '_ACC']
else:
    data = None
index = utils.get_onset_indices(onset_nm, indfiles[onset_nm], years, data)
onset, retreat, length = index['onset'], index['retreat'], index['length']
tseries[onset_nm] = index['tseries']

# ENSO
enso = utils.get_enso_indices(years)
enso = xray.DataArray(enso[enso_nm]).rename({'Year' : 'year'})

# ----------------------------------------------------------------------
# Climatology

index_clim = index.mean(dim='year')
tseries_clim = tseries.mean(dim='year')
enso_clim = enso.mean(dim='year').values

# Tile the climatology to each year for plot_tseries_together
# Read data

# MFC and precip over SASM region
nroll = 7
tseries = utils.get_mfc_box(datafiles['MFC'], datafiles['PCP'], None, years,
                            nroll, lat1, lat2, lon1, lon2)

# Monsoon onset/retreat indices
if onset_nm.startswith('CHP'):
    # --- Use precip/MFC already loaded
    data = tseries[onset_nm.split('_')[1] + '_ACC']
    files = None
else:
    data = None
    files = datafiles[onset_nm]
index = utils.get_onset_indices(onset_nm, files, years, data)
index = index[['onset', 'retreat']].to_dataframe()
index['length'] = index['retreat'] - index['onset']

# ENSO
enso = utils.get_enso_indices(years, enso_keys)

# Monsoon strength
mfc = tseries['MFC_UNSM']
precip = tseries['PCP_UNSM']
ssn = utils.get_strength_indices(years, tseries['MFC_UNSM'],
                                 tseries['PCP_UNSM'], index['onset'],
                                 index['retreat'])

# ----------------------------------------------------------------------
# Helper functions