       program prepmegan_meteo
!**********************************************************************
!*
!*   This program prepares the temperature and swradiation for 
!*   MEGAN routines. Input files are from NMMB previous run with RSWIN
!*   and TSHLTR variables.
!*
!**********************************************************************
use netcdf
implicit none
integer, parameter :: max_files=60
integer :: num_meteo_files, spinup, nhours, hist_meteo_freq,imi,jmi,im, jm, ifn_args
character (len=200), DIMENSION(max_files) :: file_meteo
character*600 :: file_inp,output_file
logical :: global

namelist /meteo/ global, imi, jmi, num_meteo_files, spinup, nhours, hist_meteo_freq, file_meteo

real,dimension(:,:),allocatable :: T2,RSWIN,T2tmp,RSWINtmp,COUNTRS
real,dimension(:,:),allocatable :: padded2
integer :: count, hour, ffile,ierr,ii,jj, file_id
character*4 :: chour

!For debug netcdf file
integer :: lx_id, ly_id, sw_id,t2_id, input_id, stat
!
!*** Gets arguments from inputfile
ifn_args=10
!call GETARG(iarg,file_inp)
file_inp="namelist.input"
open(ifn_args,file=file_inp,form='formatted',status='old',action='read',iostat=ierr)
read(ifn_args,nml=meteo,iostat=ierr)
if(global)then
  im=imi+2
  jm=jmi+2
else
  im=imi
  jm=jmi
endif
print *,'global: ',global,im,jm,imi,jmi
close(ifn_args)
!*** Initialize variables
allocate(T2(im,jm))
allocate(RSWIN(im,jm))
allocate(T2tmp(im,jm))
allocate(RSWINtmp(im,jm))
allocate(COUNTRS(im,jm))
allocate(padded2(im,jm))
T2=0.
RSWIN=0.
COUNTRS=0.
!LOOP OVER INPUT FILES
count=0
do ffile=1,num_meteo_files
!OPEN NNMB NETCDF FILE
file_inp=trim(file_meteo(ffile))
stat=nf90_open(trim(file_inp),nf90_netcdf4,file_id)
call check_stat(stat,'Openning monarch netcdf file: '//trim(file_inp))
do hour=spinup,nhours,hist_meteo_freq
!do hour=hist_meteo_freq,23,hist_meteo_freq
!do hour=6,29,hist_meteo_freq !for spin-up of 6h hist_meteo_freq,23,hist_meteo_freq
!if(hour.lt.10) then
!  write(chour,'(i1)') hour
!!  file_inp=trim(file_meteo(ffile))//'nmm_b_history.00'//trim(chour) !fileiso
!  file_inp=trim(file_meteo(ffile))//'nmmb_hst_01_bin_00'//trim(chour)
!else
!  write(chour,'(i2)') hour
!  file_inp=trim(file_meteo(ffile))//'nmm_b_history.0'//trim(chour) !fileiso
!endif
T2tmp=0.
RSWINtmp=0.
call read_nc4_nmmb_file(file_id,hour,count,T2tmp,RSWINtmp,im,jm)
T2=T2+T2tmp
count=count+1

RSWIN=RSWIN+RSWINtmp
!  do ii=1,im
!    do jj=1,jm
!      if(RSWINtmp(ii,jj).gt.0.) COUNTRS(ii,jj)=COUNTRS(ii,jj)+1
!    enddo
!  enddo
enddo !hour
stat=nf90_close(file_id)
enddo !ffile

T2=T2/count
RSWIN=RSWIN/count
print *,'average on:',count
!RSWIN=RSWIN/count !!!Be carefull, average over all 24h per day!!! It has to be improved
!  do ii=1,im
!    do jj=1,jm
!      if(COUNTRS(ii,jj).gt.0.) RSWIN(ii,jj)=RSWIN(ii,jj)/COUNTRS(ii,jj)
!    enddo
!  enddo

if(.not.global)then !!!Copy boundaries for regional case
    do ii=1,im
      T2(ii,1)=T2(ii,2)
      T2(ii,jm)=T2(ii,jm-1)
      RSWIN(ii,1)=RSWIN(ii,2)
      RSWIN(ii,jm)=RSWIN(ii,jm-1)
    enddo
    do jj=1,jm
      T2(1,jj)=T2(2,jj)
      T2(im,jj)=T2(im-1,jj)
      RSWIN(1,jj)=RSWIN(2,jj)
      RSWIN(im,jj)=RSWIN(im-1,jj)
    enddo
endif

!For debug purpouses - create output netcdf file
output_file="../out/"
output_file=trim(output_file)//"meteo-data.nc"
print*,'Creating debug netcdf output file'
stat=nf90_create(output_file,nf90_write,input_id)
call check_stat(stat,'create debug file')
stat=nf90_def_dim(input_id, 'i_dim',im,lx_id)
stat=nf90_def_dim(input_id, 'j_dim',jm,ly_id)
call check_stat(stat,'Defining dimensions ')
stat=nf90_def_var(input_id,'T2mean',NF90_FLOAT,(/lx_id,ly_id/),t2_id)
call check_stat(stat,'Defining variable ')
stat=nf90_def_var(input_id,'SWmean',NF90_FLOAT,(/lx_id,ly_id/),sw_id)
call check_stat(stat,'Defining variable ')
stat=nf90_enddef(input_id)
call check_stat(stat,'End defining mode')
stat=nf90_put_var(input_id,t2_id,T2,start=(/1,1/),count=(/im,jm/))
call check_stat(stat,'Writting field')
stat=nf90_put_var(input_id,sw_id,RSWIN,start=(/1,1/),count=(/im,jm/))
call check_stat(stat,'Writting field')
stat=nf90_close(input_id)


!Pack the nmmb grid to binary file
output_file="../out/"
output_file=trim(output_file)//'meteo-data.dat'
open(22,file=output_file,form="unformatted",status='unknown')
if(global)then
      call padh2(T2,padded2,imi,jmi,im,jm)
      write(22) padded2 !T2
      call padh2(RSWIN,padded2,imi,jmi,im,jm)
      write(22) padded2 !RSWIN
else
      write(22) T2
      write(22) RSWIN
endif

close(22)
!*** END
print *,'---------Enjoy your meteo data----------'

end program prepmegan_meteo
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      subroutine read_nc4_nmmb_file(file_id,hour,count,T2tmp,RSWINtmp,im,jm)
!-----------------------------------------------------------------------
! reads binary outputs of nmmb-monarch v2.0
use netcdf
!implicit none
integer :: file_id,hour,rswin_id,t2_id,count
integer :: im,jm,stat
real,dimension(im,jm) :: T2tmp, RSWINtmp
!-----------------------------------------------------------------------
     stat=nf90_inq_varid(file_id,'RSWIN', rswin_id)
     call check_stat(stat,'problem inquiring RSWIN in prepmegan')
     stat=nf90_inq_varid(file_id,'T2',t2_id)
     call check_stat(stat,'problem inquiring T2 in prepmegan')

     stat=nf90_get_var(file_id,rswin_id,RSWINtmp,start=(/1,1,count+1/),count=(/im,jm,1/))
     call check_stat(stat,'problem reading RSWIN in prepmegan')

     stat=nf90_get_var(file_id,t2_id,T2tmp,start=(/1,1,count+1/),count=(/im,jm,1/))
     call check_stat(stat,'problem reading T2 in prepmegan')

     end subroutine read_nc4_nmmb_file
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      subroutine padh2(h2,ph2,imi,jmi,im,jm)
!-----------------------------------------------------------------------
!      include 'lmimjm_hires.inc'
!-----------------------------------------------------------------------
      dimension h2(imi,jmi),ph2(im,jm)
!-------------averaging at polar points---------------------------------
      rim=1./(imi-1)
      h2s=0.
      h2n=0.
      do i=1,imi-1
        h2s=h2(i,1)+h2s
        h2n=h2(i,jmi)+h2n
      enddo
      h2s=h2s*rim
      h2n=h2n*rim
      do i=1,imi
        h2(i,1  )=h2s
        h2(i,jmi)=h2n
      enddo
!-------------padding---------------------------------------------------
      do j=1,jmi
        do i=1,imi
          ph2(i+1,j+1)=h2(i,j)
        enddo
      enddo
!
      do i=2,im-1
        ph2(i,1 )=ph2(i,3   )
        ph2(i,jm)=ph2(i,jm-2)
      enddo
!
      do j=1,jm
        ph2(1   ,j)=ph2(im-2,j)
        ave=(ph2(2,j)+ph2(im-1,j))*0.5
        ph2(2   ,j)=ave
        ph2(im-1,j)=ave
        ph2(im  ,j)=ph2(3   ,j)
      enddo
!-----------------------------------------------------------------------
      return
      end
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
!***********************************************************************
subroutine check_stat(stat,message)
  use netcdf
  implicit none
  include 'netcdf.inc'
  integer, intent(in)       :: stat
  character*100, intent(in) :: message

  if ( stat /= nf90_NoErr ) then
     print*, 'error in netcdf status while...'
     print*, TRIM(message), stat, nf90_strerror( stat )
     STOP 1
  endif
end subroutine check_stat
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

