!-------------------------------------- LICENCE BEGIN ------------------------------------
!Environment Canada - Atmospheric Science and Technology License/Disclaimer, 
!                     version 3; Last Modified: May 7, 2008.
!This is free but copyrighted software; you can use/redistribute/modify it under the terms 
!of the Environment Canada - Atmospheric Science and Technology License/Disclaimer 
!version 3 or (at your option) any later version that should be found at: 
!http://collaboration.cmc.ec.gc.ca/science/rpn.comm/license.html 
!
!This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
!without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
!See the above mentioned License/Disclaimer for more details.
!You should have received a copy of the License/Disclaimer along with this software; 
!if not, you can write to: EC-RPN COMM Group, 2121 TransCanada, suite 500, Dorval (Quebec), 
!CANADA, H9P 1J3; or send e-mail to service.rpn@ec.gc.ca
!-------------------------------------- LICENCE END --------------------------------------
***s/r readgrid
*		
#include "model_macros_f.h"

      subroutine readgrid (xgi_8,ygi_8,ni,nj) 2
      implicit none
*
      integer ni,nj
      real*8 xgi_8(ni), ygi_8(nj)
*
*author
*     M. Desgagne -  summer 2008
*
#include "ptopo.cdk"
#include "grd.cdk"

      integer  fnom,fstluk,fstouv,fstinf,wkoffit
      external fnom,fstluk,fstouv,fstinf,wkoffit
      integer i,j,err,ni1,nj1,nk1,key,nix,njx,iref,jref,unf,ftype
      real epsilon
      real, dimension(:), allocatable :: xpff,ypff

      ftype = wkoffit(trim(Grd_filename_S))

      if ( .not. (ftype.eq.33).or.(ftype.eq.34) ) return

      unf = 0
      err = fnom   (unf,trim(Grd_filename_S),'RND+OLD', 0)
      err = fstouv (unf,ni1)

      key = fstinf (unf, nix,nj1,nk1, -1, ' ', -1,-1,-1,' ','>>')
      allocate (xpff(nix))
      err = fstluk( xpff, key, nix,nj1,nk1) 

      key = fstinf (unf, ni1,njx,nk1, -1, ' ', -1,-1,-1,' ','^^')
      allocate (ypff(njx))
      err = fstluk( ypff, key, ni1,njx,nk1) 

      epsilon = 1.0e-6
      iref = 0
      jref = 0
      do i=1,nix
        if (abs(xpff(i)).lt.(epsilon/100.)) then
           if (abs(xpff(i)-xgi_8(1)).lt.epsilon) iref=i
        else
	   if (abs(xpff(i)-xgi_8(1))/abs(xpff(i)).lt.epsilon) iref=i
        endif
      end do
      do i=1,njx
        if (abs(ypff(i)).lt.(epsilon/100.)) then
           if (abs(ypff(i)-ygi_8(1)).lt.epsilon) jref=i
        else
     	   if (abs(ypff(i)-ygi_8(1))/abs(ypff(i)).lt.epsilon) jref=i
        endif
      end do
*
      if ( (iref.eq.0) .or. (jref.eq.0) ) return

      if (Ptopo_myproc.eq.0) print*, 'FORCED GRID: ',iref,jref

      do i=1,ni
         xgi_8(i) = xpff(iref+i-1)
      end do
      do j=1,nj
         ygi_8(j) = ypff(jref+j-1)
      end do
*
      deallocate (xpff,ypff)
*
      return
      end