!
! $Id: ocs_to_so2.f90 5268 2024-10-23 17:02:39Z abarral $
!
SUBROUTINE ocs_to_so2(pdtphys,tr_seri,t_seri,pplay,paprs,is_strato)

  USE dimphy, ONLY : klon,klev
  USE aerophys
  USE infotrac_phy
  USE yomcst_mod_h, ONLY : RG
  USE phys_local_var_mod, ONLY : OCS_lifetime, budg_3D_ocs_to_so2, budg_ocs_to_so2
  USE strataer_local_var_mod, ONLY : flag_min_rreduce

  IMPLICIT NONE

  !--------------------------------------------------------
  ! transfer variables when calling this routine
  REAL,INTENT(IN)                               :: pdtphys ! Pas d'integration pour la physique (seconde)
  REAL,DIMENSION(klon,klev,nbtr),INTENT(INOUT)  :: tr_seri ! Concentration Traceur [U/KgA]
  REAL,DIMENSION(klon,klev),INTENT(IN)          :: t_seri  ! Temperature
  REAL,DIMENSION(klon,klev),INTENT(IN)          :: pplay   ! pression pour le mileu de chaque couche (en Pa)
  REAL,DIMENSION(klon,klev+1),INTENT(IN)        :: paprs   ! pression pour chaque inter-couche (en Pa)
  LOGICAL,DIMENSION(klon,klev),INTENT(IN)       :: is_strato

  ! local variables
  INTEGER                                       :: i,j,k,nb,ilon,ilev
  REAL                                          :: rreduce
  
!--convert OCS to SO2
  budg_3D_ocs_to_so2(:,:)=0.0
  budg_ocs_to_so2(:)=0.0

  DO ilon=1, klon
     DO ilev=1, klev
        !only in the stratosphere
        IF (is_strato(ilon,ilev)) THEN
          IF (OCS_lifetime(ilon,ilev).GT.0.0.AND.OCS_lifetime(ilon,ilev).LT.1.E10) THEN
            rreduce = OCS_lifetime(ilon,ilev)
            ! Check lifetime rreduce < timestep*3 (such as H2SO4 loss > 0.28*H2SO4) with exp(-1/3)=0.72
            IF(flag_min_rreduce) THEN
               IF (rreduce .LT. (3.*pdtphys)) rreduce = 3.*pdtphys
            ENDIF
            budg_3D_ocs_to_so2(ilon,ilev)=tr_seri(ilon,ilev,id_OCS_strat)*(1.0-exp(-pdtphys/rreduce))
            tr_seri(ilon,ilev,id_OCS_strat)=tr_seri(ilon,ilev,id_OCS_strat) - budg_3D_ocs_to_so2(ilon,ilev)
            tr_seri(ilon,ilev,id_SO2_strat)=tr_seri(ilon,ilev,id_SO2_strat) + mSO2mol/mOCSmol*budg_3D_ocs_to_so2(ilon,ilev)
            !convert budget from kg(OCS)/kgA to kg(S)/m2/layer/s for saving as diagnostic
            budg_3D_ocs_to_so2(ilon,ilev)=budg_3D_ocs_to_so2(ilon,ilev)*mSatom/mOCSmol*(paprs(ilon,ilev)-paprs(ilon,ilev+1))/RG/pdtphys
            budg_ocs_to_so2(ilon)=budg_ocs_to_so2(ilon)+budg_3D_ocs_to_so2(ilon,ilev)
         ENDIF
         ! END IF(OCS_lifetime(ilon,ilev).GT.0.0.AND.OCS_lifetime(ilon,ilev).LT.1.E10)
      ENDIF
      ! END IF(is_strato(ilon,ilev))
   ENDDO
  ENDDO

END SUBROUTINE ocs_to_so2
