/*             Corr

        A program for computing the correlation dimension
                  after  P. Grassberger

kmax=1000000  length of the sequence
m_embed=3     maximum embedding dimension
eps=1.        Largest distance up to which pairs are counted
logimax=7     imax=2**logimax-1 is number of boxes in each directions
              must be < 9
min_delay=1   the minimum delay for which pairs are to be included


*/

#define MAXSIZE 100000  /* Pay attention to dimensions in grassberger.f */
#include <math.h>
#include <stdio.h>
#define MM(m,i) mm[i+m*128]






main(argc, argv)
     int argc;
     char *argv[];

{

  float xdata[MAXSIZE],xmax;
  int mm[128*12];
  int kmax, m_embed, logimax, min_delay,i,j;
  float x,eps,dist,t;

  int arg;
  char name[128],sExtension[128];
  char sFileOut[128];
  FILE *fPtr;
  FILE* fPtrOut;

/* defaults: */
  m_embed=3; 
  logimax=7; 
  min_delay=1; 

  eps=1.; 
  kmax=0;
  

  for (arg=1; arg<argc; arg++)
     {
      if (!strncmp(argv[arg], "membed", 6))
	sscanf(argv[arg], "%*[^=]%*1c%d", &m_embed);
      else if (!strncmp(argv[arg], "logimax", 3))
	sscanf(argv[arg], "%*[^=]%*1c%d", &logimax);
      else if (!strncmp(argv[arg], "mindelay", 5))
	sscanf(argv[arg], "%*[^=]%*1c%d", &min_delay);
      else if (!strncmp(argv[arg], "file", 4))
	sscanf(argv[arg], "%*[^=]%*1c%s", name);
      else 
	fprintf(stderr, "The parameter %s is not recognised.\n", argv[arg]);
    }

  /*Preparing data:*/  
  if (name[0] == '\0') /*If no filename got set...*/
    {
      
      fprintf(stderr, "You must specify a filename that doesn't start with h.\n");
      exit(1);  /*...it gives up.*/
    }
  else
    {
      fPtr = fopen(name, "r");
      if(fPtr == NULL)
	{
	  fprintf(stderr, "The file %s was not found.  Sorry.\n", name);
	  exit(1);
	}
    }



  while ( fscanf(fPtr,"%*f %f",&x) != EOF )
  {
    xdata[kmax] = x;
    kmax++;
  }

  xmax = xdata[0];
  for (i=1;i<kmax;i++)
  {
    if (xdata[i]<0) 
      if (-xdata[i]>xmax)
        xmax = -xdata[i];
    else
      if (xdata[i]>xmax)
        xmax = xdata[i];
  }
   
  for (i=0;i<kmax;i++)
    xdata[i] /= xmax;
  correl(xdata,kmax,eps,logimax,m_embed,min_delay,mm); 

  for(i=2;i <= m_embed; i++)
  {
/* open the files with name "name+sExtension") */
    sprintf(sExtension,"%d", i);
    sprintf(sFileOut,"%s",name); 
    strcat(sFileOut,"_e");
    strcat(sFileOut,sExtension); 
    fPtrOut = fopen(sFileOut,"w"); 

    fprintf(stderr,"\"Embedding Dimension=%d",i);
    fprintf(stderr," -> data saved in file: %s \" \n",sFileOut);
    dist = eps;
    for(j=0;j < 128;j++)
    {
      dist /=2.;
      if(MM(i,j) > 0 ) 
	fprintf(fPtrOut,"%e %d\n",dist,MM(i,j));  
    }
    fclose(fPtrOut);
  } 
}










