FUNCTION extrap_2d, array_in, degree=degree, SAMPLE=sample

; Extrapolates each column by fitting exponential function to previous 
; SAMPLE values in column; then smooths each row.
;

array = array_in
IF not(keyword_set(DEGREE)) THEN degr=2 ELSE degr=degree
IF not(keyword_set(SAMPLE)) THEN sample=20
sz= size(array)
ny = sz(2)
nx = sz(1)
x=findgen(nx)
zs = where(array(*,0:20) EQ 0,bzs)
zs = where(array(*,ny-21:ny-1) EQ 0,tzs)
rot_flag=0
IF bzs GT tzs THEN BEGIN
	array=rotate(array,2)
	rot_flag=1
ENDIF

lTz = where (array LT 0)
nz = where(array GT 0)
moms = moment(array(nz),SDEV=sdev)
IF ltz(0) NE -1 THEN array(ltz)=sdev/100.
medarr = median(array(nz))
minarr = min(array(nz))

m=0
REPEAT BEGIN
	lastfullrow=array(*,m)
	m=m+1
	testz = where(array(*,m) EQ 0)
ENDREP UNTIL testz(0) NE -1
lastfullsub=m-1

nn=''
y = FINDGEN(ny)
;stats=moment(array(nz))
;vrnc = stats(1)
nvrnc=0
nnewval=0
newvals=fltarr(nx,ny)
allcolvals=array(0,*)
newarr = array

prevcol=newarr(0,*)
wset,0
FOR i=0,nx-1 DO BEGIN
   col = array(i,*)
   first_case=1
   jsub=0
   FOR j=0,ny-1 DO BEGIN
     IF col(j) EQ 0 THEN BEGIN
	j0 = j-sample
	subcol=col(j0:ny-1)
	;top = j+sample < ny-j-1
	;subcol = col(j0:j+top)
	IF first_case THEN BEGIN
	   nz = where(subcol GT 0,nnz)
	   nsc = n_elements(subcol)
	   subcol(nsc-1) = minarr
	   nz = where(subcol GT 0,nnz)
	   yf = ALOG(subcol(nz))		; ** Compute exponential fit
	   coef = poly_fit(nz,yf,1)		;    y = a*exp(b*x)
	   a = EXP(coef(0))			;
	   b = coef(1)				;
  	   compcol=a*exp(b*x)
   	   first_case = 0
	ENDIF
;
	colval=compcol(sample+jsub)
	;newarr(i,j)=colval > lastrow(i)
;if i EQ 142 THEN stop
	allcolvals(j)=colval
	val1 = colval
	col(j)=val1
     	jsub = jsub+1	; number of 0 values in column
   ENDIF
   ENDFOR
   newarr(i,*) = col
   prevcol = col 
   IF i mod (2*sample) EQ 0 THEN Begin
	surface,rotate(newarr,2),/horiz,back=11 
	;print,i
   ENDIF
ENDFOR

FOR j=m,ny - 1 DO BEGIN
   row = newarr(*,j)
   srow= smooth(row,5)
   oldrow = array(*,j)
   z = where(oldrow EQ 0)
   row(z)=srow(z)
   newarr(*,j) = row
ENDFOR

surface,rotate(newarr,2),/horiz,back=11

IF rot_flag THEN newarr=rotate(newarr,2)

;help,nvrnc,nnewval
return, newarr

end
