#include "dmlib.h"
#include <stdio.h>

#define FP_DW_SIZE 8
#define FP_W0_SIZE 4

void check(const char *str, DMFixedPoint v, Sint64 dw)
{
    DMFixedPoint *q = (DMFixedPoint *) &dw;

    printf("%-15s = ", str); FP_PRINTF(v); printf("\n");
    printf("should be       = "); FP_PRINTF((*q)); printf("\n");

    if (v.dw != dw)
    {
        printf("ERROR! A test value differs from expected!\n");
        exit(1);
    }
}

int main(int argc, char *argv[])
{
    int i;
    DMFixedPoint a, b, delta;
    char *s;

    (void) argc;
    (void) argv;

    // Check host characteristics
    switch (SDL_BYTEORDER)
    {
        case SDL_BIG_ENDIAN: s = "big endian"; break;
        case SDL_LIL_ENDIAN: s = "little endian"; break;
        default: s = "unknown?"; break;
    }
    
    printf(
    "SDL byte order            = %s (%d)\n\n", s, SDL_BYTEORDER);
    
    printf(
    "sizeof(DMFixedPoint)      = %d bytes\n"
    "sizeof(DMFixedPoint.dw    = %d bytes (should be %d)\n"
    "sizeof(DMFixedPoint.w[0]  = %d bytes (should be %d)\n",
    sizeof(a), sizeof(a.dw), FP_DW_SIZE,
    sizeof(a.w[0]), FP_W0_SIZE);
    
    if (sizeof(a.dw) != FP_DW_SIZE || sizeof(a.w[0]) != FP_W0_SIZE)
    {
        printf("ERROR! Some type sizes DO NOT MATCH!\n");
        return -1;
    }
    
    // TEST #1
    printf("\nTEST #1: set initial values\n");
    FP_SETHL(a, 55, 0);
    check("a", a, 0x0000003700000000ULL);

    FP_CONV(b, 178);
    check("b", b, 0x00000000000000b2ULL);

    FP_DIV_R(delta, a, b);
    check("delta", delta, 0x000000004f19e33cULL);

    // Test #2
    printf("\nTEST #2: 50 x (a + delta)\n");
    for (i = 0; i < 50; i++)
    {
        FP_ADD(a, delta);
    }
    check("a end", a, 0x00000046730e61b8ULL);


    // Test #3
    printf("\nTEST #3: 50 x (a - delta)\n");
    for (i = 0; i < 50; i++)
    {
        FP_SUB(a, delta);
    }
    check("a end", a, 0x0000003700000000ULL);

    // Test #4
    printf("\nTEST #4: 5 x (a * delta)\n");
    for (i = 0; i < 5; i++)
    {
        FP_MUL(a, delta);
    }
    check("a end", a, 0xd644e40000000000ULL);

    // Test #5
    printf("\nTEST #4: 2 x (a / delta)\n");
    for (i = 0; i < 2; i++)
    {
        FP_DIV(a, delta);
    }
    check("a end", a, 8ULL);

    return 0;
}
