! procwmo.f90
! f90 program that manipulates the WMO station list and replaces blanks with missing values
! f90 -o ./../misc/procwmo filenames.f90 ./../misc/procwmo.f90

program ProcWMO

use FileNames

implicit none

real, pointer, dimension (:)			:: Lat,Long,Elev

integer, pointer, dimension (:)			:: Code

character (len=20), pointer, dimension (:)	:: Name
character (len=04), pointer, dimension (:)	:: AcroStn
character (len=02), pointer, dimension (:)	:: AcroCty

integer :: ReadStatus, AllocStat
integer :: StnN,XStn, DLat,DLong,DElev

real, parameter :: MissVal = -999.0

character (len=80) :: LoadFile,SaveFile,Trash
character (len=30) :: LoadFormat = "(i6,a1,a4,a3,a20,a2,a6,a7,i5)"
character (len=30) :: SaveFormat = "(i6,a1,a4,a3,a20,a1,a2,3f8.2)"
character (len=20) :: TLat,TLong

LoadFile = "/cru/mikeh1/f709762/obs/meta/ncdc-stn-sort.dat"
SaveFile = "/cru/mikeh1/f709762/obs/meta/ncdc-stn-proc.dat"

call system ('wc -l ' // LoadFile // ' > trashme.txt')
open  (3,file='trashme.txt',status="old",access="sequential",form="formatted",action="read")
read  (3,"(i10)"), StnN
close (3)
call system ('rm trashme.txt')
    
allocate (Code    (StnN), &
	  Lat     (StnN), &
	  Long    (StnN), &
	  Elev    (StnN), &
	  Name    (StnN), &
	  AcroStn (StnN), &
	  AcroCty (StnN), stat=AllocStat)
if (AllocStat.NE.0) print*, "  > ##### ERROR: LoadWMOCty: Allocation failure #####"
Code=MissVal ; Lat=MissVal ; Long=MissVal ; Elev=MissVal ; Name="" ; AcroStn="" ; AcroCty=""

open  (3,file=LoadFile,status="old",access="sequential",form="formatted",action="read")
do XStn = 1, StnN
  read (3,LoadFormat), Code(XStn),Trash,AcroStn(XStn),Trash,Name(XStn),AcroCty(XStn),TLat,TLong,DElev
  
  if (len_trim(TLat).GT.0) then
    DLat = GetIntFromText (TLat)
    Lat(XStn)=real(DLat)/100.0
  else
    Lat(XStn)=MissVal
  end if
  
  if (len_trim(TLong).GT.0) then
    DLong = GetIntFromText (TLong)
    Long(XStn)=real(DLong)/100.0
  else
    Long(XStn)=MissVal
  end if
  
  Elev(XStn)=real(DElev)
  if (Elev(XStn).EQ.9999.0) Elev(XStn)=MissVal
end do
close (3)

open  (3,file=SaveFile,status="replace",access="sequential",form="formatted",action="write")
do XStn = 1, StnN
  write (3,SaveFormat), Code(XStn)," ",AcroStn(XStn),"   ",Name(XStn)," ",AcroCty(XStn),&
  			Lat(XStn),Long(XStn),Elev(XStn)
end do
close (3)
 
!*******************************************************************************

end program ProcWMO

