function interp4x, y1, y, SAMPLE=sample, DEBUG=debug, SLOPE=slope, MINSAM=minsam
; $Id: interp4x.pro,v 1.3 2017/12/19 23:03:22 nathan Exp $
;
; Purpose: given vector y, fit a line near y1 and then 
; 	   return value of x corresponding to input y1
;
; Inputs:	
;	y1	value for which x is desired
;	y	1-d array 
;
; Optional Input Keywords:
;	SAMPLE=	number of elements to use to fit a line, default is 10%	
;   	MINSAM=	Will return -1 if there are not this many samples available
;
; Outputs:
;   	value of x for input y
;
; Optional outputs:
;   	SLOPE=	FLOAT	slope of line used
;
; $Log: interp4x.pro,v $
; Revision 1.3  2017/12/19 23:03:22  nathan
; current SSW versions
;
; Revision 1.2  2010/10/20 20:56:39  nathan
; add SLOPE=, more debug info
;
; Revision 1.1  2010/10/20 19:49:29  nathan
; used by plane_project.pro to compute sun center
;

yvalid=where_not_missing(y)

ny=n_elements(yvalid)
IF ny LT 2 THEN BEGIN
	IF yvalid[0] GT 0 THEN ysam=bytarr(ny)
	goto, skip
ENDIF
x=indgen(n_elements(y))
x0=find_closest(y1,y[yvalid],/less)
IF keyword_set(SAMPLE) THEN BEGIN
    dx=sample/2 
    IF x0 LT dx or dx GT ny-x0 THEN dx=sample-(x0<(ny-x0))
ENDIF ELSE dx=fix(0.05*ny)
xsam=x[yvalid[((x0-dx)>0):((x0+dx)<(ny-1))]]
ysam=y[yvalid[((x0-dx)>0):((x0+dx)<(ny-1))]]
skip:
nsam=n_elements(ysam)
IF keyword_set(MINSAM) THEN samchk=minsam ELSE $
IF keyword_set(SAMPLE) THEN samchk=sample ELSE samchk=dx*2
IF nsam LT samchk THEN BEGIN
    IF keyword_set(DEBUG) THEN message,'nsam='+trim(nsam)+' LT '+trim(samchk),/info
    IF keyword_set(MINSAM) THEN return,-1
ENDIF 
bm=linfit(xsam,ysam)
slope=bm[1]
IF keyword_set(DEBUG) THEN BEGIN
    help,y,yvalid,x0,dx,ysam,slope
    wait,2
ENDIF
return,(y1-bm[0])/bm[1]

end
