PRO tri_fit,x,y,fit,xpeak,help=help

IF (keyword_set(help) or (n_params() eq 0)) THEN BEGIN
    print,'tri_fit,x,y,fit,xpeak'
    print,'  Fits the 3 data pairs to y=a+bx+cx^2, returning fit=[a,b,c]'
    print,'    and xpeak at position of inflection'
    print,'  x,y must each be [x1,x2,x3]'
    return
ENDIF

IF ((n_elements(x) NE 3) OR (n_elements(y) NE 3)) THEN BEGIN
    print,'tri_fit: need X, Y triplets'
    return
ENDIF

y1y0=y(1)-y(0)
y2y0=y(2)-y(0)
x1x0=x(1)-x(0)
x2x0=x(2)-x(0)
x1x0sq=x(1)*x(1)-x(0)*x(0)
x2x0sq=x(2)*x(2)-x(0)*x(0)
c_num=y2y0*x1x0-y1y0*x2x0
c_denom=x2x0sq*x1x0-x1x0sq*x2x0
if (c_denom EQ 0) then begin
  message,'Divide by zero error'
  return
endif
c=c_num/float(c_denom)
if (x1x0 EQ 0) then begin
  message,'Divide by zero error'
  return
endif
b=(y1y0-c*x1x0sq)/float(x1x0)
a=y(0)-b*x(0)-c*x(0)*x(0)

fit=[a,b,c]
if (c EQ 0.) then begin
  xpeak=0.
  print,'Cannot find xpeak'
  return
endif else begin
  xpeak=-b/(2.*c)
endelse

return
end

