#include "types.h"

#include "timer.h"

#include "maths.h"
#include "vdp.h"


u32 vtimer;


// return elapsed ticks from console reset (1/76800 seconde based)
u32 getTick()
{
    u32 vcnt;
    u32 current;

    vcnt = GET_VCOUNTER;
    if (vcnt >= 224) vcnt -= 224;
    else vcnt += (256 - 224);
    current = (vtimer << 8) + vcnt;

    if (ISPALSYSTEM) return (current << 2) + (current << 1);     // current * 6
    else return (current << 2) + current;   // current * 5
}

// return elapsed time from console reset (1/256 seconde based)
u32 getTime()
{
    return getTick() / 300;
}

fix32 getTimeAsFix32()
{
#if (FIX32_FRAC_BITS > 8)
    return (getTick() / 300) << (FIX32_FRAC_BITS - 8);
#else
    return (getTick() / 300) >> (8 - FIX32_FRAC_BITS);
#endif
}

void wait(u32 tick)
{
    u32 start;

    start = getTick();
    // wait until we reached tick
    while ((getTick() - start) < tick);
}

