
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>
#include <sys/mman.h>
#include <unistd.h>

#include "gp2x.h"

void set_FCLK(unsigned MHZ)
{
    unsigned v;
    unsigned mdiv,pdiv=3,scale=0;
    volatile unsigned short *MEM_REG;

    MEM_REG=(unsigned short *)mmap(0, 0x10000, PROT_READ|PROT_WRITE, MAP_SHARED, open("/dev/mem", O_RDWR), 0xc0000000);
    MHZ*=1000000;
    mdiv=(MHZ*pdiv)/SYS_CLK_FREQ;

    mdiv=((mdiv-8)<<8) & 0xff00;
    pdiv=((pdiv-2)<<3) & 0xfc; /* <-- should be << 2 */
    scale&=3;
    v=mdiv | pdiv | scale;
    MEM_REG[0x910>>1]=v;
}

int gp2x_getvol()
{
    int mixer,tmp;

    mixer=open("/dev/sound/mixer",O_RDONLY);
    ioctl(mixer,MIXER_READ(SOUND_MIXER_PCM),&tmp);
    close(mixer);

    return tmp;
}

void gp2x_setvol(int left,int right)
{
    int mixer,tmp=right*256+left;

    mixer=open("/dev/sound/mixer",O_WRONLY);
    ioctl(mixer,SOUND_MIXER_WRITE_PCM,&tmp);
    close(mixer);
}

void gp2x_menu(void)
{
    chdir("/usr/gp2x");
    execl("/usr/gp2x/gp2xmenu", "/usr/gp2x/gp2xmenu", NULL);
}
