! getGuadPCcellnum.exe
!
! read 3D list of cells
! read list Guadalupe and Plum Creek wells
! find nearest cell
! return cell number, layer, and distance of closest cell center

! declare arrays

dimension xcg(382024),ycg(382024),ilg(382024),igcdg(382024),icog(382024),igmag(382024)
dimension xcw(103),ycw(103)
dimension icellw(7:9,103),distw(7:9,103)
character*30 text

! initialize cell,ilw,distw

do 10 kk=1,103
do 11 kl=7,9
icellw(kl,kk)=0
distw(kl,kk)=1e6
11 continue
10 continue

! read 3D cell list

open (10,file='GMA13Grid.csv')
read (10,*) text
do 100 k=1,382024
read (10,*) idg,ilg(k),igcdg(k),icog(k),igmag(k),xcg(k),ycg(k)
100 continue

! read list of Guadalupe and Plum Creek Wells

open (20,file='GuadalupePlumCreekLocations.csv')
read (20,*) text
do 200 kk=1,103
read (20,*) text,xlat,xlong,xcw(kk),ycw(kk)
200 continue

! find nearest cell

do 300 kk=1,103
do 301 k=1,382024
if (ilg(k).eq.7) then
dt1=xcw(kk)-xcg(k)
dt2=dt1*dt1
dt3=ycw(kk)-ycg(k)
dt4=dt3*dt3
dt5=dt2+dt4
dt6=sqrt(dt5)
if (dt6.lt.distw(7,kk)) then
icellw(7,kk)=k
distw(7,kk)=dt6
end if
end if
if (ilg(k).eq.8) then
dt1=xcw(kk)-xcg(k)
dt2=dt1*dt1
dt3=ycw(kk)-ycg(k)
dt4=dt3*dt3
dt5=dt2+dt4
dt6=sqrt(dt5)
if (dt6.lt.distw(8,kk)) then
icellw(8,kk)=k
distw(8,kk)=dt6
end if
end if
if (ilg(k).eq.9) then
dt1=xcw(kk)-xcg(k)
dt2=dt1*dt1
dt3=ycw(kk)-ycg(k)
dt4=dt3*dt3
dt5=dt2+dt4
dt6=sqrt(dt5)
if (dt6.lt.distw(9,kk)) then
icellw(9,kk)=k
distw(9,kk)=dt6
end if
end if
301 continue
300 continue

! write results

open (40,file='Guad PC Well Cell.dat')
do 400 kk=1,103
write (40,410) kk,(icellw(kl,kk),kl=7,9),(distw(kl,kk),kl=7,9)
410 format (4i10,3f10.0)
400 continue

stop
end
