! grabpp.f90 
! loads Hadley Centre pp files (single slices only) and saves them as ASCII files
! program written by Tim Mitchell on 08.10.01
! last modified on 08.10.01
! f90 -convert big_endian -o ./../misc/grabpp filenames.f90 glofiles.f90 ./../misc/grabpp.f90

program GrabPP

use FileNames
use GloFiles

implicit none

real, pointer, dimension (:) 			:: Data
integer, pointer, dimension (:,:) 		:: MapIDLReg
character (len=80), pointer, dimension (:) 	:: Batch

real, dimension (19) :: HeaderReal
integer, dimension (45) :: HeaderInt

real, parameter :: MissVal = -999.0
character (len=80), parameter :: Blank = ""

integer :: AllocStat
integer :: XLong, XLat, XFile, XDatum, XHeader, XEight
integer :: LongN, LatN, FileN, DataN, HalfN
integer :: FileSubBeg

character (len=80) :: SaveFile, RefFilePath

!*******************************************************************************

open (99,file="/cru/mikeh1/f709762/scratch/log/log-grabpp.dat",status="replace",action="write")

print*, "  > Specify the batch of pp files to transform .pp -> .txt"
call GetBatch (Blank,Batch)
FileN = size (Batch,1)

do XFile = 1, FileN
  print*, "  > Operating on file: ", XFile
  
  open  (1,status="old",form="unformatted",file=Batch(XFile))
  read  (1) HeaderInt, HeaderReal
  LatN = HeaderInt(18) ; LongN = HeaderInt(19) 
  DataN = HeaderInt(15)
  print*, "  > Latitude and Longitudes: ", LatN, LongN
  allocate (Data(DataN),stat=AllocStat)
  if (AllocStat.NE.0) print*, "  > ##### ERROR: Allocation failure: Data #####"  
  read  (1) (Data(XDatum),XDatum=1,DataN)
  close (1)  
  
  do XDatum = 1, DataN
    if (Data(XDatum).EQ.-0.1E+31) Data(XDatum) = MissVal
  end do
  
  allocate (MapIDLReg(LongN,LatN),stat=AllocStat)
  if (AllocStat.NE.0) print*, "  > ##### ERROR: Allocation failure: MapIDLReg #####"  
  XDatum = 0 ; HalfN = floor(real(LongN)/2.0)
  do XLat = 1, LatN
    do XLong = (HalfN+1), LongN
      XDatum = XDatum + 1
      MapIDLReg (XLong,XLat) = XDatum
    end do
    do XLong = 1, HalfN
      XDatum = XDatum + 1
      MapIDLReg (XLong,XLat) = XDatum
    end do
  end do    
  
  SaveFile = Batch(XFile) ; FileSubBeg = index(SaveFile,".pp ")
  SaveFile (FileSubBeg:(FileSubBeg+3)) = ".glo"
  SaveFile = SavePath (SaveFile,".glo")
  
  RefFilePath = GetGloRef (LongN,LatN)
  call SaveGlo (LongN,LatN,DataN,RefFilePath,SaveFile,trim(Batch(XFile)),Data,MapIDLReg)
  
  deallocate (Data,MapIDLReg,stat=AllocStat)
  if (AllocStat.NE.0) print*, "  > ##### ERROR: Deallocation failure: Data #####"
end do

close (99)

end program GrabPP
