/*===========================================================================
  Copyright (C) 1995-2009 European Southern Observatory (ESO)
 
  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., 675 Massachusetts Ave, Cambridge, 
  MA 02139, USA.
 
  Correspondence concerning ESO-MIDAS should be addressed as follows:
	Internet e-mail: midas@eso.org
	Postal address: European Southern Observatory
			Data Management Division 
			Karl-Schwarzschild-Strasse 2
			D 85748 Garching bei Muenchen 
			GERMANY
===========================================================================*/

/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

.IDENT        fitnol.c
.MODULE       subroutines 
.LANGUAGE     C
.AUTHOR       Cristian Levin - ESO La Silla
.PURPOSE      gaussian fitting.
.KEYWORDS     gaussian fitting.
.ENVIRONMENT  UNIX
.VERSION 1.0  1-Apr-1991   Implementation

 090723		last modif
------------------------------------------------------------*/

#include <math.h>





/************************************************************
 *
 * fit_gauss(): Gaussian fitting. 
 * 
 ************************************************************/

#include "mpfit.h"
#include <stdlib.h>

static double gauss(double x, double amp, double mean, double sigma)
{
    double v = x - mean;
    return amp * exp(-(v * v) / (2. * (sigma * sigma)));
}

typedef struct {
    double * x;
    double * y;
} priv_data;

int myfunct(int m, int n, double *p, double *deviates,
            double **derivs, priv_data *d)
{
    int i;
    /* Compute function deviates */
    for (i=0; i<m; i++) {
        deviates[i] = d->y[i] - gauss(d->x[i], p[0], p[1], p[2]);
    }

    return 0;
}

int fit_gauss (double *x, double *y, int n, double *a, int nfp)
{
    priv_data pdata = {&x[1], &y[1]};
    mpfit((mp_func)&myfunct, n, nfp,
          &a[1], NULL, NULL,
          &pdata,
          NULL);
}

