! $Id: phys_output_mod.F90 3792 2021-01-04 17:01:25Z evignon $

MODULE phys_output_mod 
  USE indice_sol_mod
  USE phys_output_var_mod
  USE phys_output_write_mod, ONLY: phys_output_write
  REAL, DIMENSION(nfiles),SAVE :: ecrit_files
  USE lmdz_cppkeys_wrapper, ONLY: CPPKEY_STRATAER

! Abderrahmane 12 2007
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!! Ecreture des Sorties du modele dans les fichiers Netcdf :
! histmth.nc : moyennes mensuelles
! histday.nc : moyennes journalieres
! histhf.nc  : moyennes toutes les 3 heures
! histins.nc : valeurs instantanees
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

CONTAINS

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!! Ouverture des fichier et definition des variable de sortie !!!!!!!!
  !! histbeg, histvert et histdef
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 

  SUBROUTINE phys_output_open(rlon,rlat,pim,tabij,ipt,jpt,plon,plat, &
       jjmp1,nlevSTD,clevSTD,rlevSTD, dtime, ok_veget, &
       type_ocean, iflag_pbl,iflag_pbl_split,ok_mensuel,ok_journe, &
       ok_hf,ok_instan,ok_LES,ok_ade,ok_aie, read_climoz, &
       phys_out_filestations, &
       aerosol_couple, flag_aerosol_strat, &
       pdtphys, paprs, pphis, pplay, lmax_th, ptconv, ptconvth, ivap, &
       d_u, d_t, qx, d_qx, zmasse, ok_sync)   

    USE iophy 
    USE dimphy
    USE infotrac_phy, ONLY: nqtot, tracers, niso, ntraciso=>ntiso
    USE strings_mod,  ONLY: maxlen
    USE ioipsl
    USE phys_cal_mod, ONLY: hour, calend
    USE mod_phys_lmdz_para
    !Martin
    USE surface_data, ONLY: landice_opt
    USE phys_output_ctrlout_mod
    USE mod_grid_phy_lmdz, only: klon_glo,nbp_lon,nbp_lat
    USE print_control_mod, ONLY: prt_level,lunout
    USE vertical_layers_mod, ONLY: ap,bp,preff,presnivs, aps, bps, pseudoalt, presinter
    USE time_phylmdz_mod, ONLY: day_ini, itau_phy, start_time, annee_ref, day_ref
    ! ug Pour les sorties XIOS
    USE wxios
#ifdef ISO
    USE isotopes_mod, ONLY: isoName,iso_HTO
#ifdef ISOTRAC
    use isotrac_mod, only: index_zone,index_iso,strtrac
#endif
#endif

    IMPLICIT NONE
    include "clesphys.h"
    include "alpale.h"
    include "YOMCST.h"

    ! ug Nouveaux arguments n\'ecessaires au histwrite_mod:
    INTEGER, INTENT(IN)                         :: ivap
    INTEGER, DIMENSION(klon), INTENT(IN)        :: lmax_th
    LOGICAL, INTENT(IN)                         :: ok_sync
    LOGICAL, DIMENSION(klon, klev), INTENT(IN)  :: ptconv, ptconvth
    REAL, INTENT(IN)                            :: pdtphys
    REAL, DIMENSION(klon), INTENT(IN)           :: pphis
    REAL, DIMENSION(klon, klev), INTENT(IN)     :: pplay, d_u, d_t
    REAL, DIMENSION(klon, klev+1), INTENT(IN)   :: paprs
    REAL, DIMENSION(klon,klev,nqtot), INTENT(IN):: qx, d_qx
    REAL, DIMENSION(klon, klev), INTENT(IN)      :: zmasse


    REAL,DIMENSION(klon),INTENT(IN) :: rlon
    REAL,DIMENSION(klon),INTENT(IN) :: rlat
    INTEGER, INTENT(IN)             :: pim
    INTEGER, DIMENSION(pim)            :: tabij
    INTEGER,DIMENSION(pim), INTENT(IN) :: ipt, jpt
    REAL,DIMENSION(pim), INTENT(IN) :: plat, plon
    REAL,DIMENSION(pim,2) :: plat_bounds, plon_bounds

    INTEGER                               :: jjmp1
    INTEGER                               :: nlevSTD, radpas
    LOGICAL                               :: ok_mensuel, ok_journe, ok_hf, ok_instan
    LOGICAL                               :: ok_LES,ok_ade,ok_aie
    INTEGER                               :: flag_aerosol_strat
    LOGICAL                               :: aerosol_couple
    INTEGER, INTENT(IN)::  read_climoz ! read ozone climatology
    !     Allowed values are 0, 1 and 2
    !     0: do not read an ozone climatology
    !     1: read a single ozone climatology that will be used day and night
    !     2: read two ozone climatologies, the average day and night
    !     climatology and the daylight climatology

    REAL                                  :: dtime
    INTEGER                               :: idayref
    REAL                                  :: zjulian_start, zjulian
    CHARACTER(LEN=4), DIMENSION(nlevSTD)  :: clevSTD
    REAL, DIMENSION(nlevSTD)              :: rlevSTD
    INTEGER                               :: nsrf, k, iq, iff, i, j, ilev, itr, ixt, iiso, izone
    INTEGER                               :: naero
    LOGICAL                               :: ok_veget
    INTEGER                               :: iflag_pbl
    INTEGER                               :: iflag_pbl_split
    CHARACTER(LEN=4)                      :: bb2
    CHARACTER(LEN=2)                      :: bb3
    CHARACTER(LEN=6)                      :: type_ocean
    INTEGER, DIMENSION(nbp_lon*jjmp1)         ::  ndex2d
    INTEGER, DIMENSION(nbp_lon*jjmp1*klev)    :: ndex3d
    INTEGER                               :: imin_ins, imax_ins
    INTEGER                               :: jmin_ins, jmax_ins
    INTEGER, DIMENSION(nfiles)            :: phys_out_levmin, phys_out_levmax
    INTEGER, DIMENSION(nfiles)            :: phys_out_filelevels
    CHARACTER(LEN=20), DIMENSION(nfiles)  :: chtimestep = (/ 'Default', 'Default', 'Default', 'Default', 'Default', &
                                                             'Default', 'Default', 'Default', 'Default', 'Default' /)
    LOGICAL, DIMENSION(nfiles)            :: phys_out_filekeys
    LOGICAL, DIMENSION(nfiles)            :: phys_out_filestations

#ifdef ISO
    CHARACTER(LEN=maxlen) :: outiso
    CHARACTER(LEN=20) :: unit
#endif
    CHARACTER(LEN=maxlen) :: tnam, lnam, dn
    INTEGER :: flag(nfiles)

!!!!!!!!!! stockage dans une region limitee pour chaque fichier !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    !                 entre [phys_out_lonmin,phys_out_lonmax] et [phys_out_latmin,phys_out_latmax]
    LOGICAL, DIMENSION(nfiles), SAVE :: &
      phys_out_regfkey = [.FALSE., .FALSE., .FALSE., .FALSE., .FALSE., .FALSE., .FALSE., .FALSE., .FALSE., .FALSE.]
    REAL,    DIMENSION(nfiles), SAVE :: &
      phys_out_lonmin  = [  -180.,   -180.,   -180.,   -180.,   -180.,   -180.,   -180.,   -180.,   -180.,   -180.], &
      phys_out_lonmax  = [   180.,    180.,    180.,    180.,    180.,    180.,    180.,    180.,    180.,    180.], &
      phys_out_latmin  = [   -90.,    -90.,    -90.,    -90.,    -90.,    -90.,    -90.,    -90.,    -90.,    -90.], &
      phys_out_latmax  = [    90.,     90.,     90.,     90.,     90.,     90.,     90.,     90.,     90.,     90.]
    REAL, DIMENSION(klev,2) :: Ahyb_bounds, Bhyb_bounds
    REAL, DIMENSION(klev+1)   :: lev_index
                
    ! ug Variables utilis\'ees pour r\'ecup\'erer le calendrier pour xios
    INTEGER :: x_an, x_mois, x_jour
    REAL :: x_heure
    INTEGER :: ini_an, ini_mois, ini_jour
    REAL :: ini_heure
    INTEGER                         :: ISW
    REAL, DIMENSION(NSW)            :: wl1_sun, wl2_sun !wavelength bounds (in um) for SW
    REAL, DIMENSION(NSW)            :: wn1_sun, wn2_sun !wavenumber bounds (in m-1) for SW 
    REAL, DIMENSION(NSW)            :: spectband  !mean wavenumb. of each sp.band
    REAL, DIMENSION(NSW,2)          :: spbnds_sun !bounds of spectband

    WRITE(lunout,*) 'Debut phys_output_mod.F90'
    ! Initialisations (Valeurs par defaut

    DO ilev=1,klev
      Ahyb_bounds(ilev,1) = ap(ilev)
      Ahyb_bounds(ilev,2) = ap(ilev+1)
      Bhyb_bounds(ilev,1) = bp(ilev)
      Bhyb_bounds(ilev,2) = bp(ilev+1)
      lev_index(ilev) = REAL(ilev)
    END DO
      lev_index(klev+1) = REAL(klev+1)

    IF (.NOT. ALLOCATED(o_trac)) ALLOCATE(o_trac(nqtot))
    IF (.NOT. ALLOCATED(o_trac_cum)) ALLOCATE(o_trac_cum(nqtot))
    ALLOCATE(o_dtr_the(nqtot),o_dtr_con(nqtot),o_dtr_lessi_impa(nqtot))
    ALLOCATE(o_dtr_lessi_nucl(nqtot),o_dtr_insc(nqtot),o_dtr_bcscav(nqtot))
    ALLOCATE(o_dtr_evapls(nqtot),o_dtr_ls(nqtot),o_dtr_trsp(nqtot))
    ALLOCATE(o_dtr_sscav(nqtot),o_dtr_sat(nqtot),o_dtr_uscav(nqtot))
    ALLOCATE(o_dtr_dry(nqtot),o_dtr_vdf(nqtot))

#ifdef ISO
    ALLOCATE(o_xtprecip(ntraciso))
    ALLOCATE(o_xtplul(ntraciso))
    ALLOCATE(o_xtpluc(ntraciso))
    ALLOCATE(o_xtevap(ntraciso))
    ALLOCATE(o_xtevap_srf(ntraciso,4))
    ALLOCATE(o_xtovap(ntraciso))
    ALLOCATE(o_xtoliq(ntraciso))
    ALLOCATE(o_xtcond(ntraciso))
    ALLOCATE(o_xtrunoff_diag(ntraciso))
    ALLOCATE(o_dxtdyn(ntraciso))
    ALLOCATE(o_dxtldyn(ntraciso))
    ALLOCATE(o_dxtcon(ntraciso))
    ALLOCATE(o_dxtlsc(ntraciso))
    ALLOCATE(o_dxteva(ntraciso))
    ALLOCATE(o_dxtajs(ntraciso))
    ALLOCATE(o_dxtvdf(ntraciso))
    ALLOCATE(o_dxtthe(ntraciso))
    ALLOCATE(o_dxtch4(ntraciso))
    if (iso_HTO.gt.0) then
      ALLOCATE(o_dxtprod_nucl(ntraciso))
      ALLOCATE(o_dxtcosmo(ntraciso))
      ALLOCATE(o_dxtdecroiss(ntraciso))
    endif
#endif

    levmax = (/ klev, klev, klev, klev, klev, klev, nlevSTD, nlevSTD, nlevSTD, klev /)

    phys_out_filenames(1) = 'histmth'
    phys_out_filenames(2) = 'histday'
    phys_out_filenames(3) = 'histhf6h'
    phys_out_filenames(4) = 'histhf3h'
    phys_out_filenames(5) = 'histhf3hm'
    phys_out_filenames(6) = 'histstn'
    phys_out_filenames(7) = 'histmthNMC'
    phys_out_filenames(8) = 'histdayNMC'
    phys_out_filenames(9) = 'histhfNMC'
    phys_out_filenames(10)= 'histstrataer'

    type_ecri(1) = 'ave(X)'
    type_ecri(2) = 'ave(X)'
    type_ecri(3) = 'inst(X)'
    type_ecri(4) = 'inst(X)'
    type_ecri(5) = 'ave(X)'
    type_ecri(6) = 'inst(X)'
    type_ecri(7) = 'inst(X)'
    type_ecri(8) = 'inst(X)'
    type_ecri(9) = 'inst(X)'
    type_ecri(10)= 'ave(X)'

    clef_files(1) = ok_mensuel
    clef_files(2) = ok_journe
    clef_files(3) = ok_hf
    clef_files(4) = ok_instan
    clef_files(5) = ok_LES
    clef_files(6) = ok_instan
    clef_files(7) = ok_histNMC(1)
    clef_files(8) = ok_histNMC(2)
    clef_files(9) = ok_histNMC(3)
    clef_files(10)= CPPKEY_StratAer

    !sortir des fichiers "stations" si clef_stations(:)=.TRUE.
    clef_stations(1) = .FALSE.
    clef_stations(2) = .FALSE.
    clef_stations(3) = .FALSE.
    clef_stations(4) = .FALSE.
    clef_stations(5) = .FALSE.
    clef_stations(6) = .FALSE.
    clef_stations(7) = .FALSE.
    clef_stations(8) = .FALSE.
    clef_stations(9) = .FALSE.
    clef_stations(10)= .FALSE.

    lev_files(1) = lev_histmth
    lev_files(2) = lev_histday
    lev_files(3) = lev_histhf
    lev_files(4) = lev_histins
    lev_files(5) = lev_histLES
    lev_files(6) = lev_histins
    lev_files(7) = levout_histNMC(1)
    lev_files(8) = levout_histNMC(2)
    lev_files(9) = levout_histNMC(3)
    lev_files(10)= 5

    ecrit_files(1) = ecrit_mth
    ecrit_files(2) = ecrit_day
    ecrit_files(3) = ecrit_hf
    ecrit_files(4) = ecrit_ins
    ecrit_files(5) = ecrit_LES
    ecrit_files(6) = ecrit_ins
    ecrit_files(7) = freq_outNMC(1)
    ecrit_files(8) = freq_outNMC(2)
    ecrit_files(9) = freq_outNMC(3)
    ecrit_files(10)= ecrit_mth

    !! Lectures des parametres de sorties dans physiq.def

    CALL getin('phys_out_regfkey',phys_out_regfkey)
    CALL getin('phys_out_lonmin',phys_out_lonmin)
    CALL getin('phys_out_lonmax',phys_out_lonmax)
    CALL getin('phys_out_latmin',phys_out_latmin)
    CALL getin('phys_out_latmax',phys_out_latmax)
    phys_out_levmin(:)=levmin(:)
    CALL getin('phys_out_levmin',levmin)
    phys_out_levmax(:)=levmax(:)
    CALL getin('phys_out_levmax',levmax)
    CALL getin('phys_out_filenames',phys_out_filenames)
    phys_out_filekeys(:)=clef_files(:)
    CALL getin('phys_out_filekeys',clef_files)
    phys_out_filestations(:)=clef_stations(:)
    CALL getin('phys_out_filestations',clef_stations)
    phys_out_filelevels(:)=lev_files(:)
    CALL getin('phys_out_filelevels',lev_files)
    CALL getin('phys_out_filetimesteps',chtimestep)
    phys_out_filetypes(:)=type_ecri(:)
    CALL getin('phys_out_filetypes',type_ecri)

    type_ecri_files(:)=type_ecri(:)

!    if (ok_all_xml) phys_out_filelevels = 999

    WRITE(lunout,*)'phys_out_lonmin=',phys_out_lonmin
    WRITE(lunout,*)'phys_out_lonmax=',phys_out_lonmax
    WRITE(lunout,*)'phys_out_latmin=',phys_out_latmin
    WRITE(lunout,*)'phys_out_latmax=',phys_out_latmax
    WRITE(lunout,*)'phys_out_filenames=',phys_out_filenames
    WRITE(lunout,*)'phys_out_filetypes=',type_ecri
    WRITE(lunout,*)'phys_out_filekeys=',clef_files
    WRITE(lunout,*)'phys_out_filestations=',clef_stations
    WRITE(lunout,*)'phys_out_filelevels=',lev_files
    WRITE(lunout,*)'phys_out_regfkey=',phys_out_regfkey

! A noter pour
! l heure initiale - dans les fichiers histoire hist* - on met comme  
! heure de debut soit la vraie heure (pour le 1D) soit 0h (pour le 3D) 
! afin d avoir une seule sortie mensuelle par mois lorsque l on tourne 
! par annee (IM).

     idayref = day_ref
     IF (klon_glo==1) THEN
       ! current_time (used to compute hour) is updated at the begining of
       ! the physics; to set the correct outputs "initial time" we thus 
       ! have to use (hour-dtphys).
         CALL ymds2ju(annee_ref, 1, idayref, hour-pdtphys, zjulian)
         print *,'phys_output_mod: annee,iday,hour,zjulian=',annee_ref,idayref, hour, zjulian
     ELSE
         CALL ymds2ju(annee_ref, 1, idayref, 0.0, zjulian)
         CALL ymds2ju(annee_ref, 1, day_ini, start_time*rday, zjulian_start)
     ENDIF

    IF (using_xios) THEN
      ! ug R\'eglage du calendrier xios
      !Temps julian => an, mois, jour, heure
      CALL ju2ymds(zjulian, x_an, x_mois, x_jour, x_heure)
      CALL ju2ymds(zjulian_start, ini_an, ini_mois, ini_jour, ini_heure)
      CALL wxios_set_cal(dtime, calend, x_an, x_mois, x_jour, x_heure, ini_an, &
                         ini_mois, ini_jour, ini_heure )
    ENDIF

!!!!!!!!!!!!!!!!!!!!!!! Boucle sur les fichiers !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    ! Appel de histbeg et histvert pour creer le fichier et les niveaux verticaux !!
    ! Appel des histbeg pour definir les variables (nom, moy ou inst, freq de sortie ..
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    zdtime_moy = dtime         ! Frequence ou l on moyenne


  ecrit_files(7) = ecrit_files(1)
  ecrit_files(8) = ecrit_files(2)
  ecrit_files(9) = ecrit_files(3)

  DO iff=1,nfiles

       ! Calculate ecrit_files for all files
      IF ( chtimestep(iff)=='Default' ) THEN
          ! Par defaut ecrit_files = (ecrit_mensuel ecrit_jour ecrit_hf
          ! ...)*86400.
          ecrit_files(iff)=ecrit_files(iff)*86400.
      ELSE IF (chtimestep(iff)=='-1') THEN
          PRINT*,'ecrit_files(',iff,') < 0 so IOIPSL work on different'
          PRINT*,'months length'
          ecrit_files(iff)=-1.
      ELSE
       CALL convers_timesteps(chtimestep(iff),dtime,ecrit_files(iff)) 
      ENDIF

       WRITE(lunout,*)'ecrit_files(',iff,')= ',ecrit_files(iff)
       zoutm(iff) = ecrit_files(iff) ! Frequence ou l on ecrit en seconde


    IF (using_xios) THEN
!!! Ouverture de chaque fichier XIOS !!!!!!!!!!!
      IF (.not. ok_all_xml) THEN
        IF (prt_level >= 10) THEN
         PRINT*,'phys_output_open: CALL wxios_add_file with phys_out_filenames(iff)=',trim(phys_out_filenames(iff))
        ENDIF
        CALL wxios_add_file(phys_out_filenames(iff),chtimestep(iff),lev_files(iff))  
      ENDIF

!!! Declaration des axes verticaux de chaque fichier:
      IF (prt_level >= 10) THEN
        PRINT*,'phys_output_open: Declare vertical axes for each file'
      ENDIF

      IF (iff<=6.OR.iff==10) THEN
        CALL wxios_add_vaxis("presnivs", &
            levmax(iff) - levmin(iff) + 1, presnivs(levmin(iff):levmax(iff)))
        CALL wxios_add_vaxis("presinter", &
            klev + 1, presinter(1:klev+1))
        CALL wxios_add_vaxis("Ahyb", &
            levmax(iff) - levmin(iff) + 1, aps(levmin(iff):levmax(iff)), positif='down', &
            bnds=Ahyb_bounds(levmin(iff):levmax(iff),:))
        CALL wxios_add_vaxis("Bhyb", &
            levmax(iff) - levmin(iff) + 1, bps(levmin(iff):levmax(iff)), positif='down', &
            bnds=Bhyb_bounds(levmin(iff):levmax(iff),:))
        CALL wxios_add_vaxis("klev", levmax(iff) - levmin(iff) + 1, &
                          lev_index(levmin(iff):levmax(iff)))
        CALL wxios_add_vaxis("klevp1", klev+1, &
                          lev_index(1:klev+1))
        CALL wxios_add_vaxis("bnds", 2, (/1.,2./))

        CALL wxios_add_vaxis("Alt", &
            levmax(iff) - levmin(iff) + 1, pseudoalt)
  
        ! wl1_sun/wl2_sun: minimum/maximum bound of wavelength (in um)
        SELECT CASE(NSW)
          CASE(6)
          wl1_sun(1:6) = [0.180, 0.250, 0.440, 0.690, 1.190, 2.380]
          wl2_sun(1:6) = [0.250, 0.440, 0.690, 1.190, 2.380, 4.000]
        CASE(2)
          wl1_sun(1:2) = [0.250, 0.690]
          wl2_sun(1:2) = [0.690, 4.000]
        END SELECT

        DO ISW=1, NSW
          wn1_sun(ISW)=1.e+6/wl1_sun(ISW) 
          wn2_sun(ISW)=1.e+6/wl2_sun(ISW) 
          spbnds_sun(ISW,1)=wn2_sun(ISW)
          spbnds_sun(ISW,2)=wn1_sun(ISW)
          spectband(ISW)=(wn1_sun(ISW)+wn2_sun(ISW))/2
        ENDDO

!!! ajout axe vertical spectband : solar band number
        CALL wxios_add_vaxis("spectband", NSW, spectband, positif='down')
      ELSE
    ! NMC files
        CALL wxios_add_vaxis("plev", &
            levmax(iff) - levmin(iff) + 1, rlevSTD(levmin(iff):levmax(iff)))
      ENDIF
    ENDIF !using_xios

        IF (clef_files(iff)) THEN
!!!!!!!!!!!!!!!!! Traitement dans le cas ou l'on veut stocker sur un domaine limite !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
          IF (phys_out_regfkey(iff)) THEN
             imin_ins=1
             imax_ins=nbp_lon
             jmin_ins=1
             jmax_ins=jjmp1

             ! correction abderr        
             DO i=1,nbp_lon
                WRITE(lunout,*)'io_lon(i)=',io_lon(i)
                IF (io_lon(i)<=phys_out_lonmin(iff)) imin_ins=i
                IF (io_lon(i)<=phys_out_lonmax(iff)) imax_ins=i+1
             ENDDO

             DO j=1,jjmp1
                WRITE(lunout,*)'io_lat(j)=',io_lat(j)
                IF (io_lat(j)>=phys_out_latmin(iff)) jmax_ins=j+1
                IF (io_lat(j)>=phys_out_latmax(iff)) jmin_ins=j
             ENDDO

             WRITE(lunout,*)'On stoke le fichier histoire numero ',iff,' sur ', &
                  imin_ins,imax_ins,jmin_ins,jmax_ins
             WRITE(lunout,*)'longitudes : ', &
                  io_lon(imin_ins),io_lon(imax_ins), &
                  'latitudes : ', &
                  io_lat(jmax_ins),io_lat(jmin_ins)

             CALL histbeg(phys_out_filenames(iff),nbp_lon,io_lon,jjmp1,io_lat, &
                  imin_ins,imax_ins-imin_ins+1, &
                  jmin_ins,jmax_ins-jmin_ins+1, &
                  itau_phy,zjulian,dtime,nhorim(iff),nid_files(iff))
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
             !IM fichiers stations
          ELSE IF (clef_stations(iff)) THEN

             IF (prt_level >= 10) THEN
             WRITE(lunout,*)'phys_output_open: iff=',iff,'  phys_out_filenames(iff)=',phys_out_filenames(iff)
             ENDIF
             
             CALL histbeg_phy_all(rlon,rlat,pim,tabij,ipt,jpt,plon,plat,plon_bounds,plat_bounds, &
                  phys_out_filenames(iff), &
                  itau_phy,zjulian,dtime,nhorim(iff),nid_files(iff))
          ELSE

             IF (prt_level >= 10) THEN
             WRITE(lunout,*)'phys_output_open: iff=',iff,'  phys_out_filenames(iff)=',phys_out_filenames(iff)
             ENDIF

             CALL histbeg_phy_all(phys_out_filenames(iff),itau_phy,zjulian,&
                 dtime,nhorim(iff),nid_files(iff))
          ENDIF

#ifndef CPP_IOIPSL_NO_OUTPUT 
          IF (iff<=6.OR.iff==10) THEN
             CALL histvert(nid_files(iff), "presnivs", "Vertical levels", "Pa", &  
               levmax(iff) - levmin(iff) + 1, &
               presnivs(levmin(iff):levmax(iff)), nvertm(iff),"down")
!!!! Composantes de la coordonnee sigma-hybride 
          CALL histvert(nid_files(iff), "Ahyb","Ahyb comp of Hyb Cord ", "Pa", &
               levmax(iff) - levmin(iff) + 1,aps,nvertap(iff))

          CALL histvert(nid_files(iff), "Bhyb","Bhyb comp of Hyb Cord", " ", &
               levmax(iff) - levmin(iff) + 1,bps,nvertbp(iff))

          CALL histvert(nid_files(iff), "Alt","Height approx for scale heigh of 8km at levels", "Km", &                       
               levmax(iff) - levmin(iff) + 1,pseudoalt,nvertAlt(iff))

          ELSE
          ! NMC files
             CALL histvert(nid_files(iff), "plev", "pressure", "Pa", &
               levmax(iff) - levmin(iff) + 1, &
              rlevSTD(levmin(iff):levmax(iff)), nvertm(iff), "down")
          ENDIF
#endif

     ENDIF ! clef_files

          itr = 0
          DO iq = 1, nqtot 
            IF(.NOT.(tracers(iq)%isAdvected .AND. tracers(iq)%isInPhysics)) CYCLE
            itr = itr + 1
            dn = 'd'//TRIM(tracers(iq)%name)//'_'

            flag = [1, 5, 5, 5, 10, 10, 11, 11, 11, 11]
            lnam = 'Tracer '//TRIM(tracers(iq)%longName)
            tnam = TRIM(tracers(iq)%name);  o_trac          (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])

            flag = [4, 7, 7, 7, 10, 10, 11, 11, 11, 11]
            lnam = 'Tendance tracer '//TRIM(tracers(iq)%longName)
            tnam = TRIM(dn)//'vdf';         o_dtr_vdf       (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])

            flag = [5, 7, 7, 7, 10, 10, 11, 11, 11, 11]
            tnam = TRIM(dn)//'the';         o_dtr_the       (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])
            tnam = TRIM(dn)//'con';         o_dtr_con       (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])

            flag = [7, 7, 7, 7, 10, 10, 11, 11, 11, 11]
            tnam = TRIM(dn)//'lessi_impa';  o_dtr_lessi_impa(itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])
            tnam = TRIM(dn)//'lessi_nucl';  o_dtr_lessi_nucl(itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])
            tnam = TRIM(dn)//'insc';        o_dtr_insc      (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])
            tnam = TRIM(dn)//'bcscav';      o_dtr_bcscav    (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])
            tnam = TRIM(dn)//'evapls';      o_dtr_evapls    (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])
            tnam = TRIM(dn)//'ls';          o_dtr_ls        (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])
            tnam = TRIM(dn)//'trsp';        o_dtr_trsp      (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])
            tnam = TRIM(dn)//'sscav';       o_dtr_sscav     (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])
            tnam = TRIM(dn)//'sat';         o_dtr_sat       (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])
            tnam = TRIM(dn)//'uscav';       o_dtr_uscav     (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])

            lnam = 'tracer tendency dry deposition'//TRIM(tracers(iq)%longName)
            tnam = 'cum'//TRIM(dn)//'dry';  o_dtr_dry       (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])

            flag = [1, 4, 10, 10, 10, 10, 11, 11, 11, 11]
            lnam = 'Cumulated tracer '//TRIM(tracers(iq)%longName)
            tnam = 'cum'//TRIM(tracers(iq)%name); o_trac_cum(itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])
          ENDDO

   ENDDO !  iff

#ifdef ISO
    write(*,*) 'phys_output_mid 589'
    do ixt=1,ntraciso
      outiso = TRIM(isoName(ixt))
      i = INDEX(outiso, '_', .TRUE.)
      outiso = outiso(1:i-1)//outiso(i+1:LEN_TRIM(outiso))

      flag = [1,  1,  1, 10,  5, 10, 11, 11, 11, 11]; unit = 'kg/(s*m2)'
      o_xtprecip(ixt)=ctrl_out(flag, 'precip'//TRIM(outiso), 'Precip Totale liq+sol', unit, [('',i=1,nfiles)])
      o_xtpluc  (ixt)=ctrl_out(flag,   'pluc'//TRIM(outiso),    'Convective Precip.', unit, [('',i=1,nfiles)])

      flag = [1,  1,  1, 10, 10, 10, 11, 11, 11, 11]
      o_xtplul  (ixt)=ctrl_out(flag,   'plul'//TRIM(outiso),   'Large-scale Precip.', unit, [('',i=1,nfiles)])
      o_xtevap  (ixt)=ctrl_out(flag,   'evap'//TRIM(outiso),             'Evaporat.', unit, [('',i=1,nfiles)])

      ! ajout Camille 8 mai 2023
      flag = [1, 6, 10, 10, 10, 10, 11, 11, 11, 11]
      o_xtevap_srf (ixt,1)=ctrl_out(flag,   'evap_ter'//TRIM(outiso), 'Evap sfc'//clnsurf(1), unit, [('',i=1,nfiles)])
      o_xtevap_srf (ixt,2)=ctrl_out(flag,   'evap_lic'//TRIM(outiso), 'Evap sfc'//clnsurf(2), unit, [('',i=1,nfiles)])
      o_xtevap_srf (ixt,3)=ctrl_out(flag,   'evap_oce'//TRIM(outiso), 'Evap sfc'//clnsurf(3), unit, [('',i=1,nfiles)])
      o_xtevap_srf (ixt,4)=ctrl_out(flag,   'evap_sic'//TRIM(outiso), 'Evap sfc'//clnsurf(4), unit, [('',i=1,nfiles)])

      flag = [2,  3,  4, 10, 10, 10, 11, 11, 11, 11]; unit = 'kg/kg'
      o_xtovap  (ixt)=ctrl_out(flag,   'ovap'//TRIM(outiso),     'Specific humidity', unit, [('',i=1,nfiles)])
      o_xtoliq  (ixt)=ctrl_out(flag,   'oliq'//TRIM(outiso),          'Liquid water', unit, [('',i=1,nfiles)])
      o_xtcond  (ixt)=ctrl_out(flag,  'ocond'//TRIM(outiso),       'Condensed water', unit, [('',i=1,nfiles)])

      flag = [1,  1,  1, 10, 5, 10, 11, 11, 11, 11]; unit = 'kg/m2/s'
      o_xtrunoff_diag  (ixt)=ctrl_out(flag, 'runoffland'//TRIM(outiso), 'Run-off rate land for bucket', unit, [('',i=1,nfiles)])

      flag = [4, 10, 10, 10, 10, 10, 11, 11, 11, 11]; unit = '(kg/kg)/s'
      o_dxtdyn  (ixt)=ctrl_out(flag,  'dqdyn'//TRIM(outiso),           'Dynamics dQ', unit, [('',i=1,nfiles)])
      o_dxtldyn (ixt)=ctrl_out(flag, 'dqldyn'//TRIM(outiso),          'Dynamics dQL', unit, [('',i=1,nfiles)])
      o_dxtcon  (ixt)=ctrl_out(flag,  'dqcon'//TRIM(outiso),         'Convection dQ', unit, [('',i=1,nfiles)])
      o_dxteva  (ixt)=ctrl_out(flag,  'dqeva'//TRIM(outiso),      'Reevaporation dQ', unit, [('',i=1,nfiles)])
      o_dxtlsc  (ixt)=ctrl_out(flag,  'dqlsc'//TRIM(outiso),       'Condensation dQ', unit, [('',i=1,nfiles)])
      o_dxtajs  (ixt)=ctrl_out(flag,  'dqajs'//TRIM(outiso),        'Dry adjust. dQ', unit, [('',i=1,nfiles)])
      o_dxtvdf  (ixt)=ctrl_out(flag,  'dqvdf'//TRIM(outiso),     'Boundary-layer dQ', unit, [('',i=1,nfiles)])
      o_dxtthe  (ixt)=ctrl_out(flag,  'dqthe'//TRIM(outiso),            'Thermal dQ', unit, [('',i=1,nfiles)])

      IF(ok_qch4) o_dxtch4(ixt)=ctrl_out(flag, 'dqch4'//TRIM(outiso), 'H2O due to CH4 oxidation & photolysis', &
                                                                                      unit, [('',i=1,nfiles)])
      IF(ixt == iso_HTO) THEN
      o_dxtprod_nucl(ixt)=ctrl_out(flag, 'dqprodnucl'//TRIM(outiso), 'dHTO/dt due to nuclear production',      &
                                                                                      unit, [('',i=1,nfiles)])
      o_dxtcosmo    (ixt)=ctrl_out(flag,    'dqcosmo'//TRIM(outiso), 'dHTO/dt due to cosmogenic production',   &
                                                                                      unit, [('',i=1,nfiles)])
      o_dxtdecroiss (ixt)=ctrl_out(flag, 'dqdecroiss'//TRIM(outiso), 'dHTO/dt due to radiative destruction',   &
                                                                                      unit, [('',i=1,nfiles)])
      END IF
    enddo !do ixt=1,niso
    write(*,*) 'phys_output_mid 596'
#endif


    ! Updated write frequencies due to phys_out_filetimesteps. 
    ! Write frequencies are now in seconds.  
    ecrit_mth = ecrit_files(1)
    ecrit_day = ecrit_files(2)
    ecrit_hf  = ecrit_files(3)
    ecrit_ins = ecrit_files(4)
    ecrit_LES = ecrit_files(5)
    ecrit_ins = ecrit_files(6)

    IF (prt_level >= 10) THEN
      WRITE(lunout,*)'swaerofree_diag=',swaerofree_diag
      WRITE(lunout,*)'swaero_diag=',swaero_diag
      WRITE(lunout,*)'dryaod_diag=',dryaod_diag
      WRITE(lunout,*)'ok_4xCO2atm=',ok_4xCO2atm
      WRITE(lunout,*)'phys_output_open: ends here'
    ENDIF

  END SUBROUTINE phys_output_open

  SUBROUTINE convers_timesteps(str,dtime,timestep)

    use ioipsl
    USE phys_cal_mod
    USE time_phylmdz_mod, ONLY: day_ref, annee_ref
    USE print_control_mod, ONLY: lunout

    IMPLICIT NONE

    CHARACTER(LEN=20)   :: str
    CHARACTER(LEN=10)   :: type
    INTEGER             :: ipos,il
    real                :: ttt,xxx,timestep,dayseconde,dtime
    parameter (dayseconde=86400.)

    ipos=scan(str,'0123456789.',.TRUE.)

    il=len_trim(str)
    WRITE(lunout,*) "ipos = ", ipos
    WRITE(lunout,*) "il = ", il
    IF (ipos == 0) CALL abort_physic("convers_timesteps", "bad str", 1)
    read(str(1:ipos),*) ttt
    WRITE(lunout,*)ttt
    type=str(ipos+1:il)

    IF ( il == ipos ) THEN
       type='day'
    ENDIF

    IF ( type == 'day'.or.type == 'days'.or.type == 'jours'.or.type == 'jour' ) timestep = ttt * dayseconde
    IF ( type == 'mounths'.or.type == 'mth'.or.type == 'mois' ) THEN
       WRITE(lunout,*)'annee_ref,day_ref mon_len',annee_ref,day_ref,mth_len
       timestep = ttt * dayseconde * mth_len
    ENDIF
    IF ( type == 'hours'.or.type == 'hr'.or.type == 'heurs') timestep = ttt * dayseconde / 24.
    IF ( type == 'mn'.or.type == 'minutes'  ) timestep = ttt * 60.
    IF ( type == 's'.or.type == 'sec'.or.type == 'secondes'   ) timestep = ttt
    IF ( type == 'TS' ) timestep = ttt * dtime

    WRITE(lunout,*)'type =      ',type
    WRITE(lunout,*)'nb j/h/m =  ',ttt
    WRITE(lunout,*)'timestep(s)=',timestep

  END SUBROUTINE convers_timesteps

END MODULE phys_output_mod
