! getcellnum.exe
!
! read 3D list of cells
! read list GCUWCD 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 iocg(382024),thickg(382024),trans(382024)
dimension ilw(49),xcw(49),ycw(49)
dimension icellw(49),distw(49),icow(49),igcdw(49),igmaw(49),iocw(49)
character*30 text

! initialize cell,ilw,distw

do 10 kk=1,49
icellw(kk)=0
distw(kk)=1e6
icow(kk)=0
igcdw(kk)=0
igmaw(kk)=0
iocw(kk)=-9999
10 continue

! read 3D cell list and trans values

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

! read list of GCUWCD wells

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

! find nearest cell

do 300 kk=1,49
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(kk)) then
icellw(kk)=k
distw(kk)=dt6
ilw(kk)=7
icow(kk)=icog(k)
igcdw(kk)=igcdg(k)
igmaw(kk)=igmag(k)
iocw(kk)=iocg(k)
end if
end if
301 continue
300 continue

! write results

open (40,file='AllInteraTransCell.dat')
do 400 kk=1,49
write (40,410) kk,icellw(kk),ilw(kk),iocw(kk),icow(kk),igcdw(kk),igmaw(kk),distw(kk),trans(icellw(kk))
410 format (7i10,2f10.0)
400 continue

stop
end
