! $Id: phys_output_mod.F90 6190 2026-04-23 15:22:46Z lguez $
!

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
  LOGICAL, DIMENSION(nfiles)   :: phys_out_filekeys


! 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
! AI. nov 2024 : Modifs pour rajouter plus de choix pour la frequence temporelle d'archivage
!                dans les fichiers de sorties (avec IOIPSL) :
!                month(s),m,mth,mois,m,day(s),d,jour(s),j, ...
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

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, &
       phys_out_filestations, 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
    USE AERO_MOD, ONLY : nbands_lw_rrtm !FC
    ! ug Pour les sorties XIOS
    USE wxios_mod
    USE infotrac_phy, ONLY: nbtr_bin
#ifdef ISO
    USE isotopes_mod, ONLY: isoName,iso_HTO
#ifdef ISOTRAC
    USE isotrac_mod, ONLY: index_zone,index_iso,strtrac
#endif
#endif
    USE clesphys_mod_h
    USE lmdz_cppkeys_wrapper, ONLY: CPPKEY_STRATAER
    USE yomcst_mod_h
    USE surface_data,     ONLY : type_ocean, ok_veget
    USE conf_phys_m, ONLY : ok_mensuel,ok_journe, &
                            ok_hf,ok_instan,ok_LES,ok_ade,ok_aie, &
                            aerosol_couple, flag_aerosol_strat
    USE compbl_mod_h, ONLY : iflag_pbl,iflag_pbl_split

    IMPLICIT NONE


    ! ug Nouveaux arguments necessaires 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
    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, itrb, ixt, iiso, izone
    INTEGER                               :: naero
    CHARACTER(LEN=4)                      :: bb2
    CHARACTER(LEN=2)                      :: bb3
    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_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.]
    REAL, DIMENSION(nfiles), SAVE ::  phys_out_lonmax  = [   180.,    180.,    180.,    180.,    180.,    180.,    180.,    180.,    180.,    180.]
    REAL, DIMENSION(nfiles), SAVE ::  phys_out_latmin  = [   -90.,    -90.,    -90.,    -90.,    -90.,    -90.,    -90.,    -90.,    -90.,    -90.]
    REAL, DIMENSION(nfiles), SAVE ::  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 utilisees pour recuperer 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
!FC
    INTEGER                         :: ILW
    REAL,  DIMENSION(nbands_lw_rrtm):: wl1_lw, wl2_lw

    WRITE(lunout,*) 'Debut phys_output_mod.F90'
! Initialisations (Valeurs par defaut
!FC
       wl1_lw = [ 10., 250., 500., 630., 700., 820., 980.,1080. &
     & ,1180.,1390.,1480.,1800.,2080.,2250.,2380.,2600.]
       wl2_lw = [250., 500., 630., 700., 820., 980.,1080.,1180. &
     & ,1390.,1480.,1800.,2080.,2250.,2380.,2600.,3000.]
!         print*, 'avant boucle', nbands_lw_rrtm
!        DO ILW=1,nbands_lw_rrtm
!        spectbandLW(ILW)= (wl1_lw(ilw) + wl2_lw(ILW) )/2
!        print*, 'on a les canaux ? ',ILW,spectbandLW(ILW),wl1_lw(ILW),wl2_lw(ilw)
!        enddo
!        print*, 'spectbandLW',spectbandLW

!FC


    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_wet_cv(nqtot), o_dtr_wet(nqtot))
    ALLOCATE(o_dtr_dry(nqtot),o_dtr_vdf(nqtot))
IF (CPPKEY_STRATAER) THEN
    ALLOCATE(o_nd_mode(nbtr_bin),o_sulfmmr_mode(nbtr_bin))
END IF
#ifdef ISO
    ALLOCATE(o_xtprw(ntraciso)) ! CAa
    ALLOCATE(o_uxtflux(ntraciso))   ! CAa
    ALLOCATE(o_vxtflux(ntraciso))   ! CAa
    ALLOCATE(o_xtprecip(ntraciso))
    ALLOCATE(o_Rland_ice(ntraciso))         ! Niels
    ALLOCATE(o_xtsnow_srf(ntraciso, nbsrf)) ! Niels 18 janvier 2024
    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_xtriverflow(ntraciso))   !PRSN
    ALLOCATE(o_xtcoastalflow(ntraciso))
    ALLOCATE(o_Rsol(ntraciso))          !PRSN
    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:3) = .TRUE.
    clef_files(4:10) = .FALSE.
    IF (CPPKEY_STRATAER) THEN
      clef_files(10)= .TRUE.
    ELSE
      clef_files(10)= .FALSE.
    END IF

    !sortir des fichiers "stations" si clef_stations(:)=.TRUE.
    clef_stations(1:10) = .FALSE.
    lev_files(1:10) = 5

    print*,'A ecrit_mth=',ecrit_mth
    ! Frequencies of the history files;
    ! Defaut
    ! overwritten by chtimestep given to convers_timesteps
    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:10) = ecrit_ins

    !! 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).eq.'Default' ) THEN
          ! Par defaut ecrit_files = (ecrit_mensuel ecrit_jour ecrit_hf
          ! ...)*86400.
          ecrit_files(iff)=ecrit_files(iff)*86400.
      ELSE IF (chtimestep(iff).eq.'-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)) 
       PRINT*,'Dans phys_output_open, iff=',iff,' ecrit_files=',ecrit_files(iff)
      ENDIF
      ! ecrit_files contains frequency of file iif in seconds 


       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.LE.6.OR.iff.EQ.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).le.phys_out_lonmin(iff)) imin_ins=i
                IF (io_lon(i).le.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).ge.phys_out_latmin(iff)) jmax_ins=j+1
                IF (io_lat(j).ge.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.LE.6.OR.iff.EQ.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))
!FC
!          CALL histvert(nid_files(iff), "spectbandLW"," LW bands ", "cm-1", &
!                  nbands_lw_rrtm ,wl1_lw, ncanaux(iff))
!          print *, ' apres ncanaux = ' , ncanaux(iff),iff
!FC


          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; itrb = 0
          DO iq = 1, nqtot 
            IF(.NOT.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 convective wet deposition'//TRIM(tracers(iq)%longName)
            tnam = TRIM(dn)//'wet_cv';       o_dtr_wet_cv       (itr) = ctrl_out(flag, tnam, lnam, "-", [('',i=1,nfiles)])
            lnam = 'tracer total wet deposition'//TRIM(tracers(iq)%longName)
            tnam = TRIM(dn)//'wet';       o_dtr_wet       (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)])
            
IF (CPPKEY_STRATAER) THEN
            if(tracers(iq)%name(1:3)=='BIN') then
               itrb = itrb + 1
               flag = [11, 11, 11, 11, 11, 11, 11, 11, 11, 1]
               lnam = 'Dry particle concentration in '//TRIM(tracers(iq)%longName)
               tnam = TRIM(tracers(iq)%name)//'_nd_mode';     o_nd_mode       (itrb) = ctrl_out(flag, tnam, lnam, "part/m3", [('',i=1,nfiles)])
               lnam = 'Sulfate MMR in '//TRIM(tracers(iq)%longName)
               tnam = TRIM(tracers(iq)%name)//'_sulfmmr_mode';o_sulfmmr_mode  (itrb) = ctrl_out(flag, tnam, lnam, "kg(H2SO4)/kg(air)", [('',i=1,nfiles)])
            endif
END IF
         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, 10, 10, 10, 10, 11, 11, 11, 11]
      unit = 'kg/m2'
      o_xtprw(ixt)=ctrl_out(flag, 'prw'//TRIM(outiso), 'Precipitable water', unit, [('',i=1,nfiles)])
      unit = 'kg/m/s'
      o_uxtflux(ixt)=ctrl_out(flag, 'uq'//TRIM(outiso), 'Zonal humidity transport', unit, [('',i=1,nfiles)])
      o_vxtflux(ixt)=ctrl_out(flag, 'vq'//TRIM(outiso), 'Merid humidity transport', unit, [('',i=1,nfiles)])

      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)])

      ! Niels 14 janvier 2024
      flag = [1,  1,  1, 10, 10, 10, 11, 11, 11, 11]; unit = '1'
      o_Rland_ice(ixt) = ctrl_out(flag, 'Rland_ice'//TRIM(outiso), 'R land ice', unit, [('',i=1,nfiles)])
      
      ! Snow above soil
      flag = [1,  1,  1, 10, 10, 10, 11, 11, 11, 11]; unit = 'kg/m2'
      !do nsrf = 1, nbsrf
      !  o_xtsnow_srf (ixt, nsrf) = &
      !      ctrl_out(flag, 'snow_'//clnsurf(nsrf)//TRIM(outiso), 'Snow sfc'//clnsurf(nsrf), unit, [('',i=1,nfiles)])
      !end do
      o_xtsnow_srf (ixt,1)=ctrl_out(flag, 'snow_ter'//TRIM(outiso), 'Snow sfc'//clnsurf(1), unit, [('',i=1,nfiles)])
      o_xtsnow_srf (ixt,2)=ctrl_out(flag, 'snow_lic'//TRIM(outiso), 'Snow sfc'//clnsurf(2), unit, [('',i=1,nfiles)])
      o_xtsnow_srf (ixt,3)=ctrl_out(flag, 'snow_oce'//TRIM(outiso), 'Snow sfc'//clnsurf(3), unit, [('',i=1,nfiles)])
      o_xtsnow_srf (ixt,4)=ctrl_out(flag, 'snow_sic'//TRIM(outiso), 'Snow sfc'//clnsurf(4), unit, [('',i=1,nfiles)])
      ! end Niels

      !PRSN

      flag = [1,  1,  1, 10, 5, 10, 11, 11, 11, 11]; unit = 'kg/(s*m2)'
      o_xtriverflow  (ixt)=ctrl_out(flag, 'rivflow'//TRIM(outiso), 'River flow to ocean', unit, [('',i=1,nfiles)])
      o_xtcoastalflow  (ixt)=ctrl_out(flag, 'coastflow'//TRIM(outiso), 'Coastal flow to ocean', unit, [('',i=1,nfiles)])

      flag = [1,  1,  1, 10, 5, 10, 11, 11, 11, 11]; unit = 'kg/kg'
      o_Rsol  (ixt)=ctrl_out(flag, 'Rsol'//TRIM(outiso), 'Isotopic soil ratio', unit, [('',i=1,nfiles)])
      !PRSN

      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.  
! WHY CHANGING ecrit_mth ?
! For Cosp ?
!    ecrit_mth = ecrit_files(1)
!    print*,'B ecrit_mth=',ecrit_mth
!    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
    PRINT*,'Dans phys_output_open,ecrit_files B',ecrit_files(1:6)

!  DO iq=1,nqtot
!    IF(.NOT.tracers(iq)%isInPhysics) CYCLE
!    WRITE(*,'(a,i1,a,10i3)')'trac(',iq,')%flag = ',o_trac(iq)%flag
!    WRITE(*,'(a,i1,a)')'trac(',iq,')%name = '//TRIM(o_trac(iq)%name)
!    WRITE(*,'(a,i1,a)')'trac(',iq,')%description = '//TRIM(o_trac(iq)%description)
!  END DO

  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 == 'd'.or.type == 'jours'.or.type == 'jour'.or.type == 'j' )&
           &  timestep = ttt * dayseconde
    IF ( type == 'months'.or.type == 'month'.or.type == 'mth'.or.type == 'mois'.or.type == 'm' .or.type == 'mo' ) 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 == 'hour'.or.type == 'hr'.or.type == 'heures'.or.type == 'heure'.or.type =='h' )&
           &  timestep = ttt * dayseconde / 24.
    IF ( type == 'mn'.or.type == 'minutes'.or.type == 'minute'.or.type == 'm' ) timestep = ttt * 60.
    IF ( type == 's'.or.type == 'sec'.or.type == 'secondes'.or.type =='seconde'   ) timestep = ttt
    IF ( type == 'TS' .or. 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
