! 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 $

program fbare_modis
  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 :: fbare1(NX,NY), fbare2(NX,NY), seamask(NX,NY), fbare1_interp(imi,jmi)
  real :: fbare2_interp(imi,jmi),fbare_interp(imi,jmi),lat(imi),lon(imi)
  real :: lats(NY), lons(NX)

! This will be the netCDF ID for the file and data variable.
  integer :: ncid, ncid1, ncid2, ncid3, fbare_varid, fbare_varid1, fbare_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,clim_char
!
  integer :: interp,clim
!
  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,mnth1,mnth2,mon

  real(kind=4):: wght

  character(2):: sfx

  character(4):: yrx
!
  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"
!
  data month/31,28,31,30,31,30,31,31,30,31,30,31/
!-----------------------------------------------------------------------
!
  global=im.gt.imi
!
!-----------------------------------------------------------------------
  
  call getarg(1, interp_char)
  read (interp_char, *) interp
  call getarg(2, clim_char)
  read (clim_char, *) clim
!
!----------------------------------------------------------------------
      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 for 15th of each month-------------------------
      jmonth(1)=15
      do imon=2,13
        jmonth(imon)=0
        do mon=1,imon-1
          jmonth(imon)=jmonth(imon)+month(mon)
        enddo
        jmonth(imon)=jmonth(imon)+15
      enddo
!--------------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.lt.15) jday=365+jday
!-----------------------------------------------------------------------
      do imon=1,12
        if(jday.ge.jmonth(imon).and.jday.lt.jmonth(imon+1)) then
          mnth1=imon
          mnth2=imon+1
          wght=float(jday-jmonth(imon)) &
              /float(jmonth(imon+1)-jmonth(imon))
          go to 100
        endif
      enddo
 100  continue
      if(mnth2.gt.12) mnth2=1
!-------------read in vegfrac data for mnth1 and mnth2-------------------
      if (iyear.lt.2000.or.iyear.gt.2015.or.(iyear.eq.2015.and.mnth2.eq.1.and.jday.le.365) ) then 
         clim = 2   ! data currently not available, use climatology
         print*, 'Data not available, use climatology'
      endif 
!decide if climatology or actual year      
      if(clim.eq.1) then !actual year
!
       if(mnth2.eq.1.and.jday.gt.365) then
!
         write(yrx,'(i4.4)') iyear-1
         write(sfx,'(i2.2)') mnth1      
!
         if(iyear-1.ge.2000)then   !If year < 2000 use december climatology
            infile1= &
            '../geodata/lai_modis/new_version_C5b/'//yrx//'/LAI_FBARE_C5b_0.1x0.1_'//yrx//'_'//sfx//'.nc'
            print*,'fbare modis read data for month/year',mnth1,iyear-1 
         else
            infile1= &
            '../geodata/lai_modis/new_version_C5b/CLIM/LAI_FBARE_C5b_0.1x0.1_CLIM_'//sfx//'.nc'
            print*,'fbare modis read data for month/year',mnth1,'from climatology'
         endif
!
         write(yrx,'(i4.4)') iyear  
         write(sfx,'(i2.2)') mnth2
         infile2= &
         '../geodata/lai_modis/new_version_C5b/'//yrx//'/LAI_FBARE_C5b_0.1x0.1_'//yrx//'_'//sfx//'.nc'
!
         print*,'fbare modis read data for month/year',mnth2,iyear
!
       elseif (mnth1.eq.12 .and. mnth2.eq.1 .and. jday.le.365) then
!
         write(yrx,'(i4.4)') iyear
         write(sfx,'(i2.2)') mnth1
         infile1= &
            '../geodata/lai_modis/new_version_C5b/'//yrx//'/LAI_FBARE_C5b_0.1x0.1_'//yrx//'_'//sfx//'.nc'
         write(yrx,'(i4.4)') iyear+1
         write(sfx,'(i2.2)') mnth2
         infile2= &
            '../geodata/lai_modis/new_version_C5b/'//yrx//'/LAI_FBARE_C5b_0.1x0.1_'//yrx//'_'//sfx//'.nc'
!
         print*,'fbare modis read data for month/year',mnth1,iyear
         print*,'fbare modis read data for month/year',mnth2,iyear+1
! 
       else
!
         write(yrx,'(i4.4)') iyear
         write(sfx,'(i2.2)') mnth1
         infile1= &
            '../geodata/lai_modis/new_version_C5b/'//yrx//'/LAI_FBARE_C5b_0.1x0.1_'//yrx//'_'//sfx//'.nc'
         write(yrx,'(i4.4)') iyear
         write(sfx,'(i2.2)') mnth2
         infile2= &
            '../geodata/lai_modis/new_version_C5b/'//yrx//'/LAI_FBARE_C5b_0.1x0.1_'//yrx//'_'//sfx//'.nc'
!
         print*,'fbare modis read data for month/year',mnth1,iyear
         print*,'fbare modis read data for month/year',mnth2,iyear
!
       endif

      else     !climatology
!
         write(sfx,'(i2.2)') mnth1
         infile1= &
            '../geodata/lai_modis/new_version_C5b/CLIM/LAI_FBARE_C5b_0.1x0.1_CLIM_'//sfx//'.nc'
         write(sfx,'(i2.2)') mnth2
         infile2= &
            '../geodata/lai_modis/new_version_C5b/CLIM/LAI_FBARE_C5b_0.1x0.1_CLIM_'//sfx//'.nc'
!
         print*,'fbare modis read data for month/year',mnth1,'from climatology'
         print*,'fbare modis read data for month/year',mnth2,'from climatology'

!
      endif
!      open(unit=2,file=infile,status='unknown',form='formatted')
!      read(2,1002) ifrc
!      close(2)
!      print*,'vegfrac read data for month',mnth1
!
!      open(unit=2,file=infile,status='unknown',form='formatted')
!      read(2,1002) ifrcp
!      close(2)
!      print*,'vegfracprog read data for month',mnth2

! Open the file. NF90_NOWRITE tells netCDF we want read-only access to
! the file.
       call check( nf90_open(infile1, NF90_NOWRITE, ncid1) )
       call check( nf90_open(infile2, NF90_NOWRITE, ncid2) )
       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.
       call check( nf90_inq_varid(ncid1, "FBARE", fbare_varid1) )
       call check( nf90_inq_varid(ncid2, "FBARE", fbare_varid2) )
       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, fbare_varid1, fbare1) )
       call check( nf90_get_var(ncid2, fbare_varid2, fbare2) )
       call check( nf90_get_var(ncid3, seamask_varid, seamask) )
!
! Check the data, mask sea, and set to 0 below 60S and above 60N
       do x = 1, NX
         do y = 1, NY
           if (fbare1(x, y).le.0..or.seamask(x,y).gt.0..or.y.le.300.or.y.ge.1450) then
              fbare1(x, y) = 0.
           endif
           if (fbare2(x, y).le.0..or.seamask(x,y).gt.0..or.y.le.300.or.y.ge.1450) then
              fbare2(x, y) = 0.
           endif
! Northern Hemisphere - correct for months Dec, Jan, Feb
           if(mnth1.eq.11.and.mnth2.eq.12.and.y.ge.1372) fbare2(x,y)=fbare1(x,y)    !for nov/dec use nov above 47.25 N
           if(mnth1.eq.12.and.mnth2.eq.1.and.y.ge.1372) then 
              fbare2(x,y)=0.               !for dec/jan set to zero above 47.25 N
              fbare1(x,y)=0.   
           endif 
           if(mnth1.eq.1.and.mnth2.eq.2.and.y.ge.1372.and.y.lt.1425) fbare1(x,y)=fbare2(x,y)   !for jan/feb use feb between 47.25 N and 52.50 N and set both to zero above  
           if(mnth1.eq.1.and.mnth2.eq.2.and.y.ge.1425) then                                    !for jan/feb use feb between 47.25 N and 52.50 N and set both to zero above  
              fbare1(x,y)=0.
              fbare2(x,y)=0.                     
           endif 
           if(mnth1.eq.2.and.mnth2.eq.3.and.y.ge.1425) fbare1(x,y)=fbare2(x,y)        !for feb/mar use mar above 52.50 N
         end do
       end do
!
! Close the file, freeing all resources.
       call check( nf90_close(ncid1) )
       call check( nf90_close(ncid2) )
!
       print *,"*** SUCCESS reading example file ", infile1, "! "
       print *,"*** SUCCESS reading example file ", infile2, "! "
!
!
!
!-----------------------------------------------------------------------
!***  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,fbare1,fbare1_interp)
      call bilinb(coh,inh,jnh,imll,jmll,imi,jmi,fbare2,fbare2_interp)
!
      else  !averaging inside each grid cell (for coarse resolutions > 0.1x0.1 deg)
!
      call average_gridcell(NX,NY,lons,lats,fbare1,fbare1,fbare1_interp)
      call average_gridcell(NX,NY,lons,lats,fbare2,fbare2,fbare2_interp)
!
      endif  !interp
!
      open(unit=3,file='../output/seamask',status='unknown',form='unformatted')
      read(3) sm
      close(3)

!      open(unit=3,file='../output/snow',status='unknown',form='unformatted')
!      read(3) snow
!      close(3)
      
!
      do i=1,imi
      do j=1,jmi
!
       if(sm(i,j).gt.0..or.fbare1_interp(i,j).lt.0.) fbare1_interp(i,j)=0.
       if(sm(i,j).gt.0..or.fbare2_interp(i,j).lt.0.) fbare2_interp(i,j)=0.
! 
      enddo
      enddo      
!
!----------------------------------------------------------------------------------------
!Create netcdf to check everythind 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--------------------------------
      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


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



!
  call check( nf90_create("fbare_modis.nc", NF90_CLOBBER, ncid) )
!
! Define the dimensions. NetCDF will hand back an ID for each. 
  call check( nf90_def_dim(ncid, "west_east", imi, lon_dimid) )
  call check( nf90_def_dim(ncid, "south_north", 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, "fbare", NF90_REAL, dimids, fbare_varid) )
  call check( nf90_put_att(ncid, fbare_varid, "coordinates", "lon lat") )
  call check( nf90_def_var(ncid, "west_east", NF90_INT, lon_dimid, lon_varid) )
  call check( nf90_def_var(ncid, "south_north", NF90_INT, lat_dimid, lat_varid) )
  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, lat_varid, "axis", "Y") )
  call check( nf90_put_att(ncid, lon_varid, "axis", "X") )
  call check( nf90_put_att(ncid, rlat_varid, "units", "degrees_north") )
  call check( nf90_put_att(ncid, rlat_varid, "title", "latitude") )
  call check( nf90_put_att(ncid, rlon_varid, "units", "degrees_east") )
  call check( nf90_put_att(ncid, rlon_varid, "title", "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, fbare_varid, fbare_interp) )
  call check( nf90_put_var(ncid, lat_varid, south_north) )
  call check( nf90_put_var(ncid, lon_varid, west_east) )
  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 fbare modis! "
!
!
!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 fbare_modis

      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
!-----------------------------------------------------------------------
