! convert.f90
! module in which all the routines for variable conversions are held
! contains: SunPCFromHours

module Convert

implicit none

contains

!*******************************************************************************

function SunPCfromHours (Hours,Lat,XMonth)

real SunPCfromHours

real, intent(in) :: Hours	! sunshine hours per month (actual, not with any implicit factor)
real, intent(in) :: Lat		! in range -90 to +90
integer, intent(in) :: XMonth	! in range 1-12

real, parameter, dimension(12) :: Dys = [31.0,28.25,31.0,30.0,31.0,30.0,31.0,31.0,30.0,31.0,30.0,31.0]
real, parameter, dimension(12) :: Dec = [-21.07,-13.4,-2.42,9.38,18.77,22.95,21.1,13.53,2.62,-9.08,-18.6,-23.35]
real, parameter :: MissVal = -999.0
real, parameter :: DataMissVal = -9999.0
real, parameter :: Pi=3.14159265
real, parameter :: Rad=180.0/PI

real :: A1, H, Day

if (Hours.NE.DataMissVal.AND.Lat.NE.MissVal.AND.Lat.GE.-90.0.AND.Lat.LE.90.0) then
  A1=-tan(Lat/Rad)*tan(Dec(XMonth)/Rad)

  if (A1.GT.1.0) then
         H=0
  else
         if (A1.LT.-1.0) then
          H=Pi
         else
          H=acos(A1)
         end if
  end if
  
  Day=(24.0*H)/Pi

  if (Day.NE.0) then
         Day=Day+0.1+(abs(Lat)*0.002)
         if (Day.GT.24) Day=24
         SunPCfromHours=100.0*(Hours/Dys(XMonth))/Day
         if(SunPCfromHours.LT.  0.0) SunPCfromHours=DataMissVal
         if(SunPCfromHours.GT.100.0) SunPCfromHours=DataMissVal
  else
	 SunPCfromHours = DataMissVal
  end if
else
  SunPCfromHours = DataMissVal
end if

end function SunPCfromHours

!*******************************************************************************

end module Convert
