!
! $Id: phyredem.f90 5776 2025-07-15 12:13:19Z evignon $
!
SUBROUTINE phyredem (fichnom)
!
!-------------------------------------------------------------------------------
! Author: Z.X. Li (LMD/CNRS), 1993/08/18
!-------------------------------------------------------------------------------
! Purpose: Write restart state for physics.
!-------------------------------------------------------------------------------
  USE compbl_mod_h
  USE conf_phys_m, only: iflag_wake
  USE clesphys_mod_h
  USE dimphy, ONLY: klon, klev
  USE lmdz_gwd_ini, ONLY: ok_gwd_rando, ok_orodr, ok_orolf 
  USE fonte_neige_mod,  ONLY : fonte_neige_final
  USE pbl_surface_mod,  ONLY : pbl_surface_final
  USE phys_state_var_mod, ONLY: radpas, zmasq, pctsrf,                       &
                                ftsol, beta_aridity, delta_tsurf, falb_dir,  &
                                falb_dif, qsol, fevap, radsol, solsw, sollw, &
                                sollwdown, rain_fall, snow_fall, bs_fall, z0m, z0h, &
                                agesno, zmea, zstd, zsig, zgam, zthe, zpic,  &
                                zval, rugoro, t_ancien, q_ancien,            &
                                prw_ancien, prlw_ancien, prsw_ancien, prbsw_ancien,      &
                                ql_ancien, qs_ancien, qbs_ancien, cf_ancien, &
                                rvc_ancien, u_ancien, v_ancien, tke_ancien,  &
                                clwcon, rnebcon, ratqs, pbl_tke,             &
                                wake_delta_pbl_tke, zmax0, f0, sig1, w01,    &
                                wake_deltat, wake_deltaq, wake_s, awake_s,   &
                                wake_dens, awake_dens, cv_gen,               &
                                wake_cstar,                                  &
                                wake_pe, wake_fip, fm_therm, entr_therm,     &
                                detr_therm, ale_bl, ale_bl_trig, alp_bl,     &
                                ale_wake, ale_bl_stat,                       &
                                du_gwd_rando, du_gwd_front, u10m, v10m, &
                                treedrg, solswfdiff, delta_sal, ds_ns, dt_ns, &
!GG                                delta_sst, ratqs_inter_, dter,
                                !dser, dt_ds
                                delta_sst, ratqs_inter_, dter, dser,&
                              & dt_ds, hice, tice, bilg_cumul, &
!GG
                                frac_tersrf, z0m_tersrf,&
                              & ratio_z0m_z0h_tersrf,&
                              & albedo_tersrf, beta_tersrf,&
                              & inertie_tersrf, hcond_tersrf,&
                              & tsurfi_tersrf, tsoili_tersrf,&
                              & tsoil_depth, qsurf_tersrf,&
                              & tsurf_tersrf, tsoil_tersrf,&
                              & tsurf_new_tersrf,&
                              & cdragm_tersrf, cdragh_tersrf,&
                              & swnet_tersrf, lwnet_tersrf,&
                              & fluxsens_tersrf, fluxlat_tersrf

#ifdef ISO
  USE phys_state_var_mod, ONLY: xtsol, fxtevap,xtrain_fall, xtsnow_fall,     &
                                xt_ancien, xtl_ancien, xts_ancien,           &
                                wake_deltaxt                              
#endif
  USE geometry_mod, ONLY : longitude_deg, latitude_deg
  USE iostart, ONLY: open_restartphy, close_restartphy, enddef_restartphy, put_field, put_var
  USE traclmdz_mod, ONLY : traclmdz_to_restart
  USE infotrac_phy, ONLY: type_trac, nqtot, tracers, nbtr, niso
#ifdef ISO
#ifdef ISOVERIF
  USE isotopes_verif_mod
#endif
#endif
  USE carbon_cycle_mod, ONLY : carbon_cycle_cpl, co2_send, carbon_cycle_rad, RCO2_glo
  USE indice_sol_mod, ONLY: nbsrf, is_oce, is_sic, is_ter, is_lic, epsfra
!GG  USE surface_data, ONLY: type_ocean, version_ocean
  USE surface_data, ONLY: type_ocean, version_ocean, iflag_seaice, iflag_seaice_alb, &
                          iflag_leads
!GG
  USE ocean_slab_mod, ONLY : nslay, tslab, seaice, tice_slab, fsic
  USE time_phylmdz_mod, ONLY: annee_ref, day_end, itau_phy, pdtphys
  USE config_ocean_skin_m, ONLY: activate_ocean_skin
  USE dimsoil_mod_h, ONLY: nsoilmx

  IMPLICIT NONE
  !======================================================================
  CHARACTER*(*) fichnom

  ! les variables globales ecrites dans le fichier restart

  REAL tsoil(klon, nsoilmx, nbsrf)
  REAL qsurf(klon, nbsrf)
  REAL snow(klon, nbsrf)
  REAL fder(klon)
  REAL run_off_lic_0(klon)
  REAL trs(klon, nbtr)
#ifdef ISO
  REAL xtsnow(niso,klon, nbsrf)
  REAL xtrun_off_lic_0(niso,klon)
  REAL Rland_ice(niso,klon)
  REAL Rsol(niso,klon)
#endif

  INTEGER nid, nvarid, idim1, idim2, idim3
  INTEGER ierr
  INTEGER length
  PARAMETER (length=100)
  REAL tab_cntrl(length)

  INTEGER isoil, nsrf,isw
  CHARACTER (len=2) :: str2
  CHARACTER (len=256) :: nam, lnam
  INTEGER           :: it, iq, pass

  !======================================================================

  ! Get variables which will be written to restart file from module 
  ! pbl_surface_mod
  IF ( iflag_physiq <= 1 ) THEN
     CALL pbl_surface_final(fder, snow, qsurf,  tsoil &
#ifdef ISO
       ,xtsnow,Rland_ice,Rsol &
#endif       
       )
  ENDIF

  ! Get a variable calculated in module fonte_neige_mod
  CALL fonte_neige_final(run_off_lic_0 &
#ifdef ISO
       ,xtrun_off_lic_0 &
#endif       
       )

  !======================================================================

  CALL open_restartphy(fichnom)

  
  DO ierr = 1, length
     tab_cntrl(ierr) = 0.0
  ENDDO
  tab_cntrl(1) = pdtphys
  tab_cntrl(2) = radpas
  ! co2_ppm : current value of atmospheric CO2
  tab_cntrl(3) = co2_ppm
  tab_cntrl(4) = solaire
  tab_cntrl(5) = iflag_con
  tab_cntrl(6) = nbapp_rad

  IF( iflag_cycle_diurne.GE.1 ) tab_cntrl( 7 ) = iflag_cycle_diurne
  IF(   soil_model ) tab_cntrl( 8 ) = 1.
  IF(     liqice_in_radocond ) tab_cntrl( 9 ) = 1.
  IF(     ok_orodr ) tab_cntrl(10 ) = 1.
  IF(     ok_orolf ) tab_cntrl(11 ) = 1.

  tab_cntrl(13) = day_end
  tab_cntrl(14) = annee_ref
  tab_cntrl(15) = itau_phy

  ! co2_ppm0 : initial value of atmospheric CO2
  ! tab_cntrl(16) = co2_ppm0

  !  PC -- initial value of RCO2 for the radiation scheme
  !  tab_cntrl(17) = co2_ppm * 1.0e-06 * RMCO2 / RMD
  IF (carbon_cycle_rad) tab_cntrl(17) = RCO2_glo
  !PRINT*, "PC : phyredem RCO2_glo =",RCO2_glo
  !GG
  tab_cntrl(18 ) = iflag_seaice
  tab_cntrl(19 ) = iflag_seaice_alb
  tab_cntrl(20 ) = iflag_leads
  !GG

  DO pass=1,2   ! pass=1 netcdf definition ; pass=2 netcdf write
  
    CALL put_var(pass, "controle", "Parametres de controle", tab_cntrl)

    CALL put_field(pass,"longitude", &
         "Longitudes de la grille physique", longitude_deg)

    CALL put_field(pass,"latitude", "Latitudes de la grille physique", latitude_deg)

    ! PB ajout du masque terre/mer

    CALL put_field(pass,"masque", "masque terre mer", zmasq)

    ! BP ajout des fraction de chaque sous-surface

    ! Get last fractions from slab ocean
    IF (type_ocean == 'slab' .AND. version_ocean == "sicINT") THEN
        WHERE (1.-zmasq(:).GT.EPSFRA)
            pctsrf(:,is_oce)=(1.-fsic(:))*(1.-zmasq(:))
            pctsrf(:,is_sic)=fsic(:)*(1.-zmasq(:))
        END WHERE
    END IF

    ! 1. fraction de terre 

    CALL put_field(pass,"FTER", "fraction de continent", pctsrf(:, is_ter))

    ! 2. Fraction de glace de terre

    CALL put_field(pass,"FLIC", "fraction glace de terre", pctsrf(:, is_lic))

    ! 3. fraction ocean

    CALL put_field(pass,"FOCE", "fraction ocean", pctsrf(:, is_oce))

    ! 4. Fraction glace de mer

    CALL put_field(pass,"FSIC", "fraction glace mer", pctsrf(:, is_sic))

    IF(nbsrf>99) THEN
      PRINT*, "Trop de sous-mailles";  CALL abort_physic("phyredem", "", 1)
    END IF
    IF(nsoilmx>99) THEN
      PRINT*, "Trop de sous-surfaces"; CALL abort_physic("phyredem", "", 1)
    END IF
    IF(nsw>99) THEN
      PRINT*, "Trop de bandes"; CALL abort_physic("phyredem", "", 1)
    END IF

!    Surface variables 
    CALL put_field_srf1(pass,"TS","Temperature",ftsol(:,:))

    IF (iflag_pbl>1 .AND. iflag_wake>=1  .AND. iflag_pbl_split >=1) then
       CALL put_field_srf1(pass, "DELTATS", &
            "w-x surface temperature difference", delta_tsurf(:,:))
       CALL put_field_srf1(pass,"BETAS","Aridity factor", beta_aridity(:,:))
    END IF
!    End surface variables

! ================== Albedo =======================================
    PRINT*,'PHYREDEM NOUVEAU'
    CALL put_field_srf2(pass,"A_dir_SW","Albedo direct",falb_dir(:,:,:))
    CALL put_field_srf2(pass,"A_dif_SW","Albedo diffus",falb_dif(:,:,:))

    CALL put_field_srf1(pass,"U10M", "u a 10m", u10m)

    CALL put_field_srf1(pass,"V10M", "v a 10m", v10m)


! ================== Tsoil =========================================
    CALL put_field_srf2(pass,"Tsoil","Temperature",tsoil(:,:,:))
!FC
!  CALL put_field_srf2("treedrg","freinage arbres",treedrg(:,:,:))
    CALL put_field(pass,"treedrg_ter","freinage arbres",treedrg(:,:,is_ter))
!AM
    CALL put_field_srf1(pass,"frac_tersrf","fraction sous surface", frac_tersrf(:,:))
    CALL put_field_srf1(pass,"z0m_tersrf","rugosite sous surface", z0m_tersrf(:,:))
    CALL put_field_srf1(pass,"ratio_z0m_z0h_tersrf","ratio rugosites sous surface", ratio_z0m_z0h_tersrf(:,:))
    CALL put_field_srf1(pass,"albedo_tersrf","albedo sous surface", albedo_tersrf(:,:))
    CALL put_field_srf1(pass,"beta_tersrf","beta sous surface", beta_tersrf(:,:))
    CALL put_field_srf1(pass,"inertie_tersrf","inertie sous surface", inertie_tersrf(:,:))
    CALL put_field_srf1(pass,"hcond_tersrf","conductivité thermique sous surface", hcond_tersrf(:,:))
    CALL put_field_srf1(pass,"tsurfi_tersrf","temperature surface sous surface initiale", tsurfi_tersrf(:,:))
    CALL put_field_srf2(pass,"Tsoili","temperature sol sous surface initiale", tsoili_tersrf(:,:,:))
    CALL put_field_srf2(pass,"tsoil_depth","profondeur temperature sol sous surface", tsoil_depth(:,:,:))
    CALL put_field_srf1(pass,"qsurf_tersrf","humidite surface sous surface", qsurf_tersrf(:,:))
    CALL put_field_srf1(pass,"tsurf_tersrf","temperature surface sous surface", tsurf_tersrf(:,:))
    CALL put_field_srf1(pass,"tsurf_new_tersrf","temperature surface sous surface", tsurf_new_tersrf(:,:))
    CALL put_field_srf1(pass,"cdragm_tersrf","coeff trainee quantite mouvement sous surface", cdragm_tersrf(:,:))
    CALL put_field_srf1(pass,"cdragh_tersrf","coeff trainee chaleur sous surface", cdragh_tersrf(:,:))
    CALL put_field_srf1(pass,"swnet_tersrf","shortwave net sous surface", swnet_tersrf(:,:))
    CALL put_field_srf1(pass,"lwnet_tersrf","longwave net sous surface", lwnet_tersrf(:,:))
    CALL put_field_srf1(pass,"fluxsens_tersrf","flux sensible sous surface", fluxsens_tersrf(:,:))
    CALL put_field_srf1(pass,"fluxlat_tersrf","flux latent sous surface", fluxlat_tersrf(:,:))
    CALL put_field_srf2(pass,"tsoil_tersrf","temperature sol sous surface", tsoil_tersrf(:,:,:))

    CALL put_field_srf1(pass,"QS"  , "Humidite",qsurf(:,:))

    CALL put_field     (pass,"QSOL", "Eau dans le sol (mm)", qsol)

    CALL put_field_srf1(pass,"EVAP", "Evaporation", fevap(:,:))

    CALL put_field_srf1(pass,"SNOW", "Neige", snow(:,:))

    !GG
    CALL put_field(pass,"hice", "Ice thickness", hice)
    CALL put_field(pass,"tice", "Sea Ice temperature", tice)
    CALL put_field(pass,"bilg_cumul", "Flux conductivite + transmit sea-ice", bilg_cumul)
    !GG

    CALL put_field(pass,"RADS", "Rayonnement net a la surface", radsol)

    CALL put_field(pass,"solsw", "Rayonnement solaire a la surface", solsw)

    CALL put_field(pass,"solswfdiff", "Fraction du rayonnement solaire a la surface qui est diffus", solswfdiff)

    CALL put_field(pass,"sollw", "Rayonnement IF a la surface", sollw)

    CALL put_field(pass,"sollwdown", "Rayonnement down IF a la surface", sollwdown)

    CALL put_field(pass,"fder", "Derive de flux", fder)

    CALL put_field(pass,"rain_f", "precipitation liquide", rain_fall)

    CALL put_field(pass,"snow_f", "precipitation solide", snow_fall)

    CALL put_field_srf1(pass,"Z0m", "rugosite", z0m(:,:))

    CALL put_field_srf1(pass,"Z0h", "rugosite", z0h(:,:))

    CALL put_field_srf1(pass,"AGESNO", "Age de la neige", agesno(:,:))

    CALL put_field(pass,"ZMEA", "ZMEA", zmea)

    CALL put_field(pass,"ZSTD", "ZSTD", zstd)

    CALL put_field(pass,"ZSIG", "ZSIG", zsig)

    CALL put_field(pass,"ZGAM", "ZGAM", zgam)

    CALL put_field(pass,"ZTHE", "ZTHE", zthe)

    CALL put_field(pass,"ZPIC", "ZPIC", zpic)

    CALL put_field(pass,"ZVAL", "ZVAL", zval)

    CALL put_field(pass,"RUGSREL", "RUGSREL", rugoro)

    CALL put_field(pass,"TANCIEN", "TANCIEN", t_ancien)

    CALL put_field(pass,"QANCIEN", "QANCIEN", q_ancien)

    CALL put_field(pass,"QLANCIEN", "QLANCIEN", ql_ancien)

    CALL put_field(pass,"QSANCIEN", "QSANCIEN", qs_ancien)

    IF (ok_bs) THEN
      CALL put_field(pass,"bs_f", "precipitation neige soufflee", bs_fall)
      CALL put_field(pass,"QBSANCIEN", "QBSANCIEN", qbs_ancien)
      CALL put_field(pass,"PRBSWANCIEN", "PRBSWANCIEN", prbsw_ancien)
    ENDIF

    IF ( ok_ice_supersat ) THEN
      CALL put_field(pass,"CFANCIEN", "CFANCIEN", cf_ancien)
      CALL put_field(pass,"RVCANCIEN", "RVCANCIEN", rvc_ancien)
    ENDIF

    CALL put_field(pass,"PRWANCIEN", "PRWANCIEN", prw_ancien)

    CALL put_field(pass,"PRLWANCIEN", "PRLWANCIEN", prlw_ancien)

    CALL put_field(pass,"PRSWANCIEN", "PRSWANCIEN", prsw_ancien)

    CALL put_field(pass,"UANCIEN", "UANCIEN", u_ancien)

    CALL put_field(pass,"VANCIEN", "VANCIEN", v_ancien)

    CALL put_field(pass,"CLWCON", "Eau liquide convective", clwcon)

    CALL put_field(pass,"RNEBCON", "Nebulosite convective", rnebcon)

    CALL put_field(pass,"RATQS", "Ratqs", ratqs)

    ! run_off_lic_0

    CALL put_field(pass,"RUNOFFLIC0", "Runofflic0", run_off_lic_0)

    ! DEB TKE PBL !

    IF (ok_advtke) THEN
      CALL put_field(pass,"TKEANCIEN", "TKEANCIEN", tke_ancien)
    ENDIF

    IF (iflag_pbl>1) then
      CALL put_field_srf3(pass,"TKE", "Energ. Cineti. Turb.", &
           pbl_tke(:,:,:))
      CALL put_field_srf3(pass,"DELTATKE", "Del TKE wk/env.", &
           wake_delta_pbl_tke(:,:,:))
    END IF

    ! FIN TKE PBL !
    !IM ajout zmax0, f0, sig1, w01
    !IM wake_deltat, wake_deltaq, wake_s, wake_cstar, wake_pe, wake_fip

    CALL put_field(pass,"ZMAX0", "ZMAX0", zmax0)

    CALL put_field(pass,"F0", "F0", f0)

    CALL put_field(pass,"sig1", "sig1 Emanuel", sig1)

    CALL put_field(pass,"w01", "w01 Emanuel", w01)

    ! wake_deltat
    CALL put_field(pass,"WAKE_DELTAT", "WAKE_DELTAT", wake_deltat)

    CALL put_field(pass,"WAKE_DELTAQ", "WAKE_DELTAQ", wake_deltaq)

    CALL put_field(pass,"WAKE_S", "Wake frac. area", wake_s)

    CALL put_field(pass,"AWAKE_S", "Active Wake frac. area", awake_s)

    CALL put_field(pass,"WAKE_DENS", "Wake num. /unit area", wake_dens)

    CALL put_field(pass,"AWAKE_DENS", "Active Wake num. /unit area", awake_dens)

    CALL put_field(pass,"CV_GEN", "CB birth rate", cv_gen)

    CALL put_field(pass,"WAKE_CSTAR", "WAKE_CSTAR", wake_cstar)

    CALL put_field(pass,"WAKE_PE", "WAKE_PE", wake_pe)

    CALL put_field(pass,"WAKE_FIP", "WAKE_FIP", wake_fip)

    ! thermiques

    CALL put_field(pass,"FM_THERM", "FM_THERM", fm_therm)

    CALL put_field(pass,"ENTR_THERM", "ENTR_THERM", entr_therm)

    CALL put_field(pass,"DETR_THERM", "DETR_THERM", detr_therm)

    CALL put_field(pass,"ALE_BL", "ALE_BL", ale_bl)

    CALL put_field(pass,"ALE_BL_TRIG", "ALE_BL_TRIG", ale_bl_trig)

    CALL put_field(pass,"ALP_BL", "ALP_BL", alp_bl)

    CALL put_field(pass,"ALE_WAKE", "ALE_WAKE", ale_wake)

    CALL put_field(pass,"ALE_BL_STAT", "ALE_BL_STAT", ale_bl_stat)


    ! fisrtilp/clouds
    CALL put_field(pass,"RATQS_INTER","Relative width of the lsc sugrid scale water",ratqs_inter_)


    IF (ANY(type_trac == ['co2i','inco'])) THEN
       IF (carbon_cycle_cpl) THEN
          IF (.NOT. ALLOCATED(co2_send)) THEN
             ! This is the case of create_etat0_limit, ce0l
             ALLOCATE(co2_send(klon))
             co2_send(:) = co2_ppm0
          END IF
          CALL put_field(pass,"co2_send", "co2_ppm for coupling", co2_send)
       END IF

    ! trs from traclmdz_mod
    ELSE IF (type_trac == 'lmdz') THEN
       CALL traclmdz_to_restart(trs)
       it = 0
       DO iq = 1, nqtot
          IF(.NOT.tracers(iq)%isInPhysics) CYCLE
          it = it+1
          CALL put_field(pass,"trs_"//tracers(iq)%name, "", trs(:, it))
       END DO
    END IF

    ! Restart variables for Slab ocean
    IF (type_ocean == 'slab') THEN
        IF (nslay.EQ.1) THEN
          CALL put_field(pass,"tslab", "Slab ocean temperature", tslab)
        ELSE
          DO it=1,nslay
            WRITE(str2,'(i2.2)') it
            CALL put_field(pass,"tslab"//str2, "Slab ocean temperature", tslab(:,it))
          END DO
        END IF
        IF (version_ocean == 'sicINT') THEN
            CALL put_field(pass,"seaice", "Slab seaice (kg/m2)", seaice)
            CALL put_field(pass,"slab_tice", "Slab sea ice temperature", tice_slab)
        END IF
    END IF

    IF (ok_gwd_rando) CALL put_field(pass,"du_gwd_rando", &
         "tendency on zonal wind due to flott gravity waves", du_gwd_rando)

    IF (ok_gwd_rando) CALL put_field(pass,"du_gwd_front", &
         "tendency on zonal wind due to acama gravity waves", du_gwd_front)

    IF (activate_ocean_skin >= 1) THEN
      IF (activate_ocean_skin == 2 .AND. type_ocean == 'couple') THEN
        CALL put_field(pass, "delta_sal", &
             "ocean-air interface salinity minus bulk salinity", delta_sal)
        CALL put_field(pass, "delta_SST", &
             "ocean-air interface temperature minus bulk SST", delta_sst)
        CALL put_field(pass, "dter", &
             "ocean-air interface temperature minus subskin temperature", &
             dter)
        CALL put_field(pass, "dser", &
             "ocean-air interface salinity minus subskin salinity", dser)
        CALL put_field(pass, "dt_ds", &
             "(tks / tkt) * dTer", dt_ds)
      END IF
       
      CALL put_field(pass, "dS_ns", "delta salinity near surface", ds_ns)
      CALL put_field(pass, "dT_ns", "delta temperature near surface", dT_ns)
    END IF

#ifdef ISO
    WRITE(*,*) 'phyredem 342'
    CALL phyisoredem (pass, &
   &           xtsnow, &
   &           xtrun_off_lic_0,Rland_ice, Rsol, &
   &           run_off_lic_0)
#endif
    IF (pass==1) CALL enddef_restartphy
    IF (pass==2) CALL close_restartphy
  ENDDO ! DO pass=1,2   ! pass=1 netcdf definition ; pass=2 netcdf write
  
  !$OMP BARRIER


  CONTAINS


SUBROUTINE put_field_srf1(pass,nam,lnam,field)

  IMPLICIT NONE
  INTEGER, INTENT(IN)           :: pass
  CHARACTER(LEN=*),  INTENT(IN) :: nam, lnam
  REAL,              INTENT(IN) :: field(:,:)
  CHARACTER(LEN=256) :: nm, lm, str
  DO nsrf = 1, SIZE(field,2)
    WRITE(str, '(i2.2)') nsrf
    nm=TRIM(nam)//TRIM(str)
    lm=TRIM(lnam)//" de surface No. "//TRIM(str)
    CALL put_field(pass,nm,lm,field(:,nsrf))
  END DO

END SUBROUTINE put_field_srf1


SUBROUTINE put_field_srf2(pass,nam,lnam,field)

  IMPLICIT NONE
  INTEGER, INTENT(IN)           :: pass
  CHARACTER(LEN=*),  INTENT(IN) :: nam, lnam
  REAL,              INTENT(IN) :: field(:,:,:)
  CHARACTER(LEN=256) :: nm, lm, str
  DO nsrf = 1, SIZE(field,3)
    DO isoil=1, SIZE(field,2)
      WRITE(str, '(i2.2,"srf",i2.2)')isoil,nsrf
!      WRITE(lunout,*)"PHYREDEM ",TRIM(nam)//TRIM(str)
      nm=TRIM(nam)//TRIM(str)
      lm=TRIM(lnam)//" du sol No. "//TRIM(str)
      CALL put_field(pass,nm,lm,field(:,isoil,nsrf))
    END DO
  END DO

END SUBROUTINE put_field_srf2


SUBROUTINE put_field_srf3(pass,nam,lnam,field)

  IMPLICIT NONE
  INTEGER, INTENT(IN)           :: pass
  CHARACTER(LEN=*),  INTENT(IN) :: nam, lnam
  REAL,              INTENT(IN) :: field(:,:,:)
  CHARACTER(LEN=256) :: nm, lm, str
  DO nsrf = 1, SIZE(field,3)
    WRITE(str, '(i2.2)') nsrf
    nm=TRIM(nam)//TRIM(str)
    lm=TRIM(lnam)//TRIM(str)
    CALL put_field(pass,nm,lm,field(:,1:klev+1,nsrf))
  END DO

END SUBROUTINE put_field_srf3

#ifdef ISO
! je voulais mettre cette subroutine dans isotopes_mod, 
! mais elle a besoin de put_field_srf1 qui est contenue 
! dans la subroutine phyredem. Si on veut mettre cette 
! routine dans isotopes_mod, il faudrait convertir ce
! fichier en module pour pouvoir en appeler des routines

SUBROUTINE phyisoredem (pass, &
     &          xtsnow, &
     &          xtrun_off_lic_0,Rland_ice, Rsol, &
     &          run_off_lic_0) 
 USE dimphy
 !USE mod_grid_phy_lmdz
 !USE mod_phys_lmdz_para
  USE phys_state_var_mod, ONLY: q_ancien,xt_ancien,wake_deltaq,wake_deltaxt, &
         xtrain_fall,xtsnow_fall, ql_ancien,xtl_ancien,qs_ancien,xts_ancien, &
         xtsol,fxtevap
  USE infotrac_phy,ONLY: niso, ntiso
  !USE control_mod
  USE indice_sol_mod, ONLY: nbsrf
  USE iostart, ONLY: put_field
  USE isotopes_mod, ONLY: isoName,iso_eau
#ifdef ISOVERIF
  USE isotopes_verif_mod
#endif
#ifdef ISOTRAC
  USE isotrac_mod, ONLY: index_zone,index_iso,strtrac
#endif
  USE compbl_mod_h
  USE clesphys_mod_h
  USE dimsoil_mod_h, ONLY: nsoilmx

  IMPLICIT NONE

  ! equivalent isotopique de phyredem
  ! inputs
  !REAL xtsol(niso,klon)
  REAL, INTENT(IN)    :: xtsnow(niso,klon,nbsrf) 
  !REAL xtevap(ntiso,klon,nbsrf)     
  REAL, INTENT(IN)    :: xtrun_off_lic_0(niso,klon)
  REAL, INTENT(IN)    :: Rland_ice(niso,klon)
  REAL, INTENT(IN)    :: Rsol(niso,klon)
  REAL, INTENT(IN)    :: run_off_lic_0(klon)
  INTEGER, INTENT(IN) :: pass

  ! locals
  REAL iso_tmp(klon)
  REAL iso_tmp_lonlev(klon,klev)
  REAL iso_tmp_lonsrf(klon,nbsrf)
  INTEGER i,ixt,k,nsrf
  INTEGER nid, nvarid
  INTEGER ierr
  CHARACTER*7 str7
  CHARACTER*2 str2
  CHARACTER*50 outiso
  INTEGER lnblnk
#ifdef ISOTRAC
  INTEGER iiso,izone
#endif      

  WRITE(*,*) 'phyisoredem 41: entrée'
#ifdef ISOVERIF
  IF (iso_eau.GT.0) THEN
    DO k=1,klev
      DO i=1,klon
        CALL iso_verif_egalite(xt_ancien(iso_eau,i,k),q_ancien(i,k), &
     &           'phyisoredem 50a')
        CALL iso_verif_egalite(xtl_ancien(iso_eau,i,k),ql_ancien(i,k), &
     &           'phyisoredem 50b')
        CALL iso_verif_egalite(xts_ancien(iso_eau,i,k),qs_ancien(i,k), &
     &           'phyisoredem 50c')
          
      ENDDO !do i=1,klon
    ENDDO !do k=1,klev
    DO i=1,klon
      DO nsrf = 1, nbsrf
        CALL iso_verif_egalite(fxtevap(iso_eau,i,nsrf),fevap(i,nsrf), &
     &           'phyisoredem 50d')
      ENDDO !DO nsrf = 1, nbsrf
    ENDDO
  ENDIF !if (iso_eau.gt.0) then

  DO i=1,klon
    DO ixt=1,niso
      CALL iso_verif_noNaN(xtsol(ixt,i),'phyisoredem 72')
    ENDDO !do ixt=1,niso
  ENDDO !do i=1,klon
#ifdef ISOTRAC        
  DO k=1,klev
    DO i=1,klon  
      CALL iso_verif_traceur(xt_ancien(1,i,k), &
     &                   'phyisoredem 60')  
    ENDDO !do i=1,klon
  ENDDO !do k=1,kle
#endif
#endif

  do ixt=1,ntiso

    outiso = TRIM(isoName(ixt))
    i = INDEX(outiso, '_', .TRUE.)
    outiso = outiso(1:i-1)//outiso(i+1:LEN_TRIM(outiso))
    write(*,*) 'phyredem 550: ixt,outiso=',ixt,TRIM(outiso)
      
    iso_tmp_lonsrf(:,:)=fxtevap(ixt,:,:)
    CALL put_field_srf1(pass, "XTEVAP"//TRIM(outiso), "Evaporation de surface",iso_tmp_lonsrf)

    iso_tmp(:)=xtrain_fall(ixt,:)
    CALL put_field(pass,    "xtrain_f"//TRIM(outiso), "precipitation liquide",iso_tmp)

    iso_tmp(:)=xtsnow_fall(ixt,:)
    CALL put_field(pass,    "xtsnow_f"//TRIM(outiso), "precipitation solide",iso_tmp)

    iso_tmp_lonlev(:,:)=xt_ancien(ixt,:,:)
    CALL put_field(pass,    "XTANCIEN"//TRIM(outiso), "QANCIEN",     iso_tmp_lonlev)

    iso_tmp_lonlev(:,:)=xtl_ancien(ixt,:,:)
    CALL put_field(pass,   "XTLANCIEN"//TRIM(outiso), "QLANCIEN",    iso_tmp_lonlev)

    iso_tmp_lonlev(:,:)=xts_ancien(ixt,:,:)
    CALL put_field(pass,   "XTSANCIEN"//TRIM(outiso), "QSANCIEN",    iso_tmp_lonlev)

    iso_tmp_lonlev(:,:)=wake_deltaxt(ixt,:,:)
    CALL put_field(pass,"WAKE_DELTAXT"//TRIM(outiso), "WAKE_DELTAQ", iso_tmp_lonlev)

    iso_tmp_lonlev(:,:)=wake_deltaxt(ixt,:,:)
    CALL put_field(pass,"WAKE_DELTAXT"//TRIM(outiso), "WAKE_DELTAXT",iso_tmp_lonlev)

    ! variables seulement pour niso:
    IF (ixt.LE.niso) THEN

      iso_tmp_lonsrf(:,:)=xtsnow(ixt,:,:)
      CALL put_field_srf1(pass, "XTSNOW"//TRIM(outiso), "NEIGE",       iso_tmp_lonsrf)

      iso_tmp(:)=xtsol(ixt,:)
      CALL put_field(pass,      "XTSOL"//TRIM(outiso), "Eau dans le sol (mm)",iso_tmp)

      iso_tmp(:)=Rland_ice(ixt,:)
      CALL put_field(pass,  "Rland_ice"//TRIM(outiso), "ratio land ice",      iso_tmp)

      iso_tmp(:)=Rsol(ixt,:)
      CALL put_field(pass,  "Rsol"//TRIM(outiso), "ratio land soil",      iso_tmp)

      iso_tmp(:)=xtrun_off_lic_0(ixt,:)
      CALL put_field(pass,"XTRUNOFFLIC0"//TRIM(outiso), "Runofflic0",  iso_tmp)

    ENDIF ! if (ixt.le.niso) then

  ENDDO !do ixt=1,niso

  WRITE(*,*) 'phyisoredem 261: sortie'

END SUBROUTINE phyisoredem
#endif

END SUBROUTINE phyredem
