#include <stdlib.h>
#include "./sticky.h"
#define GNMAX 20000
#define CNMAX 500

void read_nemoformat(fp,n,dim,t,m,x,v)
	FILE *fp;
	int *n;
	int *dim;
	REAL *t;
  	REAL m[NMAX];
	REAL x[NMAX][DIM];
	REAL v[NMAX][DIM];
{
	int i;
	unsigned long int index;

	fscanf(fp,"%d%d%lf",n,dim,t);
	index = *n;
	for(i=0;i<index;i++)fscanf(fp,"%lf",&m[i]);
	for(i=0;i<index;i++)fscanf(fp,"%lf%lf%lf",&x[i][0],&x[i][1],&x[i][2]);
	for(i=0;i<index;i++)fscanf(fp,"%lf%lf%lf",&v[i][0],&v[i][1],&v[i][2]);
}	

void write_nemoformat(fp,n,dim,t,m,x,v)
	FILE *fp;
	int n;
	int dim;
	REAL t;
	REAL m[NMAX];
	REAL x[NMAX][DIM];
	REAL v[NMAX][DIM];
{
	int i;
	
	fprintf(fp,"%d \n%d \n%e \n",n,dim,t);
	for(i=0;i<n;i++)fprintf(fp,"%e \n",m[i]);
	for(i=0;i<n;i++)fprintf(fp,"%e %e %e \n",x[i][0],x[i][1],x[i][2]);
	for(i=0;i<n;i++)fprintf(fp,"%e %e %e \n",v[i][0],v[i][1],v[i][2]);
}	

static FILE *fpinput;

void data_input(x,v,m,cm,n,filename,time)
	REAL x[NMAX][DIM];
	REAL v[NMAX][DIM];
	REAL m[NMAX];
	REAL cm[DIM];
	int *n;
	char filename[];
	REAL *time;
{
	long int k,j,i,pindex;
	int kx,ky,kz;
        REAL ranx,rany,ranz,abs,root2;
	FILE *fp,*fp1,*fopen();
	int nc,ng;
	REAL alpha1 = 0.0;		
	REAL alpha2 = 0.0;		
	REAL dum1;
	int dum;

	fpinput = fopen(filename,"r");
        if (fpinput == NULL) {
            char buf[256];
            sprintf(buf, "In %s data_input() fopen(\"%s\", \"r\") failed. ",
                    __FILE__, filename);
            perror(buf);
            exit(1);
        }
	read_nemoformat(fpinput,n,&dum,time,m,x,v);
	fclose(fpinput);

	printf("initialdata end\n");

/*	for(k=0;k<DIM;k++) cm[k] = 0.0;
	i = *n;
 	for(j=0;j<i;j++){
	  for(k=0;k<DIM;k++) cm[k] += x[j][k] * m[j] ;
	}
	for(k=0;k<DIM;k++) cm[k] /= *n;
*/
}

void data_output(t,x,v,m,n,fp1)
	REAL t;
	REAL x[NMAX][DIM];
	REAL v[NMAX][DIM];
	REAL m[NMAX];
	int n;
	FILE *fp1;
{
	int dum = 3;
	long int i;

#ifdef NEMOFORMATOUTPUT
	write_nemoformat(fp1,n,dum,t,m,x,v);
#endif
#ifdef MONGOFORMAT
	for(i=0;i<n;i++) fprintf(fp1,"%g %g %g ",x[i][0],x[i][1],x[i][2]);
	fprintf(fp1,"\n");
#endif
}

void galaxy_center_of_mass(x,time)
	REAL x[NMAX][DIM];
	REAL time;
{
	FILE *fp3,*fopen();
	int i,ij,j,k;
	REAL gcm[3];
	REAL gcmr;
	int nog=256,noc=64;


	fp3 = fopen("gcm","a");
        fprintf(fp3,"%e ",time);
        for(i=0;i<noc;i++){
          for(k=0;k<DIM;k++) gcm[k] = 0.0;
          for(j=0;j<nog;j++){
            ij = i*nog + j;
            for(k=0;k<DIM;k++) gcm[k] += x[ij][k]/(REAL)nog;
          }
          gcmr = sqrt(gcm[0]*gcm[0]+gcm[1]*gcm[1]+gcm[2]*gcm[2]);
          fprintf(fp3,"%g %g %g %g ",gcm[0],gcm[1],gcm[2],gcmr);
        }
        fprintf(fp3,"\n");
	fclose(fp3);
}

