MODULE cellset_mod
  IMPLICIT NONE
  SAVE
  PRIVATE
  
  TYPE t_cellset
     ! derived type containing arrays for lat,lon of center and bounds of cells of primal or dual mesh
     ! this information is needed to write CF-compliant NetCDF files and by XIOS
     INTEGER :: ncell
     INTEGER, ALLOCATABLE :: ij(:), & ! ij(n) = local index of cell n
          ind_glo(:), &  ! ind_glo(n) = global index of cell n
          sgn(:)         ! sign to apply before writing to disk (velocities)
     REAL, ALLOCATABLE :: lon(:), lat(:), bnds_lon(:,:), bnds_lat(:,:)
  END type t_cellset

  PUBLIC :: t_cellset, create_cellset
  
CONTAINS

  SUBROUTINE create_cellset(set, ind_loc, ind_glo, lon, lat, bnds_lon, bnds_lat)
    USE math_const, ONLY : radian_to_degree
    TYPE(t_cellset), INTENT(OUT) :: set
    INTEGER,         INTENT(IN)  :: ind_loc(:), ind_glo(:)
    REAL,            INTENT(IN)  :: lon(:), lat(:), bnds_lon(:,:), bnds_lat(:,:) ! in radians
    INTEGER :: ij
    set%ncell = SIZE(lon)
    ! F2003 : assignment to whole allocatable array allocates the array to match r.h.s. 
    set%ij       = ind_loc
    set%ind_glo  = ind_glo-1 ! for XIOS indices start at 0
    set%lon      = radian_to_degree*lon
    set%lat      = radian_to_degree*lat
    set%bnds_lon = radian_to_degree*bnds_lon
    set%bnds_lat = radian_to_degree*bnds_lat
  END SUBROUTINE create_cellset

END MODULE cellset_mod
