! f90 -o loadmarknew initialmod.f90 savemod.f90 loadmarknew.f90

program LoadMarkNew

use InitialMod
use SaveMod

implicit none

real, dimension (:), pointer 			:: GloSlice

integer, pointer, dimension (:,:)		:: MapIDLRaw, MapIDLReg
integer, dimension (:), pointer 		:: MapRawReg, RegSizes

character (len=20), dimension (:), pointer 	:: RegNames

integer, dimension (:,:), allocatable :: RawData

real, parameter :: MissVal = -999.0

integer :: XRawLat, XRawLong, XSix, XRaw, XLat, XLong, XDatum, XReg
integer :: Raw0, Raw1
integer :: LatN, LongN, GridChosen, GridDataN, RegN

character (len=80) :: GloFilePath, GridFilePath, RegTitle, Header, Blank, LogFilePath
character (len=10) :: GridTitle

call GridSelect (GridChosen,GridTitle,LongN,LatN,GridDataN,GridFilePath)
call RegSelect  (GridChosen, LongN, LatN, GridDataN, MapIDLReg, RegSizes, RegNames, RegTitle, RegN)
call RawSelect  (GridChosen,LongN,LatN,MapIDLReg,MapIDLRaw,MapRawReg)

LogFilePath = '/cru/u2/f709762/data/scratch/log-marknew.dat'
open (99, file=LogFilePath, status="replace", access="sequential", form="formatted", action="write")

allocate (RawData(LatN,LongN),GloSlice(RegN))
GloSlice = MissVal

GloFilePath = '/cru/u2/f709762/data/scratch/ctmp6190.dat'
open (2, file=GloFilePath, status="old", access="sequential", form="formatted", action="read")

read (2,*), Header
read (2,*), Header

do XRawLat = 1, LatN
    read (2,"(720i5)"), (RawData (XRawLat,XRawLong), XRawLong = 1,720)
end do

close (2)

print*, "### loaded"

do XRawLat = 1, LatN
  do XRawLong = 1, LongN
    XDatum = ((XRawLat-1) * LongN) + XRawLong
    
    GloSlice (MapRawReg(XDatum)) = float(RawData (XRawLat,XRawLong))
    
!    write (99,"(2i6,i8,i8,2f12.4)"), XRawLat, XRawLong, XDatum, MapRawReg(XDatum), &
!    			RawData (XRawLat,XRawLong), &
!    			GloSlice (MapRawReg(XDatum))
  end do
end do

print*, "### transferred to regions"

do XReg = 1, RegN
!  write (99,"(i8,f12.4)"), XReg, GloSlice(XReg)
  if (GloSlice(XReg).EQ.-9999.0) GloSlice(XReg) = MissVal
end do

print*, "### missing values detected"

Blank = ""
call SaveGlo (LongN, LatN, RegN, GridFilePath, Blank, Blank, GloSlice, MapIDLReg)

deallocate (RawData,GloSlice,MapIDLRaw,MapIDLReg,MapRawReg, RegSizes,RegNames)

close (99)

end program LoadMarkNew
