
#include "shared.h"

void pad_shutdown(void)
{
    IOSEL   = 0x00; /* Manual mode for both ports */
}

void pad_init(void)
{
    DDR1    = 0x60; /* TH,TR out, TL,D3-D0 in */
    DDR2    = 0x60; /* TH,TR out, TL,D3-D0 in */
    IOSEL   = 0x03; /* Manual mode for both ports */
    EXLE    = 0x00;
}

unsigned char _yabause_fix = 2;
void pad_read(pad_t *p)
{
#if 0
    uint16 temp;
    int count;
    
    PDR1 = 0x60;
    for(count=0; count < PAD_DELAY; count++)
        asm("nop");
    temp = (PDR1 & 0x08) << 12;

    PDR1 = 0x40;
    for(count=0; count < PAD_DELAY; count++)
        asm("nop");
    temp |= (PDR1 & 0x0F) << 8;

    PDR1 = 0x20;
    for(count=0; count < PAD_DELAY; count++)
        asm("nop");
    temp |= (PDR1 & 0x0F) << 4;

    PDR1 = 0x00;
    for(count=0; count < PAD_DELAY; count++)
        asm("nop");
    temp |= (PDR1 & 0x0F) << 0;

    temp ^= 0x8FFF;

    p->old = p->new;
    p->new = temp;
    p->delta = (p->new ^ p->old) & p->new;
#else
    /* Modified version for yabause compatibility. */
    unsigned char val[4];
    int count;

    PDR1 = 0x60;
    for(count=0; count < PAD_DELAY; count++)
        asm("nop");
    val[0] = PDR1 & 0x08;

    PDR1 = 0x40;
    for(count=0; count < PAD_DELAY; count++)
        asm("nop");
    val[1] = PDR1 & 0x0F;

    PDR1 = 0x20;
    for(count=0; count < PAD_DELAY; count++)
        asm("nop");
    val[2] = PDR1 & 0x0F;

    PDR1 = 0x00;
    for(count=0; count < PAD_DELAY; count++)
        asm("nop");
    val[3] = PDR1 & 0x0F;

    /* Fix for yabause: On first call, if X,Y,Z,L,R are all on, always set all of them to off. */
    if(_yabause_fix >= 2)
    {
        _yabause_fix = ((val[0] == 0) && (val[3] == 0) ? 1 : 0);
    }
    if(_yabause_fix == 1)
    {
        val[0] = 0x08;
        val[3] = 0x0F;
    }

    p->old = p->new;
    p->new = ((val[0] << 12) | (val[1] << 8) | (val[2] << 4) | (val[3] << 0)) ^ 0x8FFF;
    p->delta = (p->new ^ p->old) & p->new;
#endif
}
