MODULE compute_temperature_mod
   USE prec, ONLY: rstd
   IMPLICIT NONE
   PRIVATE
   SAVE

   PUBLIC :: temperature, compute_temperature_unst, compute_temperature_hex

CONTAINS

   SUBROUTINE temperature(f_pmid, f_q, f_temp)
      USE compute_diagnostics_mod, ONLY: compute_temperature
      USE icosa
      TYPE(t_field), POINTER :: f_pmid(:)         ! IN
      TYPE(t_field), POINTER :: f_q(:)            ! IN
      TYPE(t_field), POINTER :: f_temp(:)         ! IN: theta, OUT: temperature

      REAL(rstd), POINTER :: pmid(:, :)
      REAL(rstd), POINTER :: q(:, :, :)
      REAL(rstd), POINTER :: temp(:, :)
      INTEGER :: ind

      DO ind = 1, ndomain
         IF (.NOT. assigned_domain(ind)) CYCLE
         CALL swap_dimensions(ind)
         CALL swap_geometry(ind)
         pmid = f_pmid(ind)
         q = f_q(ind)
         temp = f_temp(ind)
         CALL compute_temperature(pmid, q, temp)
      END DO
   END SUBROUTINE temperature

   SUBROUTINE compute_temperature_unst(pmid, q, temp)
      USE thermodynamics_mod, ONLY: temperature_from_pCq
      USE earth_const, ONLY: thermo
      REAL(rstd), INTENT(IN)    :: pmid(:, :), q(:, :, :)
      REAL(rstd), INTENT(INOUT) :: temp(:, :)

      CALL temperature_from_pCq(thermo, SIZE(temp), SIZE(temp), SIZE(q, 3), &
                                temp, pmid, temp, q) ! FIXME : OpenMP
   END SUBROUTINE compute_temperature_unst

   SUBROUTINE compute_temperature_hex(pmid, q, temp)
      USE icosa
      USE omp_para
      USE thermodynamics_mod, ONLY: temperature_from_pCq
      USE earth_const, ONLY: thermo
      REAL(rstd), INTENT(IN)    :: pmid(:, :), q(:, :, :)
      REAL(rstd), INTENT(INOUT) :: temp(:, :) ! IN: theta, OUT: temperature

      INTEGER :: l
      DO l = ll_begin, ll_end
         CALL temperature_from_pCq(thermo, iim*jjm, iim*jjm*llm, nqtot, &
                                   temp(:, l), pmid(:, l), temp(:, l), q(:, l, 1))
      END DO
   END SUBROUTINE compute_temperature_hex

END MODULE compute_temperature_mod
