c     mediplug.for - dos version
c     J.Phillips, USGS, Denver, Colorado
c     changes from vms version are indicated by cv
c
c     fills holes using the median of surrounding values
c
      dimension a(10000), b(10000, 3), c(10000), id(14), pgm(2)
      character ifile*50
      data ddval / 1.0e+36 /
    1 write(*, 200) 
  200 format(14h enter ifile: ,$)
      read(5, 100) ifile
  100 format(a50)
cv    open(10,file=ifile,status='old',form='unformatted')
      open(10, file=ifile, status='old', form='unformatted', err=1) 
      write(*, 201) 
  201 format(14h enter ofile: ,$)
      read(5, 100) ifile
cv    open(11,file=ifile,status='new',form='unformatted')
      open(11, file=ifile, status='unknown', form='unformatted') 
      read(10) id, pgm, nc, nr, nz, xo, dx, yo, dy
      write(11) id, pgm, nc, nr, nz, xo, dx, yo, dy
      read(10) dlt, (b(i,3),i = 1, nc)
      write(11) dlt, (b(i,3),i = 1, nc)
      read(10) dlt, (b(i,2),i = 1, nc)
      nd = 0
      do 14 ii = 3, nr
        read(10) dlt, (b(i,1),i = 1, nc)
        c(1) = b(1,2)
        c(nc) = b(nc,2)
        do 12 i = 2, nc - 1
          c(i) = b(i,2)
          if (c(i) .gt. ddval) then
            j = 0
            do 11 k = 1, 3
              do 10 l = i - 1, i + 1
                if (b(l,k) .lt. ddval) then
                  j = j + 1
                  a(j) = b(l,k)
                end if
10            continue
11          continue
            if (j .gt. 0) call median(j, a)
            if (j .lt. 1) then
              nd = nd + 1
            else
              c(i) = a(1)
            end if
          end if
12      continue
        write(11) dlt, (c(i),i = 1, nc)
        do 13 i = 1, nc
          b(i,3) = b(i,2)
          b(i,2) = b(i,1)
13      continue
14    continue
      write(11) dlt, (b(i,1),i = 1, nc)
      write(*, 101) nd
  101 format(i10,13h dvals remain)
      stop 
      end
c
      subroutine median(n, a[HUGE])
      dimension a(n)
   10 if (n .le. 2) return 
      ax = a(1)
      an = a(1)
      iax = 1
      ian = 1
      do 11 i = 2, n
        if (a(i) .gt. ax) then
          ax = a(i)
          iax = i
        end if
        if (a(i) .lt. an) then
          an = a(i)
          ian = i
        end if
11    continue
      if (an .eq. ax) then
        a(1) = an
        return 
      end if
      j = 0
      do 20 i = 1, n
      temp = a(i)
      if ((i .eq. iax) .or. (i .eq. ian)) goto 20
      j = j + 1
      a(j) = temp
   20 continue
      n = j
      goto 10
      end
