#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include "ntp_fp.h"
char *dofptoa_(u_fp fpv);

unsigned int xorshift32(unsigned int *c) {
    unsigned int x = *c;
    x ^= x >> 13; // a
    x ^= x <<  5; // b
    x ^= x >> 19; // c
    x = x * 747796405U;
    *c = x;
    return x;
}

#if 0
char *
hacky_fptoa(u_fp fpv)
{
    static char buf[25]; 
	register uint32_t i = 0, val = fpv, val2;
	short dec = 6;
	u_char cbuf[12] = {0};
	register u_char *cp, *cpdec, *cpend;

	/*
	 * Set the pointers to point at the first
	 * decimal place.  Get a local copy of the value.
	 */
	cp = cpend = &cbuf[5];

	/*
	 * If we have to, decode the integral part
	 */
	if (!(val & 0xffff0000)) {
	    cp--;
	} else {
		uint16_t sv = (val >> 16);
		do {
			uint16_t tmp = sv;
			sv = (sv/10U);
			*(--cp) = (u_char)(tmp - 10*sv);
		} while (sv != 0);
	}

	cp = cpend = &cbuf[11];
    val2 = ((val << 16) / 1000U);
	if (!(val2 & 0xffff0000)) {
	    cp--;
	} else {
		uint16_t sv = (val2 >> 16);
		do {
			*(--cp) = (u_char)(sv%10);
			sv = (sv/10U);
		} while (sv != 0);
	}
	*(--cp) = '.';

	/*
	 * Copy it into the buffer, asciizing as we go.
	 */
	i = 0;
	while (cp < cpend) {
		if (*cp == '.'){ 
		    buf[i++] = (char)(*cp++);
        } else{  
		    buf[i++] = (char)(*cp++ + '0');
        }
	}
	buf[i++] = '\0';
	return buf;
}
#endif

char *
hacky_fptoa(u_fp fpv)
{
    static char buf[25]; 
	register uint32_t i = 0, val = fpv, val2;
    //val2 = ((((val&0xffff) * 15625) + 0x100) >> 10);
    val2 = ((((val&0xffff) * 3125) + 0x400) >> 11);
    snprintf(buf, 24, "%5u.%05u", (val >> 16), val2);
    return buf;
}

int main(void) {
    unsigned int i, j;
    unsigned int c = time(0);
    char *buf1 = NULL, *buf2 = NULL;

    setvbuf(stdout, NULL, _IONBF, 0);

    for (i = 0; i < 256; i++) {
        j = xorshift32(&c);
        //dofptoa(j, 0, 6);
        buf1 = hacky_fptoa(j);
        buf2 = dofptoa_(j);

        printf("%s, %s\n", buf1, buf2);
    }

    return 0;
}

