C Copyright 1981-2012 ECMWF.
C
C This software is licensed under the terms of the Apache Licence 
C Version 2.0 which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
C
C In applying this licence, ECMWF does not waive the privileges and immunities 
C granted to it by virtue of its status as an intergovernmental organisation 
C nor does it submit to any jurisdiction.
C

       PROGRAM FIND_T
      IMPLICIT NONE
C
      INTEGER JPACK, JPBYTES
      PARAMETER (JPACK = 300000)
      PARAMETER (JPBYTES = 4)
C
      INTEGER INBUFF
      DIMENSION INBUFF(JPACK)
      INTEGER IRET, NARGS, N, J, ILENB, LENOUT, NTEMPS
      INTEGER IVALUE, NUMBER, ISIZE, IPARAM, ITEMP, IARGC
C
      INTEGER  PBGTOTL, PBGPUT, PBGGET, PBGLENG, PBGPARM
      EXTERNAL PBGTOTL, PBGPUT, PBGGET, PBGLENG, PBGPARM
      EXTERNAL GETENV
C
      CHARACTER*128 INFILE, OUTFILE, CARG(4)
C
C **********************************************************************
C
C     Pick up file names from command line.
C
      NARGS = IARGC()
	  IF( NARGS.LT.4 ) THEN
         print*,'Usage: find_t -i inputfile -o outputfile'
         STOP
      END IF

      DO 101 J=1,NARGS
      CALL GETARG(J,CARG(J))
 101  CONTINUE

      DO 102 J=1,NARGS,2
        IF(CARG(J).EQ.'-i') THEN
           INFILE=CARG(J+1)
        ELSEIF(CARG(J).EQ.'-o') THEN
           OUTFILE=CARG(J+1)
        ELSE
            print*,'Usage: find_t -i inputfile -o outputfile'
            STOP
        END IF
 102  CONTINUE
C
C     Count number of GRIBs in the file
C
      NUMBER = PBGTOTL(INFILE)
      WRITE(*,*) 'Number of GRIBs in the file = ', NUMBER
      IF( NUMBER.EQ.0 ) STOP 'No Gribs found'
C
C     Search for temperature fields.
C     (Temperature is code 130 in table 128.)
C
      NTEMPS = 0
      ITEMP = (128*1000) + 130
      ILENB = JPACK * JPBYTES
C
      DO N = 1, NUMBER
C
        IPARAM = PBGPARM(INFILE,N)
C
C       Handle the GRIB product if it is a temperature field
C
        IF( IPARAM.EQ.ITEMP ) THEN
C
C         Check buffer is big enough for GRIB field.
C
          ISIZE = PBGLENG(INFILE,N)
          IF( ISIZE.GT.ILENB ) THEN
            WRITE(*,*) 'Field size (bytes)  = ', ISIZE
            WRITE(*,*) 'Buffer size (bytes) = ', ILENB
            STOP 'Buffer too small for field'
          ENDIF
C
C         Read temperature field and write it to the output file.
C
          NTEMPS = NTEMPS + 1
          LENOUT = PBGGET(INFILE, INBUFF, ILENB, N)
          IF( LENOUT.LT.0 ) STOP 'Problem reading temperature field'
C
          IRET = PBGPUT(OUTFILE, INBUFF, LENOUT)
          IF( IRET.LT.LENOUT ) STOP 'Problem writing temperature field'
C
        ENDIF
C
      ENDDO
C
      WRITE(*,*) 'Number of temperature fields copied = ', NTEMPS
      IF( NTEMPS.EQ.0 ) WRITE(*,*) 'No output file created'
C
      STOP
      END
