C Writing a station data set in GrADS format
C by Ooi See Hai on 2 February 2009
C
      character*8 stid
C
      undef = -999.0
	d2r = 3.141592654/180.0
C
      open (10, file='d:\tfplot\a03.txt')
      open (20, file='d:\tfplot\a03.dat',form='unformatted',
     &    recordtype='stream')
C
C If flag is zero, there are no surface variables following the header.
C
      iflag = 0
C
C Read and write
C
      read(10,*)
C
      do 30 n=1,8
C
         read(10,40) iyear,imonth,stid,rlat,rlon,t,p,id,s
  40     format(i4,3x,i2,2x,a8,2f8.2,2f8.1,i3,5x,f8.1)
C
         if (iflag .eq. 0) then
	     iflag = 1
	     iyrold = iyear
	     imnold = imonth
	   endif
C
C If new time group, write time group terminator. Number of data groups
C (nlev) is set to zero. Assuming no empty time groups. 
C
         if (iyrold .ne. iyear .or. imnold .ne. imonth) then
	     nlev = 0
	     write(20) stid,rlat,rlon,tim,nlev,nflag
	   endif
           iyrold = iyear
	     imnold = imonth
	 
C
C  Set field to undefined if not available and convert winds to u and v
C
          if (t .eq. 888.8) then
	      t = undef
	    endif

	    if (p .eq. 8888.8) then
	      p = undef
	    endif

	    if (id .eq. 888) then
	      id = undef
	      s = undef
	      u = undef
	      v = undef
	    else
	      u = -s*sin(id*d2r)
	      v = -s*cos(id*d2r)
	    endif
C     
C Write this report.Report time is set to zero for exactly on the hour.
C
           tim = 0.0
	     nlev = 1
	     nflag = 1
           write(20) stid,rlat,rlon,tim,nlev,nflag
	     write(20) t,p,u,v
C
  30   continue
C
C On end of file write last time group terminator.
C
       nlev = 0
	 write(20) stid,rlat,rlon,tim,nlev,nflag
	 stop
	 end