# Copyright 2021 - Barcelona Supercomputing Center
# Author: Rodrigo Martín Posada
# MIT License

# pylint: disable=no-member
import netCDF4
import numpy as np

def read_grid(id_begi, id_begj, id_lon, id_lat, nc, data_filename):
    gf = netCDF4.Dataset(data_filename, 'r')
    # Keep in mind Fortran is column-major while Python is row-major
    # We are switching to column-major
    dda_lon = np.transpose(gf['lon'][id_begj:id_begj+id_lat,id_begi:id_begi+id_lon])
    dda_lat = np.transpose(gf['lat'][id_begj:id_begj+id_lat,id_begi:id_begi+id_lon])
    dda_clo = np.transpose(gf['clo'][:nc,id_begj:id_begj+id_lat,id_begi:id_begi+id_lon])
    dda_cla = np.transpose(gf['cla'][:nc,id_begj:id_begj+id_lat,id_begi:id_begi+id_lon])
    dda_srf = np.transpose(gf['srf'][id_begj:id_begj+id_lat,id_begi:id_begi+id_lon])
    ida_mask = np.transpose(gf['imask'][id_begj:id_begj+id_lat,id_begi:id_begi+id_lon])
    gf.close()

    # OASIS3 mask convention (1=masked, 0=not masked) is opposite to usual one)
    ida_mask ^= 1

    return dda_lon, dda_lat, dda_clo, dda_cla, dda_srf, ida_mask