#include <euredit_sys.h>


int main (int argc, char *argv[])
{
	/* Parameters */
	char        xmlfname[] = "categorical.xml";
	long        n = 0;
	long        m = 0;
	long        max_name = 0;
	long        info[2];

	char        xdrfname[] = "categorical.xdr";
	double      miss_val = -999.0;
	double     *data;
	char      **v_name;
	long        n_cat[] = {100,2,2,2,3,5,10,11};
	long        cat_val[800];
	long        maxcat = 100;
	long        mset = 1;
	long        nmiss = 0;

	long        nimp;
	long       *irow;
	long       *icol;
	double     *rval;
	long       *iwork;

	char        xslfname[] = "categorical.xsl";
	long        u_status = 1;

	long        i;


	/* Use .xdr file to get sizes of arrays */
	xml_data_size (xdrfname,&n,&m,&max_name,info);

	if (info[0] > 0 || n < 1 || m < 1)
	{
		printf (" Error %ld calling component xml_data_size.\n", info[0]);
		exit (2);
	}

	/* Read-in data from .xml file */
	if (!(data = (double *)malloc (n*m * sizeof (double))))
	{
		printf (" Memory allocation failure.\n");
		exit (2);
	}

	if (!(v_name = (char **)malloc (m * sizeof (char *))))
	{
		printf (" Memory allocation failure.\n");
		free (data);
		exit (2);
	}

	for (i=0; i<m; ++i)
	{
		if (!(v_name[i] = (char *)malloc ((max_name+1)*sizeof(char))))
		{
			printf (" Memory allocation failure.\n");
			free (data);
			free (v_name);
			exit (2);
		}
	}

	xml_read (xmlfname,xdrfname,miss_val,n,m,data,v_name,n_cat,cat_val,maxcat,
              mset,&nmiss,info);

	if (info[0] > 0)
	{
		printf (" Error %ld calling component xml_read.\n", info[0]);
		exit (2);
	}


	/* Impute some missing values / find outliers */
	if (!(iwork = (long *)malloc (2*nmiss * sizeof (long))))
	{
		printf ("Memory allocation error.\n");
		exit (2);
	}
	irow = iwork;
	icol = irow + nmiss;

	if (!(rval = (double *)malloc (nmiss * sizeof (double))))
	{
		printf ("Memory allocation error.\n");
		free (iwork);
		exit (2);
	}

	/* Call simple imputation function */
	simp_imp (n,m,data,n_cat,cat_val,maxcat,miss_val,&nimp,irow,
		      icol,rval,info);

	if (info[0] > 0)
	{
		printf (" Error %ld in call to function simp_imp.\n", info[0]);
		free (data);
		free (iwork);
		free (rval);
		exit (2);
	}


	/* Update the XML */
	xml_update (xmlfname,xdrfname,xslfname,miss_val,n,m,u_status,nmiss,irow,
                icol,rval,info);

	if (info[0] > 0)
	{
		printf (" Error %ld calling component xml_update.\n", info[0]);
		exit (2);
	}


	return 0;
}
