
;+
; NAME
;
;     EIS_CUBIC_SPLINE()
;
; PROJECT
;
;     Hinode/EIS
;
; EXPLANATION
;
;     Creates an optimised cubic spline fit to the orbital variation of EIS
;     emission line centroids. The spline is used by eis_orbit_spline to
;     perform the orbital variation correction to the output of eis_auto_fit.
;
; INPUTS
;
;     T    Time array given in minutes.
;
;     Y    Function values at T (expected to be velocity or line centroid).
;
; OPTIONAL OUTPUT
;
;     NODES  The nodes at which the spline is defined. The points will be
;            spaced at equal intervals specified by SPACING. The
;            default is 5 minutes.
;
; OPTIONAL INPUT
;
;     SPACING Sets the spacing of the node points in minutes. The
;             default is 5 minutes. Should be an integer.
;
; OUTPUT
;
;     The spline fit values at the defined nodes.
;
; INTERNAL ROUTINES
;
;     ECS_FIT_FUNC()
;
; COMMON BLOCKS
;
;     ECS_FIT_DATA
;
; HISTORY
;
;     Ver.1, 4-Mar-2008, Peter Young
;     Ver.2, 10-May-2010, Peter Young
;       added optional input SPACING=
;-


;------------------------
FUNCTION ecs_fit_func, x, p
;
; p  These are the cubic spline values at the nodes.
; x  The data points being fit
;

COMMON ecs_fit_data, n, spacing

; node values:
;
t=findgen(n)*float(spacing)

y2=spl_init(t,p)
return,spl_interp(t,p,y2,x)

END


;------------------------
FUNCTION eis_cubic_spline, t, y, nodes, yfit=yfit, spacing=spacing

COMMON ecs_fit_data, nn, nspacing

IF n_elements(spacing) EQ 0 THEN spacing=5.

nspacing=spacing

n=n_elements(t)
weights=fltarr(n)+1.   ; set equal weighting for each data point

nn=fix(max(t)/round(spacing))+1

nodes=findgen(nn)*float(spacing)

;
; get initial guess for node points by fitting a spline
;
y2=spl_init(t,y)
init=spl_interp(t,y,y2,nodes)

expr='ecs_fit_func(x,p)'

aa=mpfitexpr(expr,t,y,weights,weights=weights,init,/quiet,yfit=yfit)

return,aa

END

