//#DOC Main, program entry and main loop
#include "main.h"
#include <otSerial.h>
#include <otTimer.h>
#include <otPrintf.h>
#include <otMalloc.h>

void setup()
{
    UartEnableSignals(UART0);
    UartSetBaud(UART0, 115200);
    _initMalloc();
    setStdout(4096, UART0);   // printf output is now directed on UART0
    TimerSetAsCounter(TIMER0);
    TimerEnable(TIMER0, true);
}

FAST_CODE_1 void loop()
{
    long    * r, i, k, b, d, c = 0, st, et;
    
    DelayMs(2000);   // Wait terminal start
    
    r = (long *) _malloc(sizeof(long) * 2801);
    for(i = 0; i < 2800; i++)
        r[i] = 2000;

    printf("print 800 digits of pi:\n");
    st = TimerGetCounts(TIMER0);
    for(k = 2800; k > 0; k = k - 14)
    {
        d = 0;
        i = k;
        while(i)
        {
            d = d + r[i] * 10000;
            b = 2 * i - 1;
            r[i] = d % b;
            d = d / b;
            i--;
            if(i)
                d = d * i;
        }
        printf("%04d ", c + d / 10000);
        c = d % 10000;
    }
    et = TimerGetCounts(TIMER0);
    printf("\nElapsed time: %umS\n", ElapsedTimeUs(st, et) / 1000);
    // From wikipedia
    printf("3141 5926 5358 9793 2384 6264 3383 2795 0288 4197 1693 9937 5105 8209 7494 4592 3078 1640 6286 2089 9862 8034 8253 4211 7067 9\n");
    _free(r);
    
    IDLE;
}