!        Generated by TAPENADE     (INRIA, Ecuador team)
!  tapenade 3.x
!
!  Differentiation of ftheta in reverse (adjoint) mode (with options noISIZE i8):
!   gradient     of useful results: tlocal theta dtheta
!   with respect to varying inputs: tlocal
! MIT License
!
! Copyright (c) 2020 SHEMAT-Suite
!
! Permission is hereby granted, free of charge, to any person obtaining a copy
! of this software and associated documentation files (the "Software"), to deal
! in the Software without restriction, including without limitation the rights
! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
! copies of the Software, and to permit persons to whom the Software is
! furnished to do so, subject to the following conditions:
!
! The above copyright notice and this permission notice shall be included in all
! copies or substantial portions of the Software.
!
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
! SOFTWARE.
!>    @brief calculates the fluid/ice partition function
!>    @param[in] tlocal = temperature
!>    @param[in] tliq = phase boundary temperature
!>    @param[in] wmushy =  scaling factor for "mushy" region = Tsolidus-tliqidus
!>    @param[in] ismpl local sample index
!>    @param[out] theta = value of partition function  (0<Theta<1)
!>    @param[out] dtheta = value of derivative of partition function with respect to temperature
!#>   returns the fluid/ice partition function theta and its derivative dtheta
!>    @details
!>calculates the fluid/ice partition function used for the \n
!>apparent heat capacity approach to phase change.\n
SUBROUTINE FTHETA_AD(tlocal, tlocal_ad, tliq, wmushy, theta, theta_ad, &
& dtheta, dtheta_ad, ismpl)
  use arrays

  USE ARRAYS_AD

  USE ICE
  IMPLICIT NONE
  INTEGER :: ismpl
  DOUBLE PRECISION :: tlocal, theta, dtheta, val, tliq, wmushy
  DOUBLE PRECISION :: tlocal_ad, theta_ad, dtheta_ad, val_ad
  INTRINSIC EXP
  DOUBLE PRECISION :: temporary_ad
  IF (tlocal .LT. tliq) THEN
    val = (tlocal-tliq)/wmushy
!         Theta=exp((-(T-Tf)/w)^2)
    theta = EXP(-(val*val))
!         dTheta=-2*(T-Tf)/w^2*Theta;
!       IF (theta.lt.liqmin) THEN
!         theta  =  liqmin
!         dtheta =  0.
!       END IF
    temporary_ad = -(2.d0*dtheta_ad/wmushy)
    theta_ad = theta_ad + val*temporary_ad
    val_ad = theta*temporary_ad - 2*val*EXP(-(val**2))*theta_ad
    tlocal_ad = tlocal_ad + val_ad/wmushy
  END IF
END SUBROUTINE FTHETA_AD

