  'http://rosettacode.org/wiki/Pi#Pascal
  'http://www.pi314.net/eng/goutte.php
     
  /*
  A spigot algorithm for the digits of pi, 
  Stanley Rabinowitz and Stan Wagon
  */
     
  uses console
     
  function Pi_Spigot(int n) as string
  ===================================
  int  count, idx, c, i, j, k, q, x, nines, predigit
  '
  'recursive series (2+n/(2n+1)*(next))
  'shifting base 2.222222222 ...
  '
  'count    pi source digit count
  'edx      register containg remainder after '\'
  'idx      digit base10 index
  'a[]      pi source digits (moving base)
  'c        thousands counter
  'i        pre carry iterator
  'j        main iterator
  'k        nines iterator
  'nines    count of consecutive '9' digits
  'predigit raw digit
  'q        carry
  's        pi string
  'ss       pi digits array
  'x      
     
  count = 10*n \ 3
  redim uint a(count)
  string s = nuls n 
  byte ss at strptr s 'overlay

  for j = 1 to count 
    a[j] = 2  'Start with 2s
  next j
  nines = 0
  predigit = 0  'First predigit is a 0
  for j = 1 to n
    if ++c=100 then c=0 : print j cr 'display progress

    'Only calculate as far as needed 
    '+16 for security digits ~5 decimals
    int e = (n-j)*10 \ 3 +16
    if e > count then e = count
    int d=e+e-1
    q = 0
    for i=e to 1 step -1  'Work backwards
      x  = 10*a[i] + q*i
      q = x \ d 'carry
      a[i] = edx 'remainder: mod(x,2*i - 1)
      d-=2
     next

    q\=10
    a[1] = edx 'remainder
    select q
    case 9  :
      nines++
    case 10 :
      idx++ : ss[idx]=predigit+1
      for k = 1 to nines
        idx++ : ss[idx]=0
      next k
      predigit = 0
      nines = 0
    case else      
      if j > 1 then idx++ : ss[idx]=predigit
      predigit = q
      if nines then
        for k = 1 to nines
          idx++ : ss[idx]=9
        next k
        nines = 0
      end if
   end select
  next j
  idx++ : ss[idx]=predigit 'final predigit
  if nines then 'remaining nines
    for k = 1 to nines
      idx++ : ss[idx]=9
    next k
    nines = 0
  end if
  'to ascii
  for j=1 to len s
    ss[j]+=48
  next
  return s
    end function

  'MAIN
  =====     
  cls
  print "This will calculate pi and save the result as a text file"
  do
    printl ""
    printl "How many digits? "
    int num=val(rtrim ltrim input())
    if num num<=0 then exit do 'finish
    string s=Pi_Spigot(num)
    int i
    for i=1 to len(s) step 100
      print i tab mid(s,i,100) cr
    next
    putfile("pi.txt",s)  
     
    printl
    printl "Saved as pi.txt"
  end do
     