c  DE_PREP.FOR
c
c  To delete extended rows and columns after filtering of output of program
c  prep and, optionally, adding back the linear trend removed by program PREP.  
c  Requires file prep.rec as output from program prep.
c
c  Lin Cordell Mar 1990.
c
        character*56 ifile,ofile
        character id*56, prjnam*80
c        dimension g(2048),id(14),pgm(2),cmbl(2)
        dimension g(2048),cmbl(2)
	open(10,file='prep.rec',status='old',form='formatted')
	read(10,1)ifile
1       format(a50)
        read(10,2)alpha,beta,nc,nr
2       format(2e16.8,2i5)
        read(10,3)prjnam,cmbl
3       format(a50/2e16.8)
	close(10)
        call pfinit('de_prep')
        call askin
        ifile=' '
400     call askc('Enter name of grid to be de-prepped',ifile,ierr)
        if(ierr.lt.0) stop
        call gopen(10,ifile,'old','read',ierr)
        if(ierr.ne.0) then
          print*,'Error - try again'
          go to 400
        endif
c        ofile=' '
        ofile=ifile(1:index(ifile,'.'))//'dpr'
401     call askc('Enter output grid name',ofile,ierr)
        if(ierr.eq.-2) then
          close(10)
          go to 400
        endif
        call gopen(11,ofile,'new','write',ierr)
        if(ierr.ne.0) then
          print*,'Error - try again'
          go to 401
        endif
        call gheader('r',10,id,ncol,nrow,xo,dx,yo,dy,ierr)
        if(ierr.ne.0) stop 'error reading grid header'
        call askalt
        call askc('Enter id',id,ierr)
        call askalt
	if(ncol.lt.nc.or.nrow.lt.nr)go to 900
30      print*,'Enter mode: 1 to add back linear trend,'
        mode=2
        call aski4('         or 2 not to add back linear trend',mode,
     1       ierr)
	if(mode.ne.1.and.mode.ne.2)go to 30
        call mpsnam('w',idum,prjnam,nch,ierr)
        call mpsref('w',idum,cmbl,nch,ierr)
        call gheader('w',11,id,nc,nr,xo,dx,yo,dy,ierr)
	if(mode.eq.1)then
	  do 10 j2=1,nr
        call grow('r',10,j2,g,nc,ierr)
	  yy=float(j2-1)
	  do 9 j1=1,nc
	  x=float(j1-1)
9         g(j1)=g(j1)-alpha*x-beta*yy
10        call grow('w',11,j2,g,nc,ierr)
	else
	  do 20 j2=1,nr
        call grow('r',10,j2,g,nc,ierr)
20        call grow('w',11,j2,g,nc,ierr)
	endif
	go to 999
900     print*, 'Cant handle it.'
	close(10)
999     close(11)
	stop
	end

