c     TERRACE1
c
c     1-D (profile) terracing program.
c     Input is a 1-row grid.
c     Lin Cordell 17 August 92
c
      character*50 infile,outfile
      dimension f(1024),g(1024),id(14),pgm(2)
      ifft=2
c  Input
50    write(6,1)
1     format(1x,'Enter input file name (a 1-row grid):')
      print 101
101   format(' *'$)
      read(5,100)infile
100   format(a50)
      open(10,file=infile,form='unformatted',status='old',err=995)
      read(10)id,pgm,ncol,nrow,nz,x0,dx,y0,dy
      if(ncol.le.1024.and.dx.ne.0.e0.and.nz.eq.1)go to 3
      write(6,2)
2     format(1x,'Can''t handle it.')
      stop
3     continue
      rncol=ncol
      nrow=1
      read(10)dum,(g(i),i=1,ncol)
      do 7 i=1,ncol
      if(g(i).ge.1.e+30) then
            print*,'Cant handle dvals.'
            stop
      endif
7     f(i)=g(i)
c  Terrace.
      iter1=1
      iter2=20
33    do 30 iter=iter1,iter2
      flat=0.
      do 31 i=2,ncol-1
      a=0.5*(f(i+1)+f(i-1))
      if(f(i-1).eq.f(i+1))flat=flat+1
      if(f(i).gt.a)then
	g(i)=max(f(i-1),f(i+1))
      else
	g(i)=min(f(i-1),f(i+1))
      endif
31    continue
      do 32 i=1,ncol
32    f(i)=g(i)
      f(1)=f(2)
      f(ncol)=f(ncol-1)
      p=(flat*100)/rncol
30    continue
      print*,'After',iter2,' iterations, Percent of flat slopes =',p
      print*,'Enter number of additional iterations:'
      print 101
      read*,iterd
      if(iterd.gt.0)then
	iter1=iter2+1
	iter2=iter2+iterd
	go to 33
      endif
      print*,'Enter output file name'
      read 100,outfile
      print*,'Enter id:'
      print 101
      read(5,211)(id(i),i=1,14)
211   format(14a4)
      open(11,file=outfile,status='new',form='unformatted')
      pgm(1)='terr'
      pgm(2)='ace1'
      write(11)id,pgm,ncol,nrow,nz,x0,dx,y0,dy
      print*,'Result will be normalized between range of min,max'
209   print*,'Enter min, max (or 0,0 not to normalize):'
      print 101
      read*,tmin,tmax
      if(tmin.ge.tmax.and.tmin.ne.0.and.tmax.ne.0)then
	print*,'min < max, or 0,0, si,l vous plait.'
	go to 209
      endif
      if(tmin.eq.0.and.tmax.eq.0.)go to 210
      trange=tmax-tmin
      fmax=-1.e30
      fmin=1.e30
      do 40 i=1,ncol
      if(f(i).gt.fmax)fmax=f(i)
      if(f(i).lt.fmin)fmin=f(i)
40    continue
      y=0
      range=fmax-fmin
      do 41 i=1,ncol
      f(i)=(f(i)-fmin)/range
      f(i)=f(i)*trange+tmin
41    continue
210   continue
      write(11)dum,(f(i),i=1,ncol)
      go to 999
995   print*,'File not found.'
999   continue
      stop
      end
