#include <p_std.h>
#include <p_file.h>
#include <epoc.h>

/* Sound demo: plays the ice cream van tune at various
   beat per minute ... */

GLDEF_C VOID waitstat2(WORD *pstat1, WORD *pstat2)
/*
Wait for *pstat!=E_FILE_PENDING and *pstat2 != E_FILE_PENDING
*/
    {
    INT i;

    i = -1;
    do
        {
        p_iowait();
        i++;
        }
        while (*pstat1 == E_FILE_PENDING && *pstat2 == E_FILE_PENDING);

    if (*pstat2 == E_FILE_PENDING)
        pstat1 = pstat2;
    p_waitstat(pstat1);

    while (i--)
        p_iosignal();
    }


GLDEF_C VOID play_notes(WORD *buf1, WORD *buf2, WORD l1, WORD l2, INT volume, INT beatsPerMinute)
    {
    VOID *pcb;
    WORD sndstat1,sndstat2;
    E_SOUND sound;
    INT err;

    if ((err=p_open(&pcb,"SND:",-1)) < 0)
        {
        p_close(pcb);
        p_exit(err);
        }

    if ((err=p_iow3(pcb,P_FSENSE,&sound)) < 0)
        {
        p_close(pcb);
        p_exit(err);
        }

    if (beatsPerMinute >= 0)
        sound.beatsPerMinute = (UBYTE) beatsPerMinute;

    if (volume >= 0)
        sound.volume = (UBYTE) volume;

    if ((err=p_iow3(pcb,P_FSET,&sound)) < 0)
        {
        p_close(pcb);
        p_exit(err);
        }

    p_ioc5(pcb,E_FSSOUNDCHANNEL1,&sndstat1,&buf1[0],&l1);
    p_ioc5(pcb,E_FSSOUNDCHANNEL2,&sndstat2,&buf2[0],&l2);
    waitstat2(&sndstat1,&sndstat2);
    
    p_close(pcb);

    if (sndstat1 != 0 || sndstat1 != 0)
        p_exit(0);
}

GLDEF_C INT main(VOID)
{
    WORD notes1[] = {1048,24,524,12};
    WORD notes2[] = {1048,4,1320,4,1568,4,2092,4,1568,4,1320,4,1048,12};
    WORD len1 = sizeof(notes1)/4,len2 = sizeof(notes2)/4;
    INT i;

    for (i = 0; i < 6; i++)
        {
        play_notes(&notes1[0],&notes2[0],len1,len2,i,-1);
        p_sleep(1);
        }
    
    for (i = 0; i < 6; i++)
        {
        play_notes(&notes1[0],&notes2[0],len1,len2,-1,140+i*20);
        p_sleep(1);
        }

    return(0);
}

