MODULE CPLNG_INIT_MOD

    IMPLICIT NONE

    PRIVATE

    PUBLIC CPLNG_INIT

CONTAINS

SUBROUTINE CPLNG_INIT

    USE PARKIND1,   ONLY: JPIM
    USE MPL_MODULE, ONLY: LMPLUSERCOMM, MPLUSERCOMM
    USE MOD_OASIS
    USE CPLNG_DATA_MOD

    CHARACTER(LEN=6),PARAMETER :: CMODEL_NAME = "ATMIFS"

    INTEGER(KIND=JPIM) :: NCOMPID
    INTEGER(KIND=JPIM) :: IERROR
    CHARACTER(LEN=3)   :: CERRSTR

    CHARACTER(LEN=255) :: CPLNG_ENV

    ! -------------------------------------------------------------------------
    ! * (1) Read CPLNG environment variable
    ! -------------------------------------------------------------------------
    CALL GETENV('CPLNG',CPLNG_ENV)

    SELECT CASE (TRIM(CPLNG_ENV))

    CASE ('active','ACTIVE')
        CPLNG_ACTIVE = .TRUE.

    CASE DEFAULT
        CPLNG_ACTIVE = .FALSE.
        RETURN

    END SELECT

    ! -------------------------------------------------------------------------
    ! * (2) Initialise OASIS coupling
    ! -------------------------------------------------------------------------
    CALL OASIS_INIT_COMP(NCOMPID,CMODEL_NAME,IERROR)
    IF (IERROR/=OASIS_OK) THEN
        WRITE (CERRSTR,'(I3)') IERROR
        CALL ABOR1("CPLNG_INIT: Error in OASIS_INIT_COMM: "//CERRSTR)
    ENDIF

    ! Get internal communicator from OASIS
    CALL OASIS_GET_LOCALCOMM(MPLUSERCOMM,IERROR)
    IF (IERROR/=OASIS_OK) THEN
        WRITE (CERRSTR,'(I3)') IERROR
        CALL ABOR1("CPLNG_INIT: Error in OASIS_GET_LOCALCOMM: "//CERRSTR)
    ENDIF

    ! -------------------------------------------------------------------------
    ! * (3) Let IFS know we've set an internal communicator
    ! -------------------------------------------------------------------------
    LMPLUSERCOMM = .TRUE.

END SUBROUTINE CPLNG_INIT

END MODULE CPLNG_INIT_MOD
