      dimension f1(3000),f2(3000),dif(3000)
      character fil1*50,fil2*50,title*56,pgm*8,exit*2,comout*50,blnk*2
      data exit/'ex'/,ir/5/,blnk/'  '/
      bval=99999999.
      iw=6
1     write(iw,2)
2     format(' enter 1st file name: '$)
      read(ir,10)fil1
10    format(a)
      if(fil1.eq.exit.or.fil1.eq.blnk) go to 99
      open(10,status='old',form='unformatted',file=fil1)
      read(10)title,pgm,nc1,nr1,nz,x1,dx1,y1,dy1
      write(iw,4)
4     format(' enter 2nd file name: '$)
      read(ir,10)fil2
      open(12,status='old',form='unformatted',file=fil2)
      read(12)title,pgm,nc2,nr2,nz,x2,dx2,y2,dy2
      if(abs(dx1-dx2).gt.0.00001.or.abs(dy1-dy2).gt.0.00001)go to 98
      comout='compgrd.out'
      open(20,status='unknown',form='formatted',file=comout)
      write(20,20)fil1,nr1,nc1,y1,x1,dy1,dx1,fil2,nr2,nc2,y2,x2,dy2,dx2
20    format(///,' comparison of two grids',/,' file 1= ',a50,
     1/,' no. of rows & cols=',
     12i4,/,' 1st row & col coord=',2e12.5,/,' row & col spacing=',
     12e12.5,//,' file 2= ',a50,/,' no. of rows & cols=',2i4,/
     1,' 1st row & col coord.=',2e12.5,/,' row & col spacing=',
     12e12.5,///)
      ye1=y1+(nr1-1)*dy1
      ye2=y2+(nr2-1)*dy1
      ye=ye1
      if(ye1.gt.ye2)ye=ye2
      if(y1.lt.y2) go to 30
      mf=12
      nrb=(y1-y2)/dy1+1.000001
      nre=(ye-y1)/dy1+1.000001
      go to 40
30      mf=10
      nrb=(y2-y1)/dy1+1.000001
      nre=(ye-y2)/dy2+1.000001
40    xe1=x1+(nc1-1)*dx1
      xe2=x2+(nc2-1)*dx1
      xe=xe1
      if(xe1.gt.xe2)xe=xe2
      if(x1.lt.x2) go to 50
      nce=(xe-x1)/dx1+1.000001
      ncb1=1
      ncb2=(x1-x2)/dx1+1.000001
      nce1=(xe-x1)/dx1+1.000001
      nce2=(xe-x2)/dx1+1.000001
      go to 60
50      ncb1=(x2-x1)/dx1+1.000001
      nce=(xe-x2)/dx1+1.000001
      ncb2=1
      nce1=(xe-x1)/dx1+1.000001
      nce2=(xe-x2)/dx1+1.000001
60    if(nrb.eq.1) go to 72
      do 70 i=1,nrb-1
70    read(mf)dum
72    sumt=0.
      nt=0
      nsum=0
      sum=0.
      do 80 i=1,nre
      read(10)dum,(f1(j),j=1,nce1)
      read(12)dum,(f2(j),j=1,nce2)
      j1=ncb1-1
      j2=ncb2-1
      sum=0.
      nsum=0
      do 90 j=1,nce
      dif(j)=0.1701411e+39
      j1=j1+1
      j2=j2+1
      if(f1(j1).gt.bval.or.f2(j2).gt.bval) go to 90
      dif(j)=f1(j1)-f2(j2)
      sum=sum+dif(j)
      nsum=nsum+1
90    continue
      sumt=sumt+sum
      nt=nt+nsum
      if(nsum.eq.0) go to 80
      asum=sum/nsum
      write(6,100)i,asum
      write(20,100)i,asum
      write(20,101)(dif(j),j=1,nce)
80    continue
101   format(13g10.3)
100   format(' row =',i4,'    average diff=',f10.2)
      asumt=sumt/nt
      write(6,110)asumt,nt
      write(20,110)asumt,nt
110   format(//,' total average diff=',f10.2,4x,i5,'  values used')
      close(20)
98    close(10)
      close(12)
      go to 1
99    stop
      end
