MODULE ReadFields
  
   IMPLICIT NONE
   PRIVATE
   PUBLIC :: ReadGrib

   CONTAINS

   SUBROUTINE ReadGrib(fname,imax,jmax,temp,statfctrd)
   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   !
   ! Subroutine ReadGrib
   !
   ! Julio P. R. Fernandez, DMD/CPTEC
   ! 11/2005
   ! Modified: Antonio Marcos Mendonca
   ! Dec/2008
   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   
   CHARACTER(LEN=*),         INTENT(IN)    :: fname
   INTEGER,  	             INTENT(IN)    :: imax,jmax
   REAL,DIMENSION(imax,jmax),INTENT(OUT)   :: temp
   INTEGER,                  INTENT(INOUT) :: statfctrd

   ! Local Variables

   INTEGER*4                :: nxny
   INTEGER*4                :: i,j,k,iunit,ierr,nwords,knum
   INTEGER*4,DIMENSION(200) :: jpds,jgds,kpds,kgds

   REAL,DIMENSION(imax*jmax)     :: tmp

   LOGICAL*1,DIMENSION(imax*jmax) :: bitmap


   !
   ! READ DATA IN GRIB1 FORMAT
   !

   nxny=imax*jmax
   iunit=12

   write(*,*) ' '
   write(*,*) 'fname: ',fname
   CALL BAOPEN(iunit,fname,ierr)
   IF (ierr .NE. 0) THEN
      WRITE(6,*) 'BAOPEN TROUBLE!!!! ', ierr
      statfctrd=1
   END IF 


   !
   ! variable tems
   !

   jpds(:)=-1
   jgds(:)=-1
   jpds(5)=188    !				    C	       (5)   - INDICATOR OF PARAMETER
   jpds(6)=1      !- TYPE OF LEVEL		    C	       (6)   - TYPE OF LEVEL     1- surface    =100   level	
   jpds(7)=0      !- HEIGHT/PRESSURE , ETC OF LEVEL C	       (7)   - HEIGHT/PRESSURE , ETC OF LEVEL

   CALL GETGB(iunit,0,nxny,0,jpds,jgds,nwords,knum,kpds,kgds,bitmap,tmp,ierr)
   IF (ierr .ne. 0) THEN
      WRITE(6,*) 'getgb TROUBLE!!!! field', ierr
      statfctrd=1
   END IF

   WRITE(6,*)'Variable: ',jpds(5),jpds(6),jpds(7)
   WRITE(*,*) 'nwords: ',nwords

   IF (nwords .NE. imax*jmax) THEN
      WRITE(*,*) 'field n.o of points is wrong: ',nwords  
      statfctrd=1
   END IF  

   DO j=1,jmax
   DO i=1,imax
      k=(j-1)*imax+i
      temp(i,j)=tmp(k)	  
   END DO
   END DO 
   CALL BACLOSE(iunit,ierr)
   WRITE(6,*) 'BACLOSE :', ierr
   IF (ierr .NE. 0) WRITE(6,*) 'BACLOSE TROUBLE!!!! ', ierr

   RETURN
   END SUBROUTINE ReadGrib


END MODULE ReadFields


PROGRAM Main
  USE ReadFields, Only :ReadGrib
  INTEGER, PARAMETER :: iMax=384
  INTEGER, PARAMETER :: jMax=192
  CHARACTER(LEN=500) :: DirName
  CHARACTER(LEN=500) :: FileName
  INTEGER            :: statfctrd
  REAL               :: prec(iMax,jMax)
  REAL               :: temp(iMax,jMax)
  DirName='./datain'
  FileName='GPOS01N20150801122015080118P.fct.TQ0126L028.grb'
  statfctrd=0
  PRINT*,TRIM(DirName)//'/'//TRIM(FileName)
  CALL ReadGrib(TRIM(DirName)//'/'//TRIM(FileName),imax,jmax,prec,temp,statfctrd)

END PROGRAM Main
