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

program GrabPPXLu

use FileNames

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
character (len=20) :: DataFormat, ColumnText


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

open (99,file="/cru/mikeh1/f709762/scratch/log/log-grabppxlu.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)
  allocate (Data(DataN),stat=AllocStat)
  if (AllocStat.NE.0) print*, "  > ##### ERROR: Allocation failure: Data #####"  
  read  (1) (Data(XDatum),XDatum=1,DataN)
  close (1)  
  
  if (XFile.EQ.1) write (99,*), (HeaderInt(XHeader),XHeader=1,19)
  if (XFile.EQ.1) write (99,*), (HeaderReal(XHeader),XHeader=1,45)
  
  print*, "  > Latitudes, Longitudes, Data: ", LatN, LongN, DataN
  
  SaveFile = Batch(XFile) ; FileSubBeg = index(SaveFile,".pp ")
  SaveFile (FileSubBeg:(FileSubBeg+3)) = ".txt"
  SaveFile = SavePath (SaveFile,".txt")
  
  ColumnText = GetTextFromInt (LongN)
  DataFormat = "(" // trim(ColumnText) // "e16.7)"
  
  open (1,status="replace",form="formatted",action="write",file=SaveFile)
    write (1,"(2a)"), "converted to ASCII from: ", trim(Batch(XFile))
    write (1,"(a)"), "by Dr. Shaper (TM)"
    write (1,"(a)"), "beware of missing values"
    write (1,"(a)"), "it is *not* guaranteed that this is the correct lat/long structure: check!"
    write (1,"(a17,3i6)"), "lats,longs,data: ", LatN,LongN,DataN
    write (1,"(2a)"), "data format: ", trim(DataFormat)
    
    do XLat = 1, LatN
      write (1,DataFormat), (Data(XDatum),XDatum=(((XLat-1)*LongN)+1),(XLat*LongN))
    end do
  close(1)
  
  deallocate (Data,stat=AllocStat)
  if (AllocStat.NE.0) print*, "  > ##### ERROR: Deallocation failure: Data #####"
end do

close (99)

end program GrabPPXLu
