/***************************************************************************

    M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
    Win32 Portions Copyright (C) 1997-98 Michael Soderstrom and Chris Kirmse

    This file is part of MAME32, and may only be used, modified and
    distributed under the terms of the MAME license, in "readme.txt".
    By continuing to use, modify or distribute this file you indicate
    that you have read the license and understand and accept it fully.

 ***************************************************************************/

/***************************************************************************

  uclock.c

 ***************************************************************************/

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <time.h>
#include <mmsystem.h>
#include "ticker.h"

/***************************************************************************
    External variables
 ***************************************************************************/

LONGLONG TICKS_PER_SEC = -1;

/***************************************************************************
    Internal variables
 ***************************************************************************/

static BOOL bHavePerformanceCounter;
static BOOL bSleep;

/***************************************************************************
    External functions
 ***************************************************************************/

#ifdef KAILLERA
static TICKER adder = 0;

void addTick(TICKER a)
{
    adder += a;
}
#endif /* KAILLERA */

TICKER ticker(void)
{
    LARGE_INTEGER   tick_count;

    if (bHavePerformanceCounter == TRUE)
    {
        QueryPerformanceCounter(&tick_count);
#ifdef KAILLERA
        return tick_count.QuadPart - adder;
#else /* KAILLERA */
        return tick_count.QuadPart;
#endif /* KAILLERA */
    }
    else
    {
#ifdef KAILLERA
        TICKER a = timeGetTime();
        return a - adder;
#else /* KAILLERA */
        return timeGetTime();
#endif /* KAILLERA */
    }
}

int ticker_init(options_type *osd_options)
{
    LARGE_INTEGER tick_frequency;
    MMRESULT      hResult;

#ifdef KAILLERA
    adder = 0;
#endif /* KAILLERA */

    bSleep = osd_options->use_sleep;
    if (!osd_options->disable_pcounter)
        bHavePerformanceCounter = QueryPerformanceFrequency(&tick_frequency);
    else
        bHavePerformanceCounter = FALSE;

    if (bSleep || !bHavePerformanceCounter)
    {
        hResult = timeBeginPeriod(1);
        if (hResult == TIMERR_NOCANDO)
            return 1;
    }

    if (bHavePerformanceCounter)
        TICKS_PER_SEC = tick_frequency.QuadPart;
    else
        TICKS_PER_SEC = CLOCKS_PER_SEC;

    return 0;
}

int ticker_exit(void)
{
    TICKS_PER_SEC = -1;

    if (bSleep || !bHavePerformanceCounter)
    {
        MMRESULT hResult;

        hResult = timeEndPeriod(1);
        if (hResult == TIMERR_NOCANDO)
            return 1;
    }
    return 0;
}
