/* pi - faaaaasssstcopyright
  solon luigi lutz - solon@pyro.de
  permission to use this code is granted as long
  as the author is mentioned
*/

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

int main (int argc, char *argv[])
{
  unsigned int a=10000,b,c,d=0,e=0,g,h=0,i=0;
  long siz,n,line=0;
  unsigned short *f;
  const char *copyright = "       (C) by Solon Luigi Lutz - solon@pyro.de\n"
                          "       Cleanup by Georg Wiora 12-FEB-1998.\n";

  if (argc != 2)
   {
    printf ("Usage: PiLuigi <N-Digits>\n Calculate Pi to N digits\n%s",copyright);
    return 5;
   }

  printf (copyright);

  /* Number of digits */
  n = atol(argv[1]);

  /* Memsize */
  c = siz = ((n >> 2)+1)*14;

  /* Alloc array */

  if ((f = (unsigned short*)malloc(siz*sizeof(*f))) == NULL)
   {
    printf("Error: No memory (%ld Bytes)!\n",siz);
    return 20;
   }

  printf ("%d digits of Pi:\n",n);

  /* Calculation Loop starts here */
  for(;;)
   {
    b = c;
    if ((c -=14) == 0)      break;

    while ( --b !=0)
     {
      d = a* ( i ? f[b]:2000)+ h*b;
      g = b *2 -1;
      h = d / g;
      f[b] = (unsigned short)(d - h * g);
     }

    i = 1;
    printf("%04d",e+d/a);
    e = d % a;line += 4;

    if (line > 76)
     {
      putchar('\n');line=0;
     }
   }

  /* Free array */
  free(f);

  printf("\n\n Finished.\n");

  return 0;
}
