#include <euredit_sys.h>


int main (int argc, char *argv[])
{
	long        n = 200;
	long        m = 8;
	long       *sx;
	double     *data;
	double      miss_val = -999.0;
	long        c = 3;
	double      alpha = 0.005;
	long        method = 1;
	double     *indwt;
	double     *swts = NULL;
	long        info[2];

	const char  file[] = "continuous.dat";
	FILE       *fp;
	long        i, j, niw, nrw;
	long       *iwork;
	double     *rwork;


	/* Memory allocation. */
	niw = m;
	nrw = (1+m)*n;
	if (swts != NULL)
	{
		nrw += n;
	}

	if (!(iwork = (long *)malloc (niw * sizeof (long))))
	{
		printf ("Memory allocation failure.\n");
		exit (2);
	}
	if (!(rwork = (double *)malloc (nrw * sizeof (double))))
	{
		printf ("Memory allocation failure.\n");
		exit (2);
	}

	data = rwork;
	indwt = data + m*n;
	if (swts != NULL)
	{
		swts = indwt + n;
	}
	sx = iwork;
	
	/* Include all variables in the analysis */
	for (i=0; i<m-1; ++i) sx[i] = 1;
	sx[m-1] = sx[1] = sx[0] -1;

	/* Load data */
	if ((fp = fopen (file, "r")) == NULL)
    {
         free (iwork);
         free (rwork);
		 printf ("Cannot open file named %s for reading.\n", file);
		 exit (2);
	}

    for (i=0; i<n; ++i)
    {
        for (j=0; j<m; ++j)
        {
			fscanf(fp, "%lf", &data[i*m+j]);
        }
        fscanf(fp, "\n");
    }
    fclose(fp);

	info[0] = info[1] = 0;

	/* Call BACON-EM implementation */
	bacon (n,m,sx,data,miss_val,c,alpha,method,indwt,swts,info);

	if (info[0] == -999)
	{
		printf (" Obtain a licence from NAG to run the EM option in this component.\n");
		exit (2);
	}
	else if (info[0] > 0)
	{
		printf (" Error %i calling bacon component.\n", info[0]);
		exit (2);
	}
	else
	{
		for (i=0; i<n; i++)
        {
            if (indwt[i] == 0.0)
            {
			    printf(" Observation %ld suspected outlier \n",i+1);
            }
            else if (indwt[i] == -1.0)
            {
			    printf(" Observation %ld contains missing values \n",i+1);
            }
        }
	}

	free (iwork);
	free (rwork);

	return 0;
}
