#include "types.h"

#include "base.h"

#include "vdp.h"
#include "vdp_pal.h"
#include "psg.h"
#include "ym2612.h"
#include "joy.h"
#include "z80_ctrl.h"
#include "bitmap.h"
#include "logo_lib.h"
#include "timer.h"


// we don't want to share them
extern u16 randbase;
extern _joyEventCallback *joyEventCB;

// extern library callback function (we don't want to share them)
extern u16 VDP_doStepFading();

// main function
extern int main();


static _voidCallback *VBlankCB;
static _voidCallback *HBlankCB;

u32 VBlankProcess;
u32 HBlankProcess;


// VBlank Callback
void _vblankcallback()
{
    // joy state refresh
    JOY_update();

    // specials VBlank processing
    if (VBlankProcess)
    {
        // palette fading
        if (VBlankProcess & PROCESS_PALETTE_FADING)
        {
            if (!VDP_doStepFading()) VBlankProcess &= ~PROCESS_PALETTE_FADING;
        }

        // ...
    }

    // then call user's callback
    if (VBlankCB) VBlankCB();
}

// HBlank Callback
void _hblankcallback()
{
    // specials HBlank processing
    if (HBlankProcess)
    {
        // ...
    }

    // then call user's callback
    if (HBlankCB) HBlankCB();
}


void start()
{
    // initiate random number generator
    randbase = 0xD94B;

    VBlankCB = NULL;
    HBlankCB = NULL;
    VBlankProcess = 0;
    HBlankProcess = 0;

    // init part
    VDP_init();
    PSG_init();
    JOY_init();
    // reseting z80 also reset the ym2612
    Z80_init();

#ifndef nologo_
    {
        u16 tmp_pal[64];

        // display logo
        setBitmapMode(BITMAP_WIDTH, BITMAP_HEIGHT);

        // set palette 0 to black
        VDP_setPalette(0, palette_black);
        // get the bitmap palette
        getGenBmp16Palette(logo_lib, tmp_pal);
        // don't load the palette immediatly
        loadGenBmp16ToBitmap(logo_lib, 8, 0, 0xFF);

        // fade in logo
        VDP_fadeIn(0, tmp_pal, 30, 0);
        // wait 3 second
        wait(TICKPERSECOND * 3);
        // fade out logo
        VDP_fadeOut(0, 20, 0);
        // wait 0.5 second
        wait(TICKPERSECOND * 0.5);
    }

    // reinit vdp before program execution
    VDP_init();
#endif

    // let's the fun go on !
    main();
}


void setVBlankCallback(_voidCallback *CB)
{
    VBlankCB = CB;
}

void setHBlankCallback(_voidCallback *CB)
{
    HBlankCB = CB;
}

