/*
 * This file is part of the ESO SINFONI Pipeline
 * Copyright (C) 2004,2005 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, 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
 */
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif
/*#include "companion.c"*/
/*#include "balance.c"*/
/*#include "qr.c"*/
#include "sinfo_solve_poly_root.h"

/**@{*/
/**
 * @addtogroup sinfo_utilities Utilities to find roots of a polynomial
 *
 * TBD
 */


gsl_poly_complex_workspace *
sinfo_gsl_poly_complex_workspace_alloc (size_t n)
{
  size_t nc ;

  gsl_poly_complex_workspace * w ;
 
  if (n == 0)
    {
      sinfo_msg_error ("sinfo_matrix size n must be positive integer");
      return NULL ;
    }

  w = (gsl_poly_complex_workspace *)
    cpl_malloc (sizeof(gsl_poly_complex_workspace));

  if (w == 0)
    {
      sinfo_msg_error ("failed to allocate space for struct");
      return NULL ;
    }

  nc = n - 1;

  w->nc = nc;

  w->sinfo_matrix = (double *) cpl_malloc (nc * nc * sizeof(double));

  if (w->sinfo_matrix == 0)
    {
      cpl_free (w) ;       /* error in constructor, avoid memory leak */
      sinfo_msg_error("failed to allocate for workspace sinfo_matrix") ;
      return  NULL ;
    }

  return w ;
}

void
sinfo_gsl_poly_complex_workspace_free (gsl_poly_complex_workspace * w)
{
  cpl_free(w->sinfo_matrix) ;
  cpl_free(w);
}


int
sinfo_gsl_poly_complex_solve (const double *a, size_t n,
            gsl_poly_complex_workspace * w,
            gsl_complex_packed_ptr z)
{
  int status;
  double *m;

  if (n == 0)
    {
      sinfo_msg_error ("number of terms must be a positive integer");
      return -1 ;
    }

  if (n == 1)
    {
      sinfo_msg_error ("cannot solve for only one term");
      return -1 ;
    }

  if (a[n - 1] == 0)
    {
      sinfo_msg_error ("leading term of polynomial must be non-zero") ;
      return -1 ;
    }

  if (w->nc != n - 1)
    {
      sinfo_msg_error ("size of workspace does not match polynomial");
      return -1 ;
    }
  
  m = w->sinfo_matrix;

  sinfo_set_companion_matrix (a, n - 1, m);

  sinfo_balance_companion_matrix (m, n - 1);

  status = sinfo_qr_companion (m, n - 1, z);

  if (status == -1)
    {
      sinfo_msg_error("root solving qr method failed to converge");
      return -1 ;
    }

  return 1;
}

/**@}*/

