%N fitpoly %F $MIR/src/subs/calpoly.for
%D Fit a polynomial
%: calibration, polynomials
%P pjt
%B
        INTEGER FUNCTION fitpoly( n, x, y, code, bl, porder)
        IMPLICIT NONE

        INTEGER   bl, porder, n
        REAL      x(*), y(*)
        CHARACTER code*(*)

   Fit a polynomial of certain order to data - the polynomial coefficients
   are merged into the /calpoly/ common data. This does not guarantee
   that evalpoly returns the correct value is previous fits for this
   'window' (code,bl) existed. [BUG or FEATURE - FIX OR NOT TO FIX].
   <<some redundant code exists in calfit now>>

   Fitpoly returns the ranking index of the new poly in the (code,bl) 
   interval. If there are breakpoints and/or multiple sources the data 
   may be only valid over a subinterval. 

   In case of multiple calls to FITPOLY with
   non-overlapping intervals FITPOLY will keep track of more than
   one polynomial per interval and tell you it's current ranking.

   When n-1 < porder, a fit is done to order n-1, and the remaining
   coefficients are set to 0

   Input:
       n         number of points
       x         x-ordinates
       y         y-data to fit
       bl        associated baseline [b=findbase(bl); b=1..nbl]
       code      associated phase/amp code
       porder    order to fit (0..MAXORDER)
   Output:
       fitpoly   index 'IPOL' of current data in poly(i,IPOL,s,b)
