!! Diagnostics: low / mid / high cloud fraction
!! Code originally from MM5toGrADS

MODULE module_calc_clfr

  CONTAINS
  SUBROUTINE calc_clfr(SCR4, cname, cdesc, cunits, RH_in)

  USE module_model_basics

  IMPLICIT NONE

  !Arguments
  real, allocatable, dimension(:,:,:,:)                          :: SCR4
  real, pointer, dimension(:,:,:)                                :: RH_in
  character (len=128)                                            :: cname, cdesc, cunits

  ! Local variables
  integer                                                        :: i, j, k, kclo, kcmi, kchi

  
  SCR4 = 0.0

   DO j = 1,south_north_dim   
     DO i = 1,west_east_dim
       DO k = 1,bottom_top_dim
          IF ( PRES(i,j,k) .gt. 97000. ) kclo=k
          IF ( PRES(i,j,k) .gt. 80000. ) kcmi=k
          IF ( PRES(i,j,k) .gt. 45000. ) kchi=k
       END DO
       DO k = 1,bottom_top_dim
          IF ( k .ge. kclo .AND. k .lt. kcmi ) &               !! low cloud
               SCR4(i,j,1,1) = AMAX1(RH_in(i,j,k),SCR4(i,j,1,1))
          IF ( k .ge. kcmi .AND. k .lt. kchi ) &               !! mid cloud
               SCR4(i,j,1,2) = AMAX1(RH_in(i,j,k),SCR4(i,j,1,2))
          IF ( k .ge. kchi ) &                                 !! high cloud
               SCR4(i,j,1,3) = AMAX1(RH_in(i,j,k),SCR4(i,j,1,3))
       END DO

       SCR4(i,j,1,1)=4.0*SCR4(i,j,1,1)/100.-3.0
       SCR4(i,j,1,2)=4.0*SCR4(i,j,1,2)/100.-3.0
       SCR4(i,j,1,3)=2.5*SCR4(i,j,1,3)/100.-1.5

       SCR4(i,j,1,1)=amin1(SCR4(i,j,1,1),1.0)
       SCR4(i,j,1,1)=amax1(SCR4(i,j,1,1),0.0)
       SCR4(i,j,1,2)=amin1(SCR4(i,j,1,2),1.0)
       SCR4(i,j,1,2)=amax1(SCR4(i,j,1,2),0.0)
       SCR4(i,j,1,3)=amin1(SCR4(i,j,1,3),1.0)
       SCR4(i,j,1,3)=amax1(SCR4(i,j,1,3),0.0)

     END DO 
   END DO 


  cname    = " "
  cdesc    = " "
  cunits   = "%"
  

  END SUBROUTINE calc_clfr

END MODULE module_calc_clfr
