SUBROUTINE dynetat0(fichnom,vcov,ucov,teta,q,masse,ps,phis,time)

!-------------------------------------------------------------------------------
! Authors: P. Le Van , L.Fairhead
!-------------------------------------------------------------------------------
! Purpose: Initial state reading.
!-------------------------------------------------------------------------------
  USE infotrac,    ONLY: nqtot, tracers, niso, iqIsoPha, iH2O, isoName
  USE strings_mod, ONLY: maxlen, msg, strStack, real2str, int2str
  USE netcdf,      ONLY: nf90_open,  nf90_nowrite, nf90_inq_varid, &
                         nf90_close, nf90_get_var, nf90_noerr
  USE readTracFiles_mod, ONLY: new2oldH2O, newHNO3, oldHNO3, getKey
  USE control_mod, ONLY: planet_type
  USE assert_eq_m, ONLY: assert_eq
  USE comvert_mod, ONLY: pa,preff
  USE comconst_mod, ONLY: cpp, daysec, dtvr, g, im, jm, kappa, lllm, omeg, rad
  USE logic_mod, ONLY: fxyhypb, ysinus
  USE serre_mod, ONLY: clon, clat, grossismx, grossismy
  USE temps_mod, ONLY: annee_ref, day_ini, day_ref, itau_dyn, start_time
  USE ener_mod, ONLY: etot0,ptot0,ztot0,stot0,ang0
  USE lmdz_cppkeys_wrapper, ONLY: CPPKEY_INCA

  IMPLICIT NONE
  include "dimensions.h"
  include "paramet.h"
  include "comgeom2.h"
  include "description.h"
  include "iniprint.h"
!===============================================================================
! Arguments:
  CHARACTER(LEN=*), INTENT(IN) :: fichnom          !--- FILE NAME
  REAL, INTENT(OUT) ::  vcov(iip1,jjm, llm)        !--- V COVARIANT WIND
  REAL, INTENT(OUT) ::  ucov(iip1,jjp1,llm)        !--- U COVARIANT WIND
  REAL, INTENT(OUT) ::  teta(iip1,jjp1,llm)        !--- POTENTIAL TEMP.
  REAL, INTENT(OUT) ::     q(iip1,jjp1,llm,nqtot)  !--- TRACERS
  REAL, INTENT(OUT) :: masse(iip1,jjp1,llm)        !--- MASS PER CELL
  REAL, INTENT(OUT) ::    ps(iip1,jjp1)            !--- GROUND PRESSURE
  REAL, INTENT(OUT) ::  phis(iip1,jjp1)            !--- GEOPOTENTIAL
!===============================================================================
! Local variables:
  CHARACTER(LEN=maxlen) :: mesg, var, modname, oldVar
  INTEGER, PARAMETER :: length=100
  INTEGER :: iq, fID, vID, idecal, iqParent, iName, iZone, iPhase
  REAL    :: time, tnat, alpha_ideal, tab_cntrl(length)    !--- RUN PARAMS TABLE
  LOGICAL :: lSkip, ll
  LOGICAL,PARAMETER :: tnat1=.TRUE.
!-------------------------------------------------------------------------------
  modname="dynetat0"

!--- Initial state file opening
  var=fichnom
  CALL err(nf90_open(var,nf90_nowrite,fID),"open",var)
  CALL get_var1("controle",tab_cntrl)

!!! AS: idecal is a hack to be able to read planeto starts...
!!!     .... while keeping everything OK for LMDZ EARTH
  IF(planet_type=="generic") THEN
    CALL msg('NOTE NOTE NOTE : Planeto-like start files', modname)
    idecal = 4
    annee_ref  = 2000
  ELSE
    CALL msg('NOTE NOTE NOTE : Earth-like start files', modname)
    idecal = 5
    annee_ref  = tab_cntrl(5)
  END IF
  im         = tab_cntrl(1)
  jm         = tab_cntrl(2)
  lllm       = tab_cntrl(3)
  day_ref    = tab_cntrl(4)
  rad        = tab_cntrl(idecal+1)
  omeg       = tab_cntrl(idecal+2)
  g          = tab_cntrl(idecal+3)
  cpp        = tab_cntrl(idecal+4)
  kappa      = tab_cntrl(idecal+5)
  daysec     = tab_cntrl(idecal+6)
  dtvr       = tab_cntrl(idecal+7)
  etot0      = tab_cntrl(idecal+8)
  ptot0      = tab_cntrl(idecal+9)
  ztot0      = tab_cntrl(idecal+10)
  stot0      = tab_cntrl(idecal+11)
  ang0       = tab_cntrl(idecal+12)
  pa         = tab_cntrl(idecal+13)
  preff      = tab_cntrl(idecal+14)

  clon       = tab_cntrl(idecal+15)
  clat       = tab_cntrl(idecal+16)
  grossismx  = tab_cntrl(idecal+17)
  grossismy  = tab_cntrl(idecal+18)

  IF ( tab_cntrl(idecal+19)==1. )  THEN
    fxyhypb  = .TRUE.
!   dzoomx   = tab_cntrl(25)
!   dzoomy   = tab_cntrl(26)
!   taux     = tab_cntrl(28)
!   tauy     = tab_cntrl(29)
  ELSE
    fxyhypb = .FALSE.
    ysinus  = tab_cntrl(idecal+22)==1.
  END IF

  day_ini    = tab_cntrl(30)
  itau_dyn   = tab_cntrl(31)
  start_time = tab_cntrl(32)

!-------------------------------------------------------------------------------
  CALL msg('rad, omeg, g, cpp, kappa = '//TRIM(strStack(real2str([rad,omeg,g,cpp,kappa]))), modname)
  CALL check_dim(im,iim,'im','im')
  CALL check_dim(jm,jjm,'jm','jm')
  CALL check_dim(lllm,llm,'lm','lllm')
  CALL get_var1("rlonu",rlonu)
  CALL get_var1("rlatu",rlatu)
  CALL get_var1("rlonv",rlonv)
  CALL get_var1("rlatv",rlatv)
  CALL get_var2("cu"   ,cu)
  CALL get_var2("cv"   ,cv)
  CALL get_var2("aire" ,aire)
  var="temps"
  IF(nf90_inq_varid(fID,var,vID)/=nf90_noerr) THEN
    CALL msg('missing field <temps> ; trying with <Time>', modname)
    var="Time"
    CALL err(nf90_inq_varid(fID,var,vID),"inq",var)
  END IF
  CALL err(nf90_get_var(fID,vID,time),"get",var)
  CALL get_var2("phisinit",phis)
  CALL get_var3("ucov",ucov)
  CALL get_var3("vcov",vcov)
  CALL get_var3("teta",teta)
  CALL get_var3("masse",masse)
  CALL get_var2("ps",ps)

!--- Tracers
  ll=.FALSE.
#ifdef REPROBUS
  ll = nf90_inq_varid(fID, 'HNO3tot', vID) /= nf90_noerr                                 !--- DETECT OLD REPRO start.nc FILE
#endif
  DO iq=1,nqtot
    var = tracers(iq)%name
    oldVar = new2oldH2O(var)
    lSkip = ll .AND. var == 'HNO3'                                                       !--- FORCE "HNO3_g" READING FOR "HNO3"
#ifdef REPROBUS
    ix = strIdx(newHNO3, var); IF(ix /= 0) oldVar = oldHNO3(ix)                          !--- REPROBUS HNO3 exceptions
#endif
    IF (CPPKEY_INCA) THEN
      IF(var == 'O3') oldVar = 'OX'                                                        !--- DEAL WITH INCA OZONE EXCEPTION
    END IF
    !--------------------------------------------------------------------------------------------------------------------------
    IF(nf90_inq_varid(fID, var, vID) == nf90_noerr .AND. .NOT.lSkip) THEN                !=== REGULAR CASE: AVAILABLE VARIABLE
      CALL err(nf90_get_var(fID,vID,q(:,:,:,iq)),"get",var)
    !--------------------------------------------------------------------------------------------------------------------------
    ELSE IF(nf90_inq_varid(fID, oldVar, vID) == nf90_noerr) THEN                         !=== TRY WITH ALTERNATE NAME
      CALL msg('Tracer <'//TRIM(var)//'> is missing => initialized to <'//TRIM(oldVar)//'>', modname)
      CALL err(nf90_get_var(fID,vID,q(:,:,:,iq)),"get",oldVar)
    !--------------------------------------------------------------------------------------------------------------------------
    ELSE IF(tracers(iq)%iso_iGroup == iH2O .AND. niso > 0) THEN                          !=== WATER ISOTOPES
      iName    = tracers(iq)%iso_iName
      iPhase   = tracers(iq)%iso_iPhase
      iqParent = tracers(iq)%iqParent
      IF(tracers(iq)%iso_iZone == 0) THEN
         if (tnat1) then
                 tnat=1.0
                 alpha_ideal=1.0
                 write(*,*) 'attention dans dynetat0: les alpha_ideal sont a 1'
         else
          IF(getKey('tnat', tnat, isoName(iName)) .OR. getKey('alpha', alpha_ideal, isoName(iName))) &
            CALL abort_gcm(TRIM(modname), 'missing isotopic parameters', 1)
         endif
         CALL msg('Tracer <'//TRIM(var)//'> is missing => initialized with a simplified Rayleigh distillation law.', modname)
         q(:,:,:,iq) = q(:,:,:,iqParent)*tnat*(q(:,:,:,iqParent)/30.e-3)**(alpha_ideal-1.)
      ELSE
         CALL msg('Tracer <'//TRIM(var)//'> is missing => initialized to its parent isotope concentration.', modname)
         ! Camille 9 mars 2023: attention!! seuls les tags qui correspondent à
         ! izone=izone_init (définie dans isotrac_mod) sont initialisés comme
         ! les parents. Sinon, c'est nul.
         ! j'ai fait ça en attendant, mais il faudrait initialiser proprement en
         ! remplacant 1 par izone_init dans la ligne qui suit.
         IF(tracers(iq)%iso_iZone == 1) THEN
           q(:,:,:,iq) = q(:,:,:,iqIsoPha(iName,iPhase))
         ELSE
           q(:,:,:,iq) = 0.
         END IF
      END IF
    !--------------------------------------------------------------------------------------------------------------------------
    ELSE                                                                                 !=== MISSING: SET TO 0
      CALL msg('Tracer <'//TRIM(var)//'> is missing => initialized to zero', modname)
      q(:,:,:,iq)=0.
    !--------------------------------------------------------------------------------------------------------------------------
    END IF
  END DO

  CALL err(nf90_close(fID),"close",fichnom)
  day_ini=day_ini+INT(time)
  time=time-INT(time)


  CONTAINS


SUBROUTINE check_dim(n1,n2,str1,str2)
  INTEGER,          INTENT(IN) :: n1, n2
  CHARACTER(LEN=*), INTENT(IN) :: str1, str2
  CHARACTER(LEN=maxlen) :: s1, s2
  IF(n1/=n2) CALL abort_gcm(TRIM(modname), 'value of "'//TRIM(str1)//'" = '//TRIM(int2str(n1))// &
   ' read in starting file differs from gcm value of "'//TRIM(str2)//'" = '//TRIM(int2str(n2)), 1)
END SUBROUTINE check_dim


SUBROUTINE get_var1(var,v)
  CHARACTER(LEN=*), INTENT(IN)  :: var
  REAL,             INTENT(OUT) :: v(:)
  CALL err(nf90_inq_varid(fID,var,vID),"inq",var)
  CALL err(nf90_get_var(fID,vID,v),"get",var)
END SUBROUTINE get_var1


SUBROUTINE get_var2(var,v)
  CHARACTER(LEN=*), INTENT(IN)  :: var
  REAL,             INTENT(OUT) :: v(:,:)
  CALL err(nf90_inq_varid(fID,var,vID),"inq",var)
  CALL err(nf90_get_var(fID,vID,v),"get",var)
END SUBROUTINE get_var2


SUBROUTINE get_var3(var,v)
  CHARACTER(LEN=*), INTENT(IN)  :: var
  REAL,             INTENT(OUT) :: v(:,:,:)
  CALL err(nf90_inq_varid(fID,var,vID),"inq",var)
  CALL err(nf90_get_var(fID,vID,v),"get",var)
END SUBROUTINE get_var3


SUBROUTINE err(ierr,typ,nam)
  INTEGER,          INTENT(IN) :: ierr   !--- NetCDF ERROR CODE
  CHARACTER(LEN=*), INTENT(IN) :: typ    !--- TYPE OF OPERATION
  CHARACTER(LEN=*), INTENT(IN) :: nam    !--- FIELD/FILE NAME
  IF(ierr==nf90_noerr) RETURN
  SELECT CASE(typ)
    CASE('inq');   mesg="Field <"//TRIM(nam)//"> is missing"
    CASE('get');   mesg="Reading failed for <"//TRIM(nam)//">"
    CASE('open');  mesg="File opening failed for <"//TRIM(nam)//">"
    CASE('close'); mesg="File closing failed for <"//TRIM(nam)//">"
  END SELECT
  CALL ABORT_gcm(TRIM(modname),TRIM(mesg),ierr)
END SUBROUTINE err

END SUBROUTINE dynetat0
