! ctyfiles.f90
! module for loading the master countries file: master-cty.txt

module CtyFiles

implicit none

contains

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

function MasterSize

integer :: MasterSize
character (len=80), parameter :: MasterFile = './../../../data/cruts/cty/master.txt'

call system ('tail -c +1 ' // trim(adjustl(MasterFile)) // &
 		' | wc | tr -s " " "\t" | cut -f2 > count.txt')
open  (3,file='count.txt',status="old",access="sequential", &
		form="formatted",action="read")
read  (3,"(i)"), MasterSize
close (3)
call system ('rm count.txt')

MasterSize = MasterSize + 1		! this is to allow an 'unknown' entry

end function MasterSize

!*******************************************************************************
! the general approach is
! 1. use MasterSize to find NMaster
! 2. alloc arrays in call
! 3. use this routine to fill the arrays

subroutine LoadMasterCty (MasterRawCty,MasterFinalCty,MasterCode0,MasterCode1,MasterContinent)

character (len=13), dimension (:), pointer 	:: MasterRawCty,MasterFinalCty
integer, dimension (:), pointer 		:: MasterCode0,MasterCode1,MasterContinent
integer :: NMaster
integer :: XMaster
character (len=80), parameter :: MasterFile = './../../../data/cruts/cty/master.txt'

if (.NOT.associated(MasterRawCty)) print*, "  > @@@@@ ERROR: LoadMasterCty: unalloc @@@@@"
NMaster=size(MasterRawCty)

open  (2,file=MasterFile,status="old",access="sequential",form="formatted",action="read")    
do XMaster = 1, NMaster-1
  read (2,"(2(a13,x),x,3(x,i9))"), MasterRawCty(XMaster),MasterFinalCty(XMaster), &
  		MasterCode0(XMaster),MasterCode1(XMaster),MasterContinent(XMaster)
end do
close (2)

MasterRawCty	(NMaster) = "UNKNOWN"
MasterFinalCty	(NMaster) = "UNKNOWN"
MasterCode0	(NMaster) =      0
MasterCode1	(NMaster) = 999999
MasterContinent	(NMaster) =      0

end subroutine LoadMasterCty

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

end module CtyFiles

