import f90nml
import numpy as np

NAMELIST_FILE_NAME = 'namelist.amip'

def read_namelist():
    # Read namelist
    nml = f90nml.read(NAMELIST_FILE_NAME)
    RunLengthSec = nml['NAMAMIP']['RunLengthSec']
    TimeStepSec = nml['NAMAMIP']['TimeStepSec']
    StartYear = nml['NAMAMIP']['StartYear']
    StartMonth = nml['NAMAMIP']['StartMonth']
    StartDay = nml['NAMAMIP']['StartDay']
    FixYear = nml['NAMAMIP']['FixYear']
    LDebug = nml['NAMAMIP']['LDebug']
    
    vars_data = np.transpose(nml['NAMAMIP']['Vars'])
    vars_config = [None] * vars_data.shape[0]
    for i in range(len(vars_config)):
        curr_data = vars_data[i]
        conf = {
            'id': curr_data[0],
            'grid_name': curr_data[1],
            'oasis_name': curr_data[2],
            'file_pattern': curr_data[3],
            'netcdf_variable': curr_data[4],
            'yref_min': curr_data[5],
            'yref_max': curr_data[6],
            'timestep': curr_data[7],
            'interpolate': curr_data[8],
            'scale_factor': curr_data[9],
            'offset': curr_data[10],
            'min': curr_data[11],
            'max': curr_data[12],
        }
        vars_config[i] = conf

    return RunLengthSec, TimeStepSec, StartYear, StartMonth, StartDay, FixYear, LDebug, vars_config
