! This is part of the netCDF package.
! Copyright 2006 University Corporation for Atmospheric Research/Unidata.
! See COPYRIGHT file for conditions of use.
      
! This is a simple example which reads a small dummy array, from a
! netCDF data file created by the companion program simple_xy_wr.f90.
      
! This is intended to illustrate the use of the netCDF fortran 77
! API. This example program is part of the netCDF tutorial, which can
! be found at:
! http://www.unidata.ucar.edu/software/netcdf/docs/netcdf-tutorial
      
! Full documentation of the netCDF Fortran 90 API can be found at:
! http://www.unidata.ucar.edu/software/netcdf/docs/netcdf-f90

! $Id: simple_xy_rd.f90,v 1.7 2006/12/09 18:44:58 russ Exp $

! ----------------------
! M. Klose, 12 July 2018
! Read new annual source data obtained from Paul's Modis DeepBlue FoO and new HYDE 3.2.1 land use
! Program based on fbare_modis.f90 and read_paul_source_mdb2.f90
! ---------------------- 

program foo_lu
  use netcdf 
  implicit none
  include 'modelgrid.inc'
  include 'ginouxgrid_0.1.inc'  

! This is the name of the data file we will read. 
  character (len = *), parameter :: FILE_NAME = "../geodata/lai_modis/seamask/seamask0.1.nc"

! We are reading 2D data 
  integer, parameter :: NX = 3600, NY = 1800
  real :: source_nat1(NX,NY), source_nat2(NX,NY), source_ant1(NX,NY), source_ant2(NX,NY)
  real :: source_tot1(NX,NY), source_tot2(NX,NY)
  real :: source_interp_nat1(imi,jmi), source_interp_nat2(imi,jmi)
  real :: source_interp_ant1(imi,jmi), source_interp_ant2(imi,jmi)
  real :: source_interp_nat(imi,jmi), source_interp_ant(imi,jmi), source_interp_tot(imi,jmi)
  real :: lat(imi),lon(imi)
  real :: lats(NY), lons(NX), seamask(NX,NY)

! This will be the netCDF ID for the file and data variable.
  integer :: ncid, ncid1, ncid2, ncid3, src_a_varid, src_n_varid
  integer :: src_a_varid1, src_n_varid1, src_a_varid2, src_n_varid2
  integer :: lat_varid, lon_varid, rlat_varid, rlon_varid, seamask_varid
  integer :: lon_dimid, lat_dimid, south_north(jmi),west_east(imi)
! Loop indexes, and error handling.
  integer :: x, y, i, j
!
  real :: almd,aphd,tlm,tph,wb,sb,tph0,ctph0,stph0,dlm,dph
  real :: coh(3,imi,jmi),sm(imi,jmi),snow(imi,jmi)
  integer :: inh(4,imi,jmi),jnh(4,imi,jmi)

  logical :: global
!
  real, parameter :: dtr=3.1415926535897932384626433832795/180., rtd=1./dtr
!
  character :: interp_char
  character(2) :: src_char
!
  integer :: interp, src
!
  integer :: dimids(2)
!
  logical(kind=4):: run

  character(128):: infile, infile1, infile2, outfile

  integer(kind=4),dimension(1:3):: idat

  integer(kind=4),dimension(1:12):: month

  integer(kind=4),dimension(1:13):: jmonth

  integer(kind=4):: ihrst, iday, imon, iyear, jday, mon, jyear, year1, year2

  real(kind=4):: wght

  character(2):: sfx

  character(4):: yrx
  character(5):: luc
  character(20):: varname_n, varname_a
!
  character (len = *), parameter :: LAT_NAME = "latitude"
  character (len = *), parameter :: LON_NAME = "longitude"
  real :: rlat(imi,jmi), rlon(imi,jmi)
  character (len = *), parameter :: UNITS = "units"
  character (len = *), parameter :: LAT_UNITS = "degrees_north"
  character (len = *), parameter :: LON_UNITS = "degrees_east"
!
  integer, parameter :: ndays = 365 
  data month/31,28,31,30,31,30,31,31,30,31,30,31/
  integer :: useclim
  useclim = 0
!-----------------------------------------------------------------------
!
  global=im.gt.imi
!
!-----------------------------------------------------------------------
  
  call getarg(1, interp_char)
  read (interp_char, *) interp
  call getarg(2, src_char)
  read (src_char, *) src

print*, 'Input args: ', interp, src
!
!----------------------------------------------------------------------
      infile='../output/llspl.000'
      open(unit=1,file=infile,status='old',form='unformatted')
      read(1) run,idat,ihrst
      close(1)
!
      print*,'Cycle data read from ',infile
      print*,'Cycle ',idat,ihrst,' UTC'
! !-------------julian day of mid year ------------------------- 
      jyear = 183

!--------------julian day for current date------------------------------
      iday=idat(1)
      imon=idat(2)
      iyear=idat(3)
      jday=iday
      if(imon.gt.1) then
        do mon=2,imon
          jday=jday+month(mon-1)
        enddo
      endif
!-----------------------------------------------------------------------
      if (jday.le.jyear) then 
         year1 = iyear-1
         year2 = iyear
         wght = float((ndays-jyear)+jday)/float(ndays)
      else 
         year1 = iyear 
         year2 = iyear+1 
         wght = float(jday-jyear)/float(ndays)
      endif 
      print*, 'Check lu weights:', jday, year1, year2, wght
!-------------read in vegfrac data for year1 and year2 or from climatology-------------------
      print*, iyear
! decide if climatology or actual year      
      if (src.ge.7.and.src.le.10.and.year1.ge.2003.and.year2.ge.2003.and.year1.le.2016.and.year2.le.2016) then !actual year
         write(yrx,'(i4.4)') year1
         infile1 = '../geodata/dust_sources/fooMDB2_luHYDE321/foo_lu_'//yrx//'.nc'
         print*,'read foo/lu data for month/year ', year1 
! 
         write(yrx,'(i4.4)') year2
         infile2 = '../geodata/dust_sources/fooMDB2_luHYDE321/foo_lu_'//yrx//'.nc'
!
         print*,'read foo/lu data for month/year', year2
      else     ! use climatology
       useclim = 1
       infile1 = '../geodata/dust_sources/fooMDB2_luHYDE321/foo_lu_avg_2003_2016.nc'
       print*,'read foo/lu data for year ', iyear, ' from climatology'
      endif

! Open the file. NF90_NOWRITE tells netCDF we want read-only access to
! the file.
       call check( nf90_open(infile1, NF90_NOWRITE, ncid1) )
       if (useclim.eq.0) then 
          call check( nf90_open(infile2, NF90_NOWRITE, ncid2) )
       endif 
       call check( nf90_open(FILE_NAME, NF90_NOWRITE, ncid3) )   !sea mask at 0.1 deg
!
! Get the varids of the latitude and longitude coordinate variables.
       call check( nf90_inq_varid(ncid1, "lat", lat_varid) )
       call check( nf90_inq_varid(ncid1, "lon", lon_varid) )
!
! Read the latitude and longitude data.
       call check( nf90_get_var(ncid1, lat_varid, lats) )
       call check( nf90_get_var(ncid1, lon_varid, lons) )

!
! Get the varid of the data variable, based on its name.
       if ( src.eq.8 .or. src.eq.12 .or. src.eq.7 .or. src.eq.11)  then   ! SRC 7 and 11 don't use tagging so use whatever combination 
          varname_n = 'foo_nat_cp'
          varname_a = 'foo_ant_cp'
          luc = 'cp'
       elseif ( src.eq.9 .or. src.eq.13 ) then
          varname_n = 'foo_nat_cprc'
          varname_a = 'foo_ant_cprc'
          luc = 'cprc'
       elseif ( src.eq.10 .or. src.eq.14 ) then
          varname_n = 'foo_nat_cprcr'
          varname_a = 'foo_ant_cprcr'
          luc = 'cprcr'
       endif
       call check( nf90_inq_varid(ncid1, trim(varname_a), src_a_varid1) ) ! year 1, nat
       call check( nf90_inq_varid(ncid1, trim(varname_n), src_n_varid1) ) ! year 1, ant
       if (useclim.eq.0) then 
          call check( nf90_inq_varid(ncid2, trim(varname_a), src_a_varid2) ) ! year 2, nat
          call check( nf90_inq_varid(ncid2, trim(varname_n), src_n_varid2) ) ! year 2, ant
       endif 
       call check( nf90_inq_varid(ncid3, "seamask", seamask_varid) )
!
! Read the data.
!  call check( nf90_get_var(ncid, varid, source, start=(/1,1/), count=(/y,x/)) )
       call check( nf90_get_var(ncid1, src_n_varid1, source_nat1) )
       call check( nf90_get_var(ncid1, src_a_varid1, source_ant1) )
! Data is in percent. Convert to fraction. 
       source_nat1 = source_nat1/100. 
       source_ant1 = source_ant1/100. 
       source_tot1 = source_nat1 + source_ant1
       if (useclim.eq.0) then 
          call check( nf90_get_var(ncid2, src_n_varid2, source_nat2) )
          call check( nf90_get_var(ncid2, src_a_varid2, source_ant2) )
          source_nat2 = source_nat2/100. 
          source_ant2 = source_ant2/100. 
          source_tot2 = source_nat2 + source_ant2
       endif
       call check( nf90_get_var(ncid3, seamask_varid, seamask) )
!
! Check the data, mask sea
       do x = 1, NX
         do y = 1, NY
           if (seamask(x,y).gt.0.) then
             source_nat1(x,y) = 0.
             source_ant1(x,y) = 0.
             source_tot1(x,y) = 0.
             if (useclim.eq.0) then 
                source_nat2(x,y) = 0.
                source_ant2(x,y) = 0.
                source_tot2(x,y) = 0.
             endif 
           endif
         end do
       end do
!
! Close the file, freeing all resources.
       call check( nf90_close(ncid1) )
       print *,"*** SUCCESS reading file ", infile1, "! "
       if (useclim.eq.0) then 
          call check( nf90_close(ncid2) )
          print *,"*** SUCCESS reading file ", infile2, "! "
       endif
!
!-----------------------------------------------------------------------
!***  umo domain geometry
!-----------------------------------------------------------------------
!
      wb=wbd*dtr
      sb=sbd*dtr
      tph0=tph0d*dtr
      ctph0=cos(tph0)
      stph0=sin(tph0)
      dlm=dlmd*dtr
      dph=dphd*dtr
!
      call preina (global,wb,sb,tlm0d,ctph0,stph0,dlm,dph,imi,jmi,coh,inh,jnh)
!
!Selects interpolation method from keyboard
!      
      if ( interp == 0) then !bilinear interpolation (for high resolution, about 0.1x0.1 deg or higher)
!
         call bilinb(coh,inh,jnh,imll,jmll,imi,jmi,source_nat1,source_interp_nat1)
         call bilinb(coh,inh,jnh,imll,jmll,imi,jmi,source_ant1,source_interp_ant1)
         if (useclim.eq.0) then 
            call bilinb(coh,inh,jnh,imll,jmll,imi,jmi,source_nat2,source_interp_nat2)
            call bilinb(coh,inh,jnh,imll,jmll,imi,jmi,source_ant2,source_interp_ant2)
         endif
!
      else  ! averaging inside each grid cell (for coarse resolutions > 0.1x0.1 deg)
!
         call average_gridcell(NX,NY,lons,lats,source_tot1,source_nat1,source_interp_nat1)
         call average_gridcell(NX,NY,lons,lats,source_tot1,source_ant1,source_interp_ant1)
         if (useclim.eq.0) then 
            call average_gridcell(NX,NY,lons,lats,source_tot2,source_nat2,source_interp_nat2)
            call average_gridcell(NX,NY,lons,lats,source_tot2,source_ant2,source_interp_ant2)
         endif
!
      endif  !interp
!
      open(unit=3,file='../output/seamask',status='unknown',form='unformatted')
      read(3) sm
      close(3)
!
      do i=1,imi
      do j=1,jmi
!
       if(sm(i,j).gt.0..or.source_interp_nat1(i,j).lt.0.) source_interp_nat1(i,j)=0.
       if(sm(i,j).gt.0..or.source_interp_ant1(i,j).lt.0.) source_interp_ant1(i,j)=0.
       if (useclim.eq.0) then 
          if(sm(i,j).gt.0..or.source_interp_nat2(i,j).lt.0.) source_interp_nat2(i,j)=0.
          if(sm(i,j).gt.0..or.source_interp_ant2(i,j).lt.0.) source_interp_ant2(i,j)=0.
       endif
! 
      enddo
      enddo      
!
!----------------------------------------------------------------------------------------
!Create netcdf to check everything is correct
!
      tph=sb-dph
      do j=1,jmi
        tph=tph+dph
        tlm=wb-dlm
      do i=1,imi
        tlm=tlm+dlm
!
!-----------------------------------------------------------------------
!***  tll to ll conversion
!-----------------------------------------------------------------------
!
       if(.not.global) then
         call rtll(tlm,tph,tlm0d,ctph0,stph0,almd,aphd)
       else
         almd=tlm*rtd
         aphd=tph*rtd
       endif
!
        rlat(i,j)=aphd
        rlon(i,j)=almd
!
     enddo
     enddo
!
    do i=1,jmi
      south_north(i)=i
    enddo
!
    do i=1,imi
      west_east(i)=i
    enddo
!
!--------------do the time interpolation--------------------------------
    if (useclim.eq.0) then 
!        do i=1,imi
!         do j=1,jmi
!           fbare_interp(i,j)=(fbare2_interp(i,j)-fbare1_interp(i,j))*wght &
!                             +fbare1_interp(i,j)
!         enddo
!       enddo
       source_interp_nat = source_interp_nat1 + (source_interp_nat2 - source_interp_nat1)*wght
       source_interp_ant = source_interp_ant1 + (source_interp_ant2 - source_interp_ant1)*wght
    else
       source_interp_nat = source_interp_nat1
       source_interp_ant = source_interp_ant1
    endif 


      open(unit=1,file='../output/source_new_nat',status='unknown',form='unformatted')
      write(1)source_interp_nat
      close(1)

      open(unit=1,file='../output/source_new_ant',status='unknown',form='unformatted')
      write(1)source_interp_ant
      close(1)
!
!----------------------------------------------------------------------------------------



!
  call check( nf90_create("foo_lu_"//trim(luc)//"_src.nc", NF90_CLOBBER, ncid) )
!
! Define the dimensions. NetCDF will hand back an ID for each. 
  call check( nf90_def_dim(ncid, "lon", imi, lon_dimid) )
  call check( nf90_def_dim(ncid, "lat", jmi, lat_dimid) )
!
! The dimids array is used to pass the IDs of the dimensions of
! the variables. Note that in fortran arrays are stored in
! column-major format.
!
  dimids =  (/ lon_dimid, lat_dimid /)
!
! Define the variable. The type of the variable in this case is
! NF90_INT (4-byte integer).
!
  call check( nf90_def_var(ncid, "src_nat", NF90_REAL, dimids, src_n_varid) )
  call check( nf90_def_var(ncid, "src_ant", NF90_REAL, dimids, src_a_varid) )
  call check( nf90_put_att(ncid, src_n_varid, "standard_name", "foo source natural") )
  call check( nf90_put_att(ncid, src_a_varid, "standard_name", "foo source anthropogenic") )
  call check( nf90_def_var(ncid, "lat", NF90_REAL, dimids, rlat_varid) )
  call check( nf90_def_var(ncid, "lon", NF90_REAL, dimids, rlon_varid) )
  call check( nf90_put_att(ncid, rlat_varid, "units", "degrees_north") )
  call check( nf90_put_att(ncid, rlat_varid, "standard_name", "latitude") )
  call check( nf90_put_att(ncid, rlon_varid, "units", "degrees_east") )
  call check( nf90_put_att(ncid, rlon_varid, "standard_name", "longitude") )
  call check( nf90_enddef(ncid) )
!
! Write the pretend data to the file. Although netCDF supports
! reading and writing subsets of data, in this case we write all the
! data in one operation.
!
  call check( nf90_put_var(ncid, src_n_varid, source_interp_nat) )
  call check( nf90_put_var(ncid, src_a_varid, source_interp_ant) )
  call check( nf90_put_var(ncid, rlat_varid, rlat) )
  call check( nf90_put_var(ncid, rlon_varid, rlon) )
!
! Close the file. This frees up any internal netCDF resources
! associated with the file, and flushes any buffers.
!
  call check( nf90_close(ncid) )
!
  print *, "*** SUCCESS writing FoO LU sources! "
!
!
!Subroutines
!
contains
  subroutine check(status)
    integer, intent ( in) :: status
    
    if(status /= nf90_noerr) then 
      print *, trim(nf90_strerror(status))
      stop "Stopped"
    end if
  end subroutine check


  subroutine preina (global,wb,sb,tlm0d,ctph0,stph0,dlm,dph,imi,jmi,coh,inh,jnh)
!
!-----------------------------------------------------------------------
      include 'ginouxgrid_0.1.inc'
!-----------------------------------------------------------------------
!
      real(kind=4),parameter ::  dtr=3.1415926535897932384626433832795/180.,rtd=1./dtr
!
!-----------------------------------------------------------------------
!
      logical :: global
      integer :: imi, jmi
      real ::  x,y,coh(3,imi,jmi),almd,aphd,tlm,tph,wb,sb,tlm0d,ctph0,stph0,dlm,dph
      integer :: inh(4,imi,jmi),jnh(4,imi,jmi),indec,jndec
!
!-----------------------------------------------------------------------
!***  entry to the umo i,j loop
!***  neighbour avn index identification (avn data defined in ll system)
!-----------------------------------------------------------------------
!-----------------------------------------------------------------------
!
      tph=sb-dph
              do j=1,jmi
          tph=tph+dph
          tlm=wb-dlm
          do i=1,imi
      tlm=tlm+dlm
!
!-----------------------------------------------------------------------
!***  tll to ll conversion
!-----------------------------------------------------------------------
!
      if(.not.global) then
        call rtll(tlm,tph,tlm0d,ctph0,stph0,almd,aphd)
      else
        almd=tlm*rtd
        aphd=tph*rtd
      endif
!
!-----------------------------------------------------------------------
!-------------conversion from -180,180 range to 0,360 range-------------
!-----------------------------------------------------------------------
!
!      if(almd.lt.0.) almd=360.+almd    NO NEED HERE
!
!
!-----------------------------------------------------------------------
!-------------check if model point is out of llgrid domain--------------
!-----------------------------------------------------------------------
!
      if(almd.lt.bowest-delon/2      .or.  &
         almd.gt.boeast+delon/2+0.1  ) then
!     &   almd.gt.boeast+delon.or.
!     &   aphd.lt.bosout      .or.
!     &   aphd.gt.bonort          ) then
        print*,'h point i=',i,' j=',j,almd,aphd &
     ,' is out of the llgrid domain SFC2'
        print*,'program will stop'
        stop
      endif
!
!----------------------------------------------------------------------
!
      if(aphd.ge.bosout.or.  &
        aphd.le.bonort) then

      x=almd-bowest
      y=aphd-bosout
!
      indec=x/delon+1
      jndec=y/delat+1
!
      if(indec.eq.0) indec=imll
      if(indec.gt.imll) indec=1
      if(jndec.eq.0) jndec=1
      if(jndec.ge.jmll) jndec=jmll-1
!
      x=x-(indec-1)*delon
      y=y-(jndec-1)*delat
!-----------------------------------------------------------------------
      coh(1,i,j)=x/delon
      coh(2,i,j)=y/delat
      coh(3,i,j)=coh(1,i,j)*coh(2,i,j)
!-----------------------------------------------------------------------
!-----------------------------------------------------------------------
      inh(1,i,j)=indec
      inh(3,i,j)=indec
          if(indec.lt.imll) then
      inh(2,i,j)=indec+1
      inh(4,i,j)=indec+1
          else
      inh(2,i,j)=1
      inh(4,i,j)=1
          endif
!
      jnh(1,i,j)=jndec
      jnh(2,i,j)=jndec
      jnh(3,i,j)=jndec+1
      jnh(4,i,j)=jndec+1
     else

      coh(1,i,j)=0.
      coh(2,i,j)=0.
      coh(3,i,j)=coh(1,i,j)*coh(2,i,j)
!-----------------------------------------------------------------------
!-----------------------------------------------------------------------
      inh(1,i,j)=1
      inh(3,i,j)=1
          if(indec.lt.imll) then
      inh(2,i,j)=1
      inh(4,i,j)=1
          else
      inh(2,i,j)=1
      inh(4,i,j)=1
          endif
!
      jnh(1,i,j)=1
      jnh(2,i,j)=1
      jnh(3,i,j)=1
      jnh(4,i,j)=1
!-----------------------------------------------------------------------

      endif

          enddo
              enddo
!-----------------------------------------------------------------------
      end subroutine
!-----------------------------------------------------------------------

      subroutine rtll(tlm,tph,tlm0d,ctph0,stph0,almd,aphd)
!     ****************************************************************
!     *                                                              *
!     *  programer: z. janjic, shmz, feb. 1981                       *
!     *  ammended:  z. janjic, ncep, jan. 1996                       *
!     *                                                              *
!     *  transformation from rotated lat-lon to lat-lon coordinates  *
!     ****************************************************************
!     ****************************************************************
!     *  tlm   - transformed longitude, rad.                         *
!     *  tph   - transformed latitude, rad.                          *
!     *  tlm0d - the angle of rotation of the transformed lat-lon    *
!     *          system in the longitudinal direction, degs          *
!     *  ctph0 - cos(tph0), tph0 is the angle of rotation of the     *
!     *          transformed lat-lon systemn in the latitudinal      *
!     *          direction, precomputed                              *
!     *  stph0 - sin(tph0), tph0 is the angle of rotation of the     *
!     *          transformed lat-lon systemn in the latitudinal      *
!     *          direction, precomputed                              *
!     *  almd  - geographical longitude, degs, range -180.,180       *
!     *  aphd  - geographical latitude,  degs, range - 90., 90.,     *
!     *          poles are singular                                  *
!     ****************************************************************
!
!-----------------------------------------------------------------------
!
      real, parameter :: dtr=3.1415926535897932384626433832795/180.
      real :: almd,aphd,tph,tlm,ctph0,stph0,tlm0d,stlm,ctlm,stph,ctph
      real :: sph,aph,anum,denom,relm

!
      stlm=sin(tlm)
      ctlm=cos(tlm)
      stph=sin(tph)
      ctph=cos(tph)
!
      sph=ctph0*stph+stph0*ctph*ctlm
      sph=min(sph,1.)
      sph=max(sph,-1.)
      aph=asin(sph)
      aphd=aph/dtr
      anum=ctph*stlm
      denom=(ctlm*ctph-stph0*sph)/ctph0
      relm=atan2(anum,denom)
      almd=relm/dtr+tlm0d
!
      if(almd.gt. 180.)    almd=almd-360.
      if(almd.lt.-180.)    almd=almd+360.
!
!-----------------------------------------------------------------------
!
      end subroutine

      subroutine bilinb(cob,inb,jnb,imll,jmll,imi,jmi,ww,wfb)
!
!-----------------------------------------------------------------------
!
      real :: cob(3,imi,jmi)
      integer :: inb(4,imi,jmi),jnb(4,imi,jmi),imll,jmll,imi,jmi
      real :: ww(imll,jmll),wfb(imi,jmi)
      integer :: i00,i10,i01,i11,j00,j10,j01,j11
      real :: p,q,pq,z
!
!-----------------------------------------------------------------------
              do j=1,jmi
          do i=1,imi
!
      i00=inb(1,i,j)
      i10=inb(2,i,j)
      i01=inb(3,i,j)
      i11=inb(4,i,j)
!
      j00=jnb(1,i,j)
      j10=jnb(2,i,j)
      j01=jnb(3,i,j)
      j11=jnb(4,i,j)
!
      p=cob(1,i,j)
      q=cob(2,i,j)
      pq=cob(3,i,j)
!
      z=ww(i00,j00)  &
      +p*(ww(i10,j10)-ww(i00,j00))  &
      +q*(ww(i01,j01)-ww(i00,j00))  &
      +pq*(ww(i00,j00)-ww(i10,j10)-ww(i01,j01)+ww(i11,j11))
!
      wfb(i,j)=z
!
          enddo
              enddo
!-----------------------------------------------------------------------
!
      end subroutine

      subroutine average_gridcell(ix,jy,lon,lat,input_tot,input,output)      

      include 'modelgrid.inc'
!-----------------------------------------------------------------------
      integer,parameter :: lclass=1                    ! total, natural and anthropogenic
      real,parameter :: pi=3.1415926535897932384626433832795, dtr=pi/180.,scalex=0.50,scaley=0.50
      integer :: i,i1,i2,iavg,idata,ie,is,j,j1,j2,jdata,je,js,l,ix,jy
      real :: ctph,ctph0,dlm,dph,edlm,edph,elmh,elml,ephh,ephl,rctph &
                    ,rdlm,rdph,sb,stph0,tlm,tlm0,tph,tph0,wb,xdata,ydata,rr
      integer :: kount(lclass,imi,jmi)
      real :: output(imi,jmi)
      real :: input(ix,jy),input_tot(ix,jy)
      real :: lon(ix)
      real :: lat(jy)
!-----------------------------------------------------------------------
      tlm0=tlm0d*dtr
      tph0=tph0d*dtr
      stph0=sin(tph0)
      ctph0=cos(tph0)
!
      wb=wbd*dtr
      sb=sbd*dtr
      dlm=dlmd*dtr
      dph=dphd*dtr
!
      rdlm=1./dlm
      rdph=1./dph
!
      do j=1,jmi
        do i=1,imi
          output(i,j)=0.
          do l=1,lclass
          kount(l,i,j)=0
          enddo
        enddo
      enddo
!-----------------------------------------------------------------------
          do jdata=1,jy
!
            do idata=1,ix

!-----------------------------------------------------------------------
              if(im.gt.imi) then ! global domain
!-----------------------------------------------------------------------
                tlm=lon(idata)*dtr
                tph=lat(jdata)*dtr
!
                ctph=abs(cos(tph))
                if(ctph.gt.0.00001) then
                  rctph=max(dph/(ctph*dlm),1.)
                else
                  rctph=999999.
                endif
!
                edlm=min(dlm*rctph*scalex,pi)
                elml=tlm-edlm
                elmh=tlm+edlm
!
                if(elml.lt.-pi) elml=elml+pi+pi
                if(elmh.gt. pi) elmh=elmh-pi-pi
!
                is=int((elml-wb)*rdlm+0.99999)+1
                ie=int((elmh-wb)*rdlm        )+1
!
                if(is.lt.1  ) is=1
                if(ie.lt.1  ) ie=1
                if(is.gt.imi) is=imi
                if(ie.gt.imi) ie=imi
!
                edph=dph*scaley
                ephl=tph-edph
                ephh=tph+edph
!
                if(ephl.lt. sb) ephl= sb
                if(ephh.gt.-sb) ephh=-sb

                js=int((ephl-sb)*rdph+0.99999)+1
                je=int((ephh-sb)*rdph+0.00001)+1
!
                if(js.lt.1  ) js=1
                if(je.lt.1  ) je=1
                if(js.gt.jmi) js=jmi
                if(je.gt.jmi) je=jmi
!
                do j=js,je
                  if(is.gt.ie) then
                    do i=is,imi
                     if (input_tot(idata, jdata).gt.0. ) then
                         kount(1,i,j)=kount(1,i,j)+1
                         output(i,j)=output(i,j)+input(idata, jdata)
                     endif
                    enddo
                    do i=1,ie
                     if (input_tot(idata, jdata).gt.0. ) then
                         kount(1,i,j)=kount(1,i,j)+1
                         output(i,j)=output(i,j)+input(idata, jdata)
                     endif
                    enddo
                  else
                    do i=is,ie
                     if (input_tot(idata, jdata).gt.0. ) then
                         kount(1,i,j)=kount(1,i,j)+1
                         output(i,j)=output(i,j)+input(idata, jdata)
                     endif
                    enddo
                  endif
                enddo
!-----------------------------------------------------------------------
              else ! regional domain
                call tll(lon(idata),lat(jdata),tlm0d,dtr,ctph0,stph0,tlm,tph)
!
                ctph=cos(tph)
                rctph=max(dph/(ctph*dlm),1.)
!
                edlm=dlm*rctph*scalex
                elml=tlm-edlm
                elmh=tlm+edlm
!
                is=int((elml-wb)*rdlm+0.99999)+1
                ie=int((elmh-wb)*rdlm        )+1
!
                edph=dph*scaley
                ephl=tph-edph
                ephh=tph+edph
!
                js=int((ephl-sb)*rdph+0.99999)+1
                je=int((ephh-sb)*rdph+0.00001)+1
!
                if(ie.ge.1.and.is.le.imi.and. &
                   je.ge.1.and.js.le.jmi) then ! data point inside
!
                  if(is.lt.1  ) is=1
                  if(ie.gt.imi) ie=imi
                  if(js.lt.1  ) js=1
                  if(je.gt.jmi) je=jmi

                  do j=js,je
                    do i=is,ie
                     if (input_tot(idata, jdata).gt.0. ) then
                         kount(1,i,j)=kount(1,i,j)+1
                         output(i,j)=output(i,j)+input(idata, jdata)
                     endif
                    enddo
                  enddo
                endif
!-----------------------------------------------------------------------
              endif ! end of global/regional branching
!-----------------------------------------------------------------------
            enddo
          enddo
!-----------------------------------------------------------------------
      if(im.gt.imi) then
        do j=1,jmi
          do l=1,lclass
            iavg=(kount(l,1,j)+kount(l,imi,j))/2
            kount(l,1  ,j)=iavg
            kount(l,imi,j)=iavg
          enddo
        enddo
      endif
!
      do j=1,jmi
        do i=1,imi
           if(kount(1,i,j).gt.0)then
           rr=real(kount(1,i,j))
           output(i,j)=output(i,j)/rr
           endif
        enddo
      enddo

      end subroutine

end program foo_lu

      subroutine tll(almd,aphd,tlm0d,dtr,ctph0,stph0,tlm,tph)
!     ****************************************************************
!     *                                                              *
!     *  programer: z. janjic, shmz, feb. 1981                       *
!     *  ammended:  z. janjic, ncep, jan. 1996                       *
!     *                                                              *
!     *  transformation from lat-lon to rotated lat-lon coordinates  *
!     ****************************************************************
!     ****************************************************************
!     *  tlm   - transformed longitude, rad.                         *
!     *  tph   - transformed latitude, rad.                          *
!     *  tlm0d - the angle of rotation of the transformed lat-lon    *
!     *          system in the longitudinal direction, degs          *
!     *  ctph0 - cos(tph0), tph0 is the angle of rotation of the     *
!     *          transformed lat-lon systemn in the latitudinal      *
!     *          direction, precomputed                              *
!     *  stph0 - sin(tph0), tph0 is the angle of rotation of the     *
!     *          transformed lat-lon systemn in the latitudinal      *
!     *          direction, precomputed                              *
!     *  almd  - geographical longitude, degs, range -180.,180       *
!     *  aphd  - geographical latitude,  degs, range - 90., 90.,     *
!     *          poles are singular                                  *
!     ****************************************************************
!
      relm=(almd-tlm0d)*dtr
      srlm=sin(relm)
      crlm=cos(relm)
      aph=aphd*dtr
      sph=sin(aph)
      cph=cos(aph)
      cc=cph*crlm
      anum=cph*srlm
      denom=ctph0*cc+stph0*sph
!
      tlm=atan2(anum,denom)
      tph=asin(ctph0*sph-stph0*cc)
!
      return
      endsubroutine tll
!-----------------------------------------------------------------------
