# Partially autogenerated with SMOP 0.29
import numpy as np


def SwarmL2_MIO_SHA_Read_v2(filename: str) -> dict:
    # s = SwarmL2_MIO_SHA_Read(filename)

    # Purpose:
    # Read Swarm L2 MIO_SHA model from "*.DBL" file.

    # Input:
    #    filename           name of file to read

    # Output: s is a dictionary with the following elements
    #    m_e_d_Re(:,:)    primary Sq model (REAL coefficients)
    #    m_i_d_Re(:,:)    secondary Sq model (REAL coefficients)
    #    nmax, mmax       max degree and order in dipole coord.
    #    p_vec(:)         diurnal wavenumbers
    #    s_vec(:)         seasonal wavenumbers
    #    theta_NGP        co-latitude of North Geomagnetic dipole [deg]
    #    phi_NGP          longitude of North Geomagnetic dipole [deg]
    #    h                altitude of Sq current layer [km]
    #    N                Wold ratio of the F10.7 dependence

    # A. Chulliat, 2016-09-22
    # (from an earlier version dated 2011-03-27, with inputs from N. Olsen)
    # Python version rewritten by A. Woods, 2016-11-29
    s = {}
    # if exist(filename,r"file") == 0:

    try:
        fid = open(filename, 'r')
    except IOError as err:
        print("Coefficient file ", filename, r" does not exist!")
        raise err

    # skip comment lines

    tline = fid.readline()

    while tline[0] == r"#":
        tline = fid.readline()

    # read header part (1 line)
    # "%i %i %i %i %i %i %f %f %f %f"
    f = tline.split()
    s["nmax"] = int(f[0])
    s["mmax"] = int(f[1])

    pmin = int(f[2])
    pmax = int(f[3])
    smin = int(f[4])
    smax = int(f[5])

    s["theta_NGP"] = float(f[6])
    s["phi_NGP"] = float(f[7])
    s["h"] = float(f[8])
    s["N"] = float(f[9])
    s["p_vec"] = range(pmin, pmax + 1)
    s["s_vec"] = range(smin, smax + 1)

    N_nm = s["mmax"] * (s["mmax"] + 2) \
        + (s["nmax"] - s["mmax"]) * (2*s["mmax"] + 1)

    N_sp = len(s["p_vec"]) * len(s["s_vec"])

    # read primary model coefficients
    s["m_e_d_Re"] = np.zeros([N_nm, 2 * N_sp])
    for i in range(0, N_nm):
        tline = fid.readline()
        if tline.split() is None:
            raise ValueError(r"Wrong number of model coefficients!")
        f = [float(j) for j in tline.split()]
        s["m_e_d_Re"][i, :] = f[2:2*N_sp + 2]

    # read secondary model coefficients
    s["m_i_d_Re"] = np.zeros([N_nm, 2 * N_sp])
    for i in range(0, N_nm):
        tline = fid.readline()
        if tline.split() is []:
            raise ValueError(r"Wrong number of model coefficients!")
        f = [float(j) for j in tline.split()]

        s["m_i_d_Re"][i, :] = f[2:2*N_sp + 2]

    fid.close()

    return s
