/*

$Id: polynm.c,v 1.3 2015/09/22 15:09:20 jim Exp $

* This file is part of the CASU Pipeline utilities
* Copyright (C) 2015 European Southern Observatory
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <stdlib.h>
#include "imcore.h"
#include "floatmath.h"
#include "util.h"

/* least-squares fit of order m polynomial to n data points */

extern void imcore_polynm (float xdat[], float xcor[], int n, float polycf[], 
                           int m, int ilim) {
  double a[25][25], b[25], temp;
  int i, j, k;

/*   if(n < m)  bomboutx(1, "polynm: too few data points"); */
/*   if(m > 25) bomboutx(1, "polynm: order of polynomial too large"); */

  /* clear arrays */
  for(i = 0; i < 25; i++) {
    b[i] = 0.0;
    for(j = 0; j < 25; j++) a[i][j] = 0.0;
  }

  /* cumulate sums */
  for(i = 0; i < n; i++) {
    for(k = 0; k < m; k++) {
      temp = 1.0;
      if(k+ilim != 0)temp = pow(xcor[i], (float) (k+ilim));
      b[k] += xdat[i]*temp;

      for(j = 0; j <= k; j++) {
        temp = 1.0;
        if(k+j+2*ilim != 0)temp = pow(xcor[i], (float) (k+j+2*ilim));
        a[j][k] += temp;
      }
    }
  }

  for(k = 1; k < m; k++) {
    for(j = 0; j < k; j++) a[k][j] = a[j][k];
  }

  /* solve linear equations */
  imcore_solve(a, b, m);

  for(i = 0; i < m; i++) polycf[i] = b[i];
}

/*

$Log: polynm.c,v $
Revision 1.3  2015/09/22 15:09:20  jim
Fixed guards and comments

Revision 1.2  2015/08/12 11:16:55  jim
Modified procedure names to protect namespace

Revision 1.1.1.1  2015/06/12 10:44:32  jim
Initial import

Revision 1.2  2014/04/09 09:09:51  jim
Detabbed

Revision 1.1.1.1  2013/08/27 12:07:48  jim
Imported


*/
