#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>

#define TRUE 1

#include "compthreads.cpp"
#include "qcborwein.cpp"

int
main (int argc, char *argv[])
{
  FILE *fp;
  char *pistr;
  mp_exp_t expvar;
  unsigned long long prec = 4, bits, i = 0, n = 1, xdigits;
  int iter, thread = 0, k = 0;
  char column[111] = "";
	
	if (argc == 1)
	  {
	  	printf ("Invalid number of iterations \n");
	    return 0;
	  }  

/* The number of iterations */	
	iter = atoi (argv[1]);
	
	 if (iter < 4)
    iter = 4;

  /*
   * Calculate the precision xdigits 
   */

  for (i = 0; i < iter - 1; i++)
    prec += prec;

  xdigits = prec;
  bits = (unsigned long long) (prec * 3.33);
  printf (" Calculating %ld digits of pi\n", (unsigned long) xdigits);
  
  /*
   * Initialize the mpf's 
   */
  mpf_set_default_prec (bits);
 
  borwein_initialize((void *) &thread); /* Initialize the borwein's algorithm */
  printf (" Iteration: %2d -> %9d Borwein digits calculated\n", 0, 2);
  
  /* The Borwein's iterations */
  i = 0;
  prec = 4;
  
  
  while (i < (iter - 1))
    {
      borwein_calculate ((void *) &thread); /* Calculate using the borwein's algorithm */
      printf (" Iteration: %2d -> %9d Borwein digits calculated\n", i + 1, prec);
      prec += prec;
      i++;
    }  
  printf (" Iteration: %2d -> %9d Borwein digits calculated\n", i + 1, prec);
    
  borwein_finalize ((void *) &thread);	
  
  /* Create CPUPI.DAT */
  printf (" Creating CPUPI.DAT...");
  
  pistr = (char *) malloc (prec + 100);
  mpf_get_str (pistr, &expvar, 10, prec + 10, bd[0].p2);
  fp = fopen ("CPUPI.DAT", "w");
  
  fprintf (fp, " PI=3.%c%c", 10, 13);
      memset (column, ' ', 110);
      column[110] = 0;
      k = 0;
      n = 1;
      for (i = 1; i < prec; i += 10)
	{
	  memcpy (&column[n], &pistr[i], 10);
	  n += 11;
	  if (n > 110)
	    {
	      fprintf (fp, "%s%c%c", column, 10, 13);
	      n = 1;
	      k++;
	      if (k == 10)
		{
		  fprintf (fp, " %c%c", 10, 13);
		  k = 0;
		}
	    }
	}
	   n = 1;
	   i = prec - (prec % 100) + 1;
	   memset (column, ' ', 110);
	   for (; i < prec + 1; i++)
	     {
	     	column[n] = pistr[i];
	     	n++;
	     	if ((n % 11) == 0)
	     	  {
	     	  	column[n] = ' ';
	     	  	n++;
		      }	
	     }	 
       fprintf (fp, "%s%c%c", column, 10, 13);

      free (pistr);
      fclose (fp);
      printf ("done!!! \n\n");

  	
  return 0;
	  
}
