c SPLIT_N.FOR
c
c  To quantize a grid into n levels.  Requires n and data min,max. Grid
c  values less than min are assigned a value of 1; values greater than
c  max are assigned a value of n, and values beteen min and max are 
c  assigned values between 1 and n.  To display results with program
c  ZOCZC, let contour interval = 1 and datum = 8.
c
c  Lin Cordell
c  February 1994
c
      character*50 ifile,ofile
      dimension f(2000),id(14),pgm(2)
      data dval/0.170412e+39/
      dval2=1.e20
      write(6,1)
1     format(' Enter input file name:'/' *'$)
      read(5,100)ifile
100   format(a50)
      write(6,201)
201   format(1x,'Enter output file name:'/' *'$)
      read(5,100)ofile
      open(10,file=ifile,form='unformatted',status='old')
      read(10)id,pgm,ncol,nrow,nz,x0,dx,y0,dy
      if(ncol.gt.2000.or.nz.ne.1.or.dx.eq.0.e0) go to 900
      open(11,file=ofile,form='unformatted',status='new')
      write(6,202)
202   format(' Enter new id:'/' *'$)
      read(5,203)(id(i),i=1,14)
203   format(14a4)
      write(6,204)
204   format(' Enter min, max:'/' *'$)
      read*, fmin,fmax
      range=fmax-fmin
      write(6,205)
205   format(' Enter n:'/' *'$)
      read*, rn
      rnm=rn-1
      write(11)id,pgm,ncol,nrow,nz,x0,dx,y0,dy
      min=100000
      max=-min
      do 20 j=1,nrow
      call rowio(f,y,1,ncol,10,1)
      do 10 i=1,ncol
      if(f(i).gt.dval2)then
        f(i)=dval
        go to 10
      endif
      f0=f(i)-fmin
      if(f0.lt.0.)f0=0.
      if(f0.ge.range)f0=range
      kf=1.+(f0/range)*rnm
      f(i)=kf
      if(kf.gt.max)max=kf
      if(kf.lt.min)min=kf
10    continue
      call rowio(f,y,1,ncol,11,2)
20    continue
      print*,' Min =',min,',  Max =',max
      go to 998
900   write(6,901)
901   format(' Can''t handle it.')
998   close(11)
999   close(10)
      stop
      end
      subroutine rowio(a,y,nz,ncol,ld,key)
      dimension a(nz,ncol)
      go to (1,2),key
1     read(ld) y,a
      go to 90
2     write(ld)y,a
90    return
      end
