#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#define M_PI 3.141592653589793
#define INF 1.0e90 
#ifndef PI 
#define PI_2  6.2831853071795862 
#endif 



#include "randgen.c"
#include "est_xz_genotype.c"
#include "est_beta.c"


/********/
/* main */
/********/


main()
{
	int i,j,times,step,k,K,nK,trials,tt,N,Nt,Ns,an;
	int M,aN0,aN,xm;
	int **fdata;
	int G12[3] = {0,1,2};
	double a[5] = {1,1,1,1,1};
	double alpha_o;
	double az[5] = {0,0,0,0,0};
	double ***PXK;
	int xM[5]={3,3,3,3,3};
	double **ax;

	FILE *fid;

	srand(time(NULL));
 	whseed(rand(),rand(),rand());

	N=158;
	nK = 3;
	M = 2;							// binary case for G
	aN0 = 2;
	aN =3;

	trials = 1;	 					
	times =40000;						// the length of the chain
	Nt = 5000;							// the length after burning
	Ns = 1;
	step = 1;


	
	fdata = (int**) calloc(N,sizeof(int*));
	for (j = 0; j<N; j++)
	{
		fdata[j] = (int*) calloc(2+aN0,sizeof(int));
	}
	
	get_data(N,aN0,fdata,"obesitypartdata1.txt");


	PXK = (double***) calloc(2,sizeof(double));
	{
		for(an=0;an<2;an++)
		{
			PXK[an] = (double**) calloc(nK,sizeof(double));
			for(i=0;i<nK;i++)
				PXK[an][i] = (double*) calloc(trials,sizeof(double));
		}
	}
	ax = (double**) calloc(aN,sizeof(double*));
	for (an=0;an<aN;an++)
	{
		ax[an]= (double*) calloc(xM[an],sizeof(double));
	}
	for (an=0;an<aN;an++)
	{
		for (xm = 0; xm<xM[an];xm++)
		ax[an][xm]= 1;
	}


	for (tt=0;tt<trials;tt++)
	//K = 2;
	{
		for (K=1;K<nK+1;K++)
		{
			// Step 1: Start with the reseaonable initial values theta_0 for the paparameters (by the estimation)
						
			alpha_o = whrandom()*10.0;
			// inference about the population structure
			//est_xz_fn(N,a,ax,alpha_o,times,trials,nK,Nt,tt,K,M,aN,xM,fdata,PXK);
			// inference about the association parameters
			est_beta_fn(N,a,ax,alpha_o,step,times,trials,nK,Nt,tt,K,M,aN,xM,fdata);
		}
		fid = fopen("obesity_K.txt","a");
		fprintf(fid,"%d ",tt);
		for(an=0;an<2;an++)
		{
			for(k=0;k<nK;k++)
				fprintf(fid,"%4.4f ",PXK[an][k][tt]);
		}
		fprintf(fid," \n");
		fclose(fid);
	}
		
	for (j = 0; j<N; j++)
	{
		free(fdata[j]);
	}
	free(fdata);

	for (an=0;an<aN;an++)
	{
		free(ax[an]);
	}
	free(ax);

	for(an=0;an<2;an++)
	{
		for(i=0;i<nK;i++)
			free(PXK[an][i]);
		free(PXK[an]);
	}
	free(PXK);
	
}