/*---------------------------------------------------------------------------*
  Project:  NitroSDK - demos - perf
  File:     main.c

  Copyright 2003-2006 Nintendo.  All rights reserved.

  These coded instructions, statements, and computer programs contain
  proprietary information of Nintendo of America Inc. and/or Nintendo
  Company Ltd., and are protected by Federal copyright law.  They may
  not be disclosed to third parties or copied or duplicated in any form,
  in whole or in part, without the prior written consent of Nintendo.

 *---------------------------------------------------------------------------*/

#include    <nitro.h>
#include    <nitro/spi/ARM9/tp.h>
#include    <string.h>
#include    <ios.h>
#include    <fs.h>
#include    <es.h>
#include    <tp_ipc.h>
#include    "data.h"

#define USB_DEBUG
#ifdef USB_DEBUG
#define LOGPRINT(s, args...)	printf(s, ## args)
#else
#define LOGPRINT(s, args...)	OS_Printf(s, ## args)
#endif

#define MIN(a, b)  ((a) < (b) ? (a) : (b))

size_t strnlen(const char *str, size_t n);

void print64(const char *, u64);

void
print64(const char *name, u64 arg)
{
    u32 argLo;
    u32 argHi;

    argHi = (u32) ((arg & 0xffffffff00000000LL) >> 32);
    argLo = (u32) (arg & 0xffffffffLL);
    LOGPRINT("%s Hi 0x%x Lo 0x%x\n", name, argHi, argLo);
}

/*---------------------------------------------------------------------------*
    Prototype definition
 *---------------------------------------------------------------------------*/
static void VBlankIntr(void);


/*---------------------------------------------------------------------------*
    Static variables definition
 *---------------------------------------------------------------------------*/
static GXOamAttr gOam[128];


/*---------------------------------------------------------------------------*
  Name:         SetPoint16x16

  Description:  Display a 16x16 OBJ on indicated point.

  Arguments:    x - position X.
                y - position Y.

  Returns:      None.
 *---------------------------------------------------------------------------*/
static inline void SetPoint16x16(u16 pos_x, u16 pos_y)
{
    G2_SetOBJAttr(&gOam[0],            // OAM number
                  pos_x - 8,           // X position
                  pos_y - 8,           // Y position
                  0,                   // Priority
                  GX_OAM_MODE_BITMAPOBJ,        // Bitmap mode
                  FALSE,               // mosaic off
                  GX_OAM_EFFECT_NONE,  // affine off
                  GX_OAM_SHAPE_16x16,  // 16x16 size
                  GX_OAM_COLOR_16,     // 16 color
                  1,                   // charactor
                  15,                  // alpha
                  0);
}


/*---------------------------------------------------------------------------*
  Name:         DisplayInit

  Description:  Graphics Initialization

  Arguments:    None.

  Returns:      None.
 *---------------------------------------------------------------------------*/
static void DisplayInit()
{
    GX_Init();
    FX_Init();

    GX_DispOff();
    GXS_DispOff();
    GX_SetDispSelect(GX_DISP_SELECT_SUB_MAIN);

    OS_SetIrqFunction(OS_IE_V_BLANK, VBlankIntr);
    (void)OS_EnableIrqMask(OS_IE_V_BLANK);
    (void)OS_EnableIrq();
    (void)GX_VBlankIntr(TRUE);         // to generate V-Blank interrupt request

    GX_SetBankForLCDC(GX_VRAM_LCDC_ALL);
    MI_CpuClearFast((void *)HW_LCDC_VRAM, HW_LCDC_VRAM_SIZE);

    (void)GX_DisableBankForLCDC();

    MI_CpuFillFast((void *)HW_OAM, 192, HW_OAM_SIZE);   // clear OAM
    MI_CpuClearFast((void *)HW_PLTT, HW_PLTT_SIZE);     // clear the standard palette

    MI_CpuFillFast((void *)HW_DB_OAM, 192, HW_DB_OAM_SIZE);     // clear OAM
    MI_CpuClearFast((void *)HW_DB_PLTT, HW_DB_PLTT_SIZE);       // clear the standard palette

    GX_SetBankForOBJ(GX_VRAM_OBJ_256_AB);       // Set VRAM-A,B for OBJ

    GX_SetGraphicsMode(GX_DISPMODE_GRAPHICS,    // 2D / 3D Mode
                       GX_BGMODE_0,    // BGMODE 0
                       GX_BG0_AS_2D);  // Set BG0 as 2D

    GX_SetVisiblePlane(GX_PLANEMASK_OBJ);       // make OBJ visible
    GX_SetOBJVRamModeBmp(GX_OBJVRAMMODE_BMP_1D_128K);   // 2D mapping OBJ

    /* Load character bitmap data*/
    GX_LoadOBJ((const void *)IMAGE_DATA, 0, IMAGE_DATA_SIZE);   // Transfer OBJ bitmap data to VRAM

    OS_WaitVBlankIntr();               // Waiting the end of V-Blank interrupt
    GX_DispOn();

}

u8 ctrdg_buf[4096];
ESTitleId titleId;
char dataDir[] = ES_TITLE_DATA_DIR;

#define OS_GetPRAddress(regno) (OS_GetProtectionRegion##regno##() & HW_C6_PR_BASE_MASK)
#define OS_GetPRSize(regno) (OS_GetProtectionRegion##regno##() & HW_C6_PR_SIZE_MASK)

static char *szname[] = {
    "4KB",
    "8KB",
    "16KB",
    "32KB",
    "64KB",
    "128KB",
    "256KB",
    "512KB",
    "1MB",
    "2MB",
    "4MB",
    "8MB",
    "16MB",
    "32MB",
    "64MB",
    "128MB",
    "256MB",
    "512MB",
    "1GB",
    "2GB",
    "4GB",
    "UNK"
};

static void
__decodePRval(int reg, u32 val)
{
    u32 addr = val & HW_C6_PR_BASE_MASK;
    u32 size = val & HW_C6_PR_SIZE_MASK;
    int enable = (int)val & 1;
    int szidx;

    szidx = (int) (size>>1) - 11;
    if (szidx >= sizeof szname/sizeof szname[0])
        szidx = sizeof szname/sizeof szname[0] - 1;

    LOGPRINT("Region %d = 0x%08x size %s (%s)\n",
               reg, addr, szname[szidx], enable ? "enabled" : "disabled");
}

/*
 * The equivalent of "mkdir -p" (stolen from ES)
 */
static IOSError
__CreateDir(const u8* name, u32 fileAttr, u32 ownerAcc, u32 groupAcc, u32 othersAcc)
{
    IOSError rv = IOS_ERROR_OK;
    u32 num;
    u8 dir[ISFS_PATH_MAXLEN];
    char* slash;
    char* last;

    rv = ISFS_ReadDir(name, NULL, &num);
    if (rv==ISFS_ERROR_NOEXISTS) {
        memset(dir, 0, ISFS_PATH_MAXLEN);
        slash = strchr((char *)name, '/');
        last = slash + strnlen(slash, ISFS_PATH_MAXLEN) + 1;
        while (slash<last) {
            slash = strchr(slash+1, '/');
            slash = (slash==0) ? last : slash;
            strncpy((char *)dir, (char *)name, slash-(char *)name);
            rv = ISFS_ReadDir(dir, NULL, &num);
            if (rv==ISFS_ERROR_NOEXISTS) {
                rv = ISFS_CreateDir(dir, fileAttr, ownerAcc, groupAcc, othersAcc);
                if (rv!=ISFS_ERROR_OK) {
                    LOGPRINT("create dir %s failed: %d\n", dir, rv);
                    goto out;
                }
                LOGPRINT("created dir %s\n", dir);
            } else if (rv==ISFS_ERROR_OK) {
                rv = ISFS_SetAttr(dir, IOS_ROOT_ID, IOS_ROOT_GROUP, fileAttr, ownerAcc, groupAcc, othersAcc);
                if (rv!=ISFS_ERROR_OK) {
                    goto out;
                }
            } else {
                goto out;
            }
        }
    } 

out:
    return rv;
}

#define TMP_DIR "/tmp"

/*
 * Update a file atomically (stolen from ES)
 */
static IOSError
__WriteFile(const u8* name, u32 fileAttr, u32 ownerAcc, u32 groupAcc, u32 othersAcc, const u8* data, u32 size)
{
    IOSError rv = IOS_ERROR_OK;
    IOSFd fd = -1;
    char* last;
    u8 tmpName[]="/tmp/000000000000";
    u8 dir[ISFS_PATH_MAXLEN];
    int bytes;

    last = strrchr((char *)name, '/');
    strncpy((char *)tmpName+sizeof(TMP_DIR), last+1, ISFS_INODE_NAMELEN);

    /* write to /tmp */
    LOGPRINT("Deleting %s\n", tmpName);
    (void) ISFS_Delete(tmpName);
    rv = ISFS_CreateFile(tmpName, fileAttr, ownerAcc, groupAcc, othersAcc);
    if (rv!=ISFS_ERROR_OK && rv!=ISFS_ERROR_EXISTS) {
        LOGPRINT("create file %s failed: %d\n", tmpName, rv);
        goto out;
    }
    LOGPRINT("Create %s ret %d\n", tmpName, rv);
    fd = ISFS_Open(tmpName, ISFS_WRITE_ACCESS);
    if (fd<0) {
        LOGPRINT("open file %s failed: %d\n", tmpName, fd);
        rv = fd;
        goto out;
    }
    bytes = ISFS_Write(fd, data, size);
    if (bytes!=size) {
        LOGPRINT("write file %s failed: %d size %d\n", tmpName, bytes, size);
        rv = ES_ERR_FILE_WRITE_FAILED;
        goto out;
    }
    rv = ISFS_Close(fd);
    fd = -1;
    if (rv!=ISFS_ERROR_OK) {
        LOGPRINT("close file %s failed %d\n", tmpName, rv);
        goto out;
    }
    LOGPRINT("wrote file %s %d\n", tmpName, bytes);

    /* create dirs if they don't exist */
    memset(dir, 0, ISFS_PATH_MAXLEN);
    strncpy((char *)dir, (char *)name, last-(char *)name);
    rv = __CreateDir(dir, fileAttr, ownerAcc, groupAcc, othersAcc);
    if (rv!=IOS_ERROR_OK) {
         goto out;
    }

    /* rename */
    rv = ISFS_Rename(tmpName, name);
    if (rv!=ISFS_ERROR_OK) {
        LOGPRINT("file rename failed: %d\n", rv);
        goto out;
    }
    LOGPRINT("renamed file to %s\n", name);

out:
    if (fd >= 0) {
        (void) ISFS_Close(fd);
    }
    return rv;
}

/*
 * Read a file
 */
static IOSError
__ReadFile(const u8* name, u8* data, u32 *size)
{
    IOSError rv = IOS_ERROR_OK;
    ISFSFileStats fstats;
    IOSFd fd = -1;
    int bytes;
    int rsize;

    fd = ISFS_Open(name, ISFS_READ_ACCESS);
    if (fd < 0) {
        LOGPRINT("open file %s failed: %d\n", name, fd);
        rv = fd;
        goto out;
    }
    rv = ISFS_GetFileStats(fd, &fstats);
    rsize = MIN(fstats.size, *size);
    LOGPRINT("Try to Read file %s len %d\n", name, rsize);

    bytes = ISFS_Read(fd, data, rsize);
    if (bytes != rsize) {
        LOGPRINT("Read file %s failed: %d size %d\n", name, bytes, rsize);
        rv = IOS_ERROR_INVALID;
        goto out;
    }
    (void) ISFS_Close(fd);
    fd = -1;
    *size = bytes;
    LOGPRINT("Read file %s %d\n", name, bytes);

out:
    if (fd >= 0) {
        (void) ISFS_Close(fd);
    }
    return rv;
}

static void
__StatFile(const u8 *file)
{
    ISFSFileStats fstats;
    ISFSError rv;
    int fd;

    fd = ISFS_Open(file, ISFS_READ_ACCESS);
    if (fd < 0) {
        LOGPRINT("File %s - error %d on open\n", file, fd);
    }
    rv = ISFS_GetFileStats(fd, &fstats);
    if (rv < 0) {
        LOGPRINT("File %s - error %d on file stats\n", file, rv);
    } else {
        LOGPRINT("File %s - %d bytes\n", file, fstats.size);
    }
    if (fd >= 0) {
        (void) ISFS_Close(fd);
    }
}

/*
 * Rewrite a file in place
 */
static IOSError
__RewriteFile(const u8* name, u32 size)
{
    IOSError rv = IOS_ERROR_OK;
    IOSFd fd = -1;
    int bytes;
    int total = 0;

    fd = ISFS_Open(name, ISFS_WRITE_ACCESS);
    if (fd<0) {
        LOGPRINT("open file %s failed: %d\n", name, fd);
        rv = fd;
        goto out;
    }

    while (total < size) {
        bytes = MIN(sizeof ctrdg_buf, size - total);
        rv = ISFS_Write(fd, ctrdg_buf, bytes);
        if (rv!=bytes) {
            LOGPRINT("write file %s failed: %d size %d\n", name, rv, bytes);
            rv = ES_ERR_FILE_WRITE_FAILED;
            goto out;
        }
        total += bytes;
    }

    rv = ISFS_Close(fd);
    fd = -1;
    if (rv!=ISFS_ERROR_OK) {
        LOGPRINT("close file %s failed %d\n", name, rv);
        goto out;
    }
    LOGPRINT("wrote file %s %d\n", name, bytes);

out:
    if (fd >= 0) {
        (void) ISFS_Close(fd);
    }
    return rv;
}

#define PATH "/dev/media/mp3/media/music/demo.mp3"

u8 dPath[64];
u8 audSamples[4096];

int mp3Fd = -1;
s32 totalTime;
s32 curTime;
int mp3Reads = 0;
int mp3NZSamples = 0;

void *memcpy(void *dst, const void *src, size_t n);

void openDecoder(void);
void closeDecoder(void);
void readDecoder(u32);

void
openDecoder()
{
    memcpy(dPath, PATH, sizeof(dPath));

    mp3Fd = IOS_Open((const char *)dPath, 1);

    LOGPRINT("Open of %s returns %d\n", PATH, mp3Fd);

    if (mp3Fd >= 0) {
        /* Calculate length of song in seconds */
        totalTime = IOS_Seek(mp3Fd, 0, IOS_SEEK_END);
        totalTime /= 1000;
        curTime = IOS_Seek(mp3Fd, 0, IOS_SEEK_SET);
        curTime /= 1000;
    }
    mp3Reads = 0;
    mp3NZSamples = 0;
}

void
closeDecoder()
{
    if (mp3Fd >= 0) {
        (void) IOS_Close(mp3Fd);
        mp3Fd = -1;
    }
    LOGPRINT("closeDecoder: mp3Fd closed\n");
}

void
readDecoder(u32 size)
{
    s32 rc;
    u32 *wp;

    if (mp3Fd < 0) {
        LOGPRINT("readDecoder: decoder not open\n");
        return;
    }

    rc = IOS_Read(mp3Fd, audSamples, size);
    curTime = IOS_Seek(mp3Fd, 0, IOS_SEEK_CURRENT);
    curTime /= 1000;
    mp3Reads++;
    if (mp3NZSamples < 5) {
        LOGPRINT("readDecoder: read %d ret %d\n", size, rc);
        LOGPRINT("Samples %d = %02x %02x %02x %02x %02x %02x %02x %02x\n",
            mp3Reads,
            audSamples[0],
            audSamples[1],
            audSamples[2],
            audSamples[3],
            audSamples[4],
            audSamples[5],
            audSamples[6],
            audSamples[7]);
        LOGPRINT("Samples %d = %02x %02x %02x %02x %02x %02x %02x %02x\n",
            mp3Reads,
            audSamples[8],
            audSamples[9],
            audSamples[10],
            audSamples[11],
            audSamples[12],
            audSamples[13],
            audSamples[14],
            audSamples[15]);
        wp = (u32 *)audSamples;
        if (*wp != 0) {
            mp3NZSamples++;
        }
    }
    if (rc <= 0) {
        closeDecoder();
    }

}

#define NUM_IPC_LOOPS  1000

#define IPC_PERF 1

#if defined(IPC_PERF)
extern u32 __ipcCount;
extern u64 __ipcMaxTicks;
extern u64 __ipcTotTicks;
#endif /* IPC_PERF */

void IpcPerf(void);

/*
 * Measure IPC performance
 */
void
IpcPerf(void)
{
    TPData  raw_point;
    TPData  disp_point;
    int i;
    u64 startTick;
    u64 endTick;
    u64 uSec;
    u32 uSecLo;
    u64 ticks;

    raw_point.x = 309;
    raw_point.y = 427;
    raw_point.touch = 1;
    raw_point.validity = 0;

    LOGPRINT("Measure IPC performance ...\n");
    if (!OS_IsTickAvailable()) {
        LOGPRINT("Need to init ticks ...\n");
        OS_InitTick();
    }

#if defined(IPC_PERF)
    __ipcCount = 0;
    __ipcMaxTicks = 0;
    __ipcTotTicks = 0;
#endif /* IPC_PERF */

    startTick = OS_GetTick();

    for (i = 0; i < NUM_IPC_LOOPS; i++) {
        TPi_IpcGetCalibratedPoint((TPiData *)&disp_point, (TPiData *)&raw_point);
    }

    endTick = OS_GetTick();
    ticks = endTick - startTick;
    uSec = OS_TicksToMicroSeconds(ticks);
    print64("ticks", ticks);
    print64("uSec", uSec);
    uSecLo = (u32) (uSec & 0xffffffffLL);

    LOGPRINT("Elapsed usec for %ld IPC calls = %ld\n", NUM_IPC_LOOPS, uSecLo);
#if defined(IPC_PERF)
    LOGPRINT("Total %ld IPCs for %ld IPC calls\n", __ipcCount, NUM_IPC_LOOPS);
    uSec = OS_TicksToMicroSeconds(__ipcTotTicks);
    uSecLo = (u32) (uSec & 0xffffffffLL);
    LOGPRINT("NC wait usec for %ld IPC calls = %ld\n", NUM_IPC_LOOPS, uSecLo);
    uSec = OS_TicksToMicroSeconds(__ipcMaxTicks);
    uSecLo = (u32) (uSec & 0xffffffffLL);
    LOGPRINT("Worst case NC wait usec = %ld\n", uSecLo);
#endif /* IPC_PERF */
}

static void TimeFileRead(u8 *pathName, u32 size);

static void
TimeFileRead(u8 *pathName, u32 size)
{
    OSTick startTick;
    OSTick endTick;
    u64 mSec;
    u32 mSecLo;
    OSTick ticks;
    IOSError rv = IOS_ERROR_OK;
    IOSFd fd = -1;
    int realSize = size * 1024;
    int bytes;
    int total = 0;

    (void) OS_EnableIrq();
    OS_SetTick(0LL);
#if defined(IPC_PERF)
    __ipcCount = 0;
    __ipcMaxTicks = 0;
    __ipcTotTicks = 0;
#endif /* IPC_PERF */

    startTick = OS_GetTick();

    fd = ISFS_Open(pathName, ISFS_READ_ACCESS);
    if (fd < 0) {
        LOGPRINT("open file %s failed: %d\n", pathName, fd);
        rv = fd;
        goto out;
    }

    while (total < realSize) {
        bytes = MIN(sizeof ctrdg_buf, realSize - total);
        rv = ISFS_Read(fd, ctrdg_buf, bytes);
        if (rv != bytes) {
            LOGPRINT("Read file %s failed: %d size %d\n", pathName, rv, bytes);
            goto out;
        }
        total += bytes;
    }

    rv = ISFS_Close(fd);
    fd = -1;
    if (rv != ISFS_ERROR_OK) {
        LOGPRINT("close file %s failed %d\n", pathName, rv);
        goto out;
    }

    endTick = OS_GetTick();
    ticks = endTick - startTick;
    mSec = OS_TicksToMilliSeconds(ticks);
    mSecLo = (u32) (mSec & 0xffffffffLL);
    LOGPRINT("Elapsed msec to read %dKB file = %ld\n", size, mSecLo);
#if defined(IPC_PERF)
    LOGPRINT("Total IPCs = %ld\n", __ipcCount);
    mSec = OS_TicksToMilliSeconds(__ipcTotTicks);
    mSecLo = (u32) (mSec & 0xffffffffLL);
    LOGPRINT("NC total wait msec = %ld\n", mSecLo);
    mSec = OS_TicksToMicroSeconds(__ipcMaxTicks);
    mSecLo = (u32) (mSec & 0xffffffffLL);
    LOGPRINT("Worst case NC wait usec = %ld\n", mSecLo);
#endif /* IPC_PERF */

out:
    if (fd >= 0) {
        (void) ISFS_Close(fd);
    }

}

static void TimeFileCopy(u8 *pathName, u32 size);

static void
TimeFileCopy(u8 *pathName, u32 size)
{
    OSTick startTick;
    OSTick endTick;
    u64 mSec;
    u32 mSecLo;
    OSTick ticks;

    /* Create the file with small size */

    __WriteFile(pathName, 0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS,
        ctrdg_buf, sizeof ctrdg_buf);
    
    (void) OS_EnableIrq();
    OS_SetTick(0LL);
#if defined(IPC_PERF)
    __ipcCount = 0;
    __ipcMaxTicks = 0;
    __ipcTotTicks = 0;
#endif /* IPC_PERF */
    startTick = OS_GetTick();

    /* rewrite it to bigger size */

    __RewriteFile(pathName, size * 1024);

    endTick = OS_GetTick();
    ticks = endTick - startTick;
    mSec = OS_TicksToMilliSeconds(ticks);
    mSecLo = (u32) (mSec & 0xffffffffLL);
    LOGPRINT("Elapsed msec to create %dKB file = %ld\n", size, mSecLo);
#if defined(IPC_PERF)
    LOGPRINT("Total IPCs = %ld\n", __ipcCount);
    mSec = OS_TicksToMilliSeconds(__ipcTotTicks);
    mSecLo = (u32) (mSec & 0xffffffffLL);
    LOGPRINT("NC total wait msec = %ld\n", mSecLo);
    mSec = OS_TicksToMicroSeconds(__ipcMaxTicks);
    mSecLo = (u32) (mSec & 0xffffffffLL);
    LOGPRINT("Worst case NC wait usec = %ld\n", mSecLo);
#endif /* IPC_PERF */
}

static void MeasurePerf();

static void
MeasurePerf()
{
    IOSError rv;
    u8 pathName[ISFS_PATH_MAXLEN];
  
    /* Measure IPC perf first */
    IpcPerf();
 
    rv = ES_InitLib();
    rv = ES_GetTitleId(&titleId);
    if (rv < 0) {
        LOGPRINT("ES_GetTitleId fails rv = %d\n", rv);
    }
    rv = ES_GetDataDir(titleId, dataDir);
    if (rv < 0) {
        LOGPRINT("ES_GetDataDir fails rv = %d\n", rv);
    }
    rv = ES_CloseLib();
    snprintf((char *) pathName, sizeof pathName, "%s/who.dat", dataDir);

    LOGPRINT("Measure performance ...\n");
#if 0
    if (!OS_IsTickAvailable()) {
        LOGPRINT("Need to init ticks ...\n");
        OS_InitTick();
    }
#else
    OS_InitTick();
#endif

    /* Try files of different sizes */
    TimeFileCopy(pathName, 16);
    TimeFileCopy(pathName, 32);
    TimeFileCopy(pathName, 64);
    TimeFileCopy(pathName, 128);
    TimeFileCopy(pathName, 256);
    TimeFileCopy(pathName, 512);

    TimeFileRead(pathName, 16);
    TimeFileRead(pathName, 32);
    TimeFileRead(pathName, 64);
    TimeFileRead(pathName, 128);
    TimeFileRead(pathName, 256);
    TimeFileRead(pathName, 512);

}

unsigned char dirpath[] = "/media/music";
unsigned char databuf[] = "Fan mail from some flounder?";

static void
ES_FS_Experiments()
{
    ISFSStats stats;
    ISFSError rv;
    unsigned char file[ISFS_PATH_MAXLEN];
    ISFSFileStats fstats;
    int fd;
    u8 entries[512];
    u8 *namep;
    u32 num;
    int i;
    u32 idH, idL;
    u32 val;

    stats.blockSize = -1;
    stats.freeBlocks = -1;
    rv = ISFS_GetStats(&stats);
    if (rv < 0) {
        LOGPRINT("ISFS_GetStats fails rv = %d\n", rv);
    } else {
        LOGPRINT("ISFS blockSize %d\n", stats.blockSize);
        LOGPRINT("ISFS freeBlocks %d\n", stats.freeBlocks);
        LOGPRINT("ISFS occupiedBlocks %d\n", stats.occupiedBlocks);
        LOGPRINT("ISFS freeInodes %d\n", stats.freeInodes);
        LOGPRINT("ISFS occupiedInodes %d\n", stats.occupiedInodes);
    }

    __StatFile((u8*)"/media/music/blues.mp3");

    __WriteFile((u8*)"/shared2/foo.bar", 0, 
        ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS,
        databuf, sizeof databuf);

    __StatFile((u8*)"/tmp/foo.bar");
    __StatFile((u8*)"/shared2/foo.bar");

    num = sizeof entries;
    rv = __ReadFile((u8*)"/shared2/foo.bar", entries, &num);
    LOGPRINT("ReadFile %s ret %d (num %d)\n", "/shared2/foo.bar", rv, num);
    rv = __WriteFile((u8*)"/shared2/boo.hoo", 0, 
        ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS,
        entries, num);

    LOGPRINT("WriteFile %s ret %d\n", "/shared2/boo.hoo", rv);

    rv = ISFS_ReadDir(dirpath, NULL, &num);
    LOGPRINT("ReadDir %s ret %d (num %d)\n", dirpath, rv, num);

    if (rv == ISFS_ERROR_OK) {
        if (num * (ISFS_INODE_NAMELEN+1) > sizeof(entries)) {
            LOGPRINT("Directory buffer too small (%d entries)\n", num);
        } else {
            memset((void *)entries, 0, sizeof(entries));
            LOGPRINT("About to call ReadDir %s\n", dirpath);
            rv = ISFS_ReadDir(dirpath, entries, &num);
            LOGPRINT("ReadDir %s %x ret %d (num %d)\n", dirpath, entries, rv, num);
            namep = entries;
            for (i = 0; i < num; i++) {
                int fd;
                snprintf((char *)file, sizeof file, "%s/%s", dirpath, namep);
                LOGPRINT("%s", file);
                fd = ISFS_Open(file, ISFS_READ_ACCESS);
                if (fd < 0) {
                    LOGPRINT(" - error %d on open\n", fd);
                    continue;
                }
                rv = ISFS_GetFileStats(fd, &fstats);
                if (rv < 0) {
                    LOGPRINT(" - error %d on file stats\n", rv);
                } else {
                    LOGPRINT(" %d bytes\n", fstats.size);
                }
                namep = (u8 *)strchr((char *)namep, NULL) + 1;
            }
        }
    } else {
        LOGPRINT("Directory %s not found (rv = %d)\n", dirpath, rv);
    }

    rv = ES_InitLib();
    LOGPRINT("ES_InitLib rv = %d\n", rv);

    rv = ES_GetTitleId(&titleId);
    if (rv < 0) {
        LOGPRINT("ES_GetTitleId fails rv = %d\n", rv);
    } else {
        idH = titleId >> 32;
        idL = titleId & 0xffffffff;
        LOGPRINT("Title Id = %08x:%08x\n", idH, idL);
    }

    rv = ES_GetDataDir(titleId, dataDir);
    if (rv < 0) {
        LOGPRINT("ES_GetDataDir fails rv = %d\n", rv);
    } else {
        LOGPRINT("Data Dir = %s\n", dataDir);
    }

    rv = ES_CloseLib();
    LOGPRINT("ES_CloseLib rv = %d\n", rv);
}

/*
 * Routine to test cartridge access
 */
static void
Cartridge_Init(void)
{
    ISFSStats stats;
    ISFSError rv;
    unsigned char file[ISFS_PATH_MAXLEN];
    ISFSFileStats fstats;
    int fd;
    u32 *ctrp;
    u32 *memp;
    u8 *bp;
    u16 *sp;
    int i;
    u32 idH, idL;
    u32 val;
    unsigned char entries[512];
    unsigned char *namep;
    u32 num;

    LOGPRINT("Initialize GBA Cartridge Interface\n");

    CTRDG_Init();
    CTRDG_Enable(TRUE);
    MI_CpuClear8(ctrdg_buf, sizeof ctrdg_buf);

    /*
     * Set slowest timings for both ROM and RAM
     */
    MI_SetCartridgeRomCycle1st(MI_CTRDG_ROMCYCLE1_18);
    MI_SetCartridgeRomCycle2nd(MI_CTRDG_ROMCYCLE2_6);
    MI_SetCartridgeRamCycle(MI_CTRDG_RAMCYCLE_18);

    LOGPRINT("Protection Unit Regions\n");
    val = OS_GetProtectionRegion0();
    __decodePRval(0, val);
    val = OS_GetProtectionRegion1();
    __decodePRval(1, val);
    val = OS_GetProtectionRegion2();
    __decodePRval(2, val);
    val = OS_GetProtectionRegion3();
    __decodePRval(3, val);
    val = OS_GetProtectionRegion4();
    __decodePRval(4, val);
    val = OS_GetProtectionRegion5();
    __decodePRval(5, val);
    val = OS_GetProtectionRegion6();
    __decodePRval(6, val);
    val = OS_GetProtectionRegion7();
    __decodePRval(7, val);

    val = OS_GetIPermissionsForProtectionRegion();
    LOGPRINT("Region I permissions = %08x\n", val);
    val = OS_GetDPermissionsForProtectionRegion();
    LOGPRINT("Region D permissions = %08x\n", val);

    /*
     * Experiment with poking around in cartridge space
     */
    memp = (u32 *) ctrdg_buf;
    ctrp = (u32 *) HW_CTRDG_ROM;  /* beginning of GBA cartridge space */

    for (i = 0; i < 32; i++) {
        if (CTRDG_Read32(ctrp, memp) == 0) {
            LOGPRINT("CTRDG_Read32 failed with i = %d\n", i);
            break;
        }
        LOGPRINT("0x%x = 0x%x\n", ctrp, *memp);
        ctrp++, memp++;
    }

    LOGPRINT("CTRDG_Read32 returns %d words\n", i);

    /*
     * Try word writes
     */
#define TEST_BASE (0x08000000 + 64 * 1024)
    ctrp = (u32 *)(TEST_BASE - 16);
    if (CTRDG_Read32(ctrp, memp) == 0) {
        LOGPRINT("CTRDG_Read32(0x%x) failed\n", ctrp);
    }
    LOGPRINT("0x%x = 0x%x before write\n", ctrp, *memp);
    if (CTRDG_Write32(ctrp, 0x12345678) == 0) {
        LOGPRINT("CTRDG_Write32(0x%x) failed\n", ctrp);
    }
    if (CTRDG_Read32(ctrp, memp) == 0) {
        LOGPRINT("CTRDG_Read32(0x%x) failed\n", ctrp);
    }
    LOGPRINT("0x%x = 0x%x after write\n", ctrp, *memp);

    /*
     * Invalidate DCache and try it again
     */
#if 0
    LOGPRINT("Writeback DCache\n");
    DC_StoreAll();
#endif
    if (CTRDG_Read32(ctrp, memp) == 0) {
        LOGPRINT("CTRDG_Read32(0x%x) failed\n", ctrp);
    }
    LOGPRINT("0x%x = 0x%x before write\n", ctrp, *memp);
    if (CTRDG_Write32(ctrp, 0x56781234) == 0) {
        LOGPRINT("CTRDG_Write32(0x%x) failed\n", ctrp);
    }
    if (CTRDG_Read32(ctrp, memp) == 0) {
        LOGPRINT("CTRDG_Read32(0x%x) failed\n", ctrp);
    }
    LOGPRINT("0x%x = 0x%x after write\n", ctrp, *memp);

    /*
     * Writeback DCache and try it again
     */
#if 0
    LOGPRINT("Writeback DCache\n");
    DC_StoreAll();
#endif
    if (CTRDG_Read32(ctrp, memp) == 0) {
        LOGPRINT("CTRDG_Read32(0x%x) failed\n", ctrp);
    }
    LOGPRINT("0x%x = 0x%x before write\n", ctrp, *memp);
    if (CTRDG_Write32(ctrp, 0x87654321) == 0) {
        LOGPRINT("CTRDG_Write32(0x%x) failed\n", ctrp);
    }
#if 0
    LOGPRINT("Invalidate DCache\n");
    DC_InvalidateAll();
#endif
    if (CTRDG_Read32(ctrp, memp) == 0) {
        LOGPRINT("CTRDG_Read32(0x%x) failed\n", ctrp);
    }
    LOGPRINT("0x%x = 0x%x after write\n", ctrp, *memp);

    ctrp = (u32 *)(TEST_BASE + 0x40);
    if (CTRDG_Read32(ctrp, memp) == 0) {
        LOGPRINT("CTRDG_Read32(0x%x) failed\n", ctrp);
    }
    LOGPRINT("0x%x = 0x%x before write\n", ctrp, *memp);
    if (CTRDG_Write32(ctrp, 0x12345678) == 0) {
        LOGPRINT("CTRDG_Write32(0x%x) failed\n", ctrp);
    }
    if (CTRDG_Read32(ctrp, memp) == 0) {
        LOGPRINT("CTRDG_Read32(0x%x) failed\n", ctrp);
    }
    LOGPRINT("0x%x = 0x%x after write\n", ctrp, *memp);

    /*
     * Try byte writes
     */
    bp = (u8 *)(TEST_BASE + 0x41);
    if (CTRDG_Read32(ctrp, memp) == 0) {
        LOGPRINT("CTRDG_Read32(0x%x) failed\n", ctrp);
    }
    LOGPRINT("0x%x = 0x%x before write\n", ctrp, *memp);
    if (CTRDG_Write8(bp, 0x42) == 0) {
        LOGPRINT("CTRDG_Write8(0x%x) failed\n", bp);
    }
    *memp = 0;
    if (CTRDG_Read32(ctrp, memp) == 0) {
        LOGPRINT("CTRDG_Read32(0x%x) failed\n", ctrp);
    }
    LOGPRINT("0x%x = 0x%x after write to 0x%x\n", ctrp, *memp, bp);

    /*
     * Try halfword writes
     */
    sp = (u16 *)(TEST_BASE + 0x42);
    if (CTRDG_Read32(ctrp, memp) == 0) {
        LOGPRINT("CTRDG_Read32(0x%x) failed\n", ctrp);
    }
    LOGPRINT("0x%x = 0x%x before write\n", ctrp, *memp);
    if (CTRDG_Write16(sp, 0x4321) == 0) {
        LOGPRINT("CTRDG_Write16(0x%x) failed\n", sp);
    }
    *memp = 0;
    if (CTRDG_Read32(ctrp, memp) == 0) {
        LOGPRINT("CTRDG_Read32(0x%x) failed\n", ctrp);
    }
    LOGPRINT("0x%x = 0x%x after write to 0x%x\n", ctrp, *memp, sp);
}


/*---------------------------------------------------------------------------*
  Name:         NitroMain

  Description:  Initialization and main loop

  Arguments:    None.

  Returns:      None.
 *---------------------------------------------------------------------------*/
void NitroMain(void)
{
    TPData  raw_point;
    TPData  disp_point;
    TPCalibrateParam calibrate;

    // Initialization
    OS_Init();
    OS_InitThread();
    TP_Init();
    Cartridge_Init();
    DisplayInit();

    /* Now get really crazy and try ISFS and ES */
    ES_FS_Experiments();
    MeasurePerf();
    
    // get CalibrateParameter from FlashMemory
    if (!TP_GetUserInfo(&calibrate))
    {
        OS_Panic("FATAL ERROR: can't read UserOwnerInfo\n");
    }
    else
    {
        LOGPRINT("Got Calibration Parameters from NVRAM\n");
    }

    TP_SetCalibrateParam(&calibrate);
    LOGPRINT("SetCalibParam: x=(%d,%d) y=(%d,%d)\n",
            calibrate.x0, calibrate.xDotSize, 
            calibrate.y0, calibrate.yDotSize);

    // unnecessary called.
    // be able to use default parameter (retry,range).
#if 0
    // Send parameter of revision noise.
    if (TP_RequestSetStability(3, 15) != 0)
    {
        OS_Panic("SetStability request err!\n");
    }
#endif

    openDecoder();

    while (TRUE)
    {
        // Draw Marker by calibrated point.
        while (TP_RequestRawSampling(&raw_point) != 0)
        {
        }
        TP_GetCalibratedPoint(&disp_point, &raw_point);

        if (disp_point.touch)
        {
            SetPoint16x16(disp_point.x, disp_point.y);

            switch (disp_point.validity)
            {
            case TP_VALIDITY_VALID:
                LOGPRINT("( %d, %d ) -> ( %d, %d )\n", raw_point.x, raw_point.y, disp_point.x,
                          disp_point.y);
                break;
            case TP_VALIDITY_INVALID_X:
                LOGPRINT("( *%d, %d ) -> ( *%d, %d )\n", raw_point.x, raw_point.y, disp_point.x,
                          disp_point.y);
                break;
            case TP_VALIDITY_INVALID_Y:
                LOGPRINT("( %d, *%d ) -> ( %d, *%d )\n", raw_point.x, raw_point.y, disp_point.x,
                          disp_point.y);
                break;
            case TP_VALIDITY_INVALID_XY:
                LOGPRINT("( *%d, *%d ) -> ( *%d, *%d )\n", raw_point.x, raw_point.y, disp_point.x,
                          disp_point.y);
                break;
            }
        }

        /* flush cache of OAM buffers to main memory*/
        DC_FlushRange(gOam, sizeof(gOam));
        /* IO register is accessed using DMA operation, so cache Wait is not needed*/
        // DC_WaitWriteBufferEmpty();
        GX_LoadOAM(gOam, 0, sizeof(gOam));
        MI_DmaFill32(3, gOam, 192, sizeof(gOam));       // Clear OAM buffer

        // If mp3 decoder is open, read another block of samples
        if (mp3Fd >= 0)
        {
            readDecoder(sizeof audSamples);
            LOGPRINT("Decode: %02d:%02d / %02d:%02d\n",
                curTime/60, curTime%60, totalTime/60, totalTime%60);
        }

        // Wait V-Blank interrupt
        OS_WaitVBlankIntr();

    }
}


/*---------------------------------------------------------------------------*
  Name:         VBlankIntr

  Description:  V-Blank function

  Arguments:    None.

  Returns:      None.
 *---------------------------------------------------------------------------*/
static void VBlankIntr(void)
{

    // Set IRQ check flag
    OS_SetIrqCheckFlag(OS_IE_V_BLANK);
}


/*---------------------------------------------------------------------------*
  End of file
 *---------------------------------------------------------------------------*/
