//main.c

#include <stdio.h>

#include "ds2io.h"
#include "ds2_cpu.h"
#include "ds2_malloc.h"
#include "fs_api.h"
#include "key.h"
#include <math.h>
#include "gfx.i"
#include "keyorwhatever.h"
#include <stdarg.h>
#include<sys/stat.h>

int* topBG;
int* bottomBG;
int* dockImage;
int* menuImage;

char text_string[1024]; // for input routine
int keyRepeattime=5;
int keyCounter=0;

int Old_Stylus_X=0;
float icon_offset=0;
int click_position=0;
bool dragging = 0;
int temp1=0;
bool hitIcon=0;
int current_page=0;
int cursor_pos=0; // selected icon number
int* moveImage;
int moveNumber=0;
int* minuteHand;
int* hourHand;
float mySin[360];
float myCos[360];
int clockX=0;
int clockY=0;
int clockType=0;

int showInfoIcon=0;
int infoIX;
int infoIY; 
int showInfoName=0;
int infoNX;
int infoNY;
int showInfoNote;
int infoNoX;
int infoNoY;
int nameText = RGB15(31,0,31);
int nameTextShaddow = RGB15(0,31,0);
int noteText = RGB15(31,0,31);
int noteTextShaddow = RGB15(0,31,0);

int quietboot;
int hideicontext=0;

int showDay=0;
int DayX=0;
int DayY=0;
int dayText = RGB15(31,0,31);
int dayTextShaddow = RGB15(0,31,0);
int showDate=0;
int DateX=0;
int DateY=0;
int dateText = RGB15(31,0,31);
int dateTextShaddow = RGB15(0,31,0);

int topText = RGB15(31,31,31);
int topTextShaddow = RGB15(0,0,0);
int botText = RGB15(31,31,31);
int botTextShaddow = RGB15(0,0,0);

char months[12][4]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};


//----------------[ Keyboard routines ]------------------
char kb_shift=0;
int last_key=0;


void PutPixel(int screen, int x1, int y1, int color){
	if(screen==0)((unsigned short*)down_screen_addr)[x1+256*y1] = color;
	if(screen==1)((unsigned short*)up_screen_addr)[x1+256*y1] = color;
}

void drawLine(u8 screen, int x1, int y1, int x2, int y2, int color) {
	int dx = x2 - x1;
	int dy = y2 - y1;
	int stepX, stepY;
	if(dy < 0) { dy = -dy; stepY = -1; } else { stepY = 1; }
	if(dx < 0) { dx = -dx; stepX = -1; } else { stepX = 1; }
	dy <<= 1;
	dx <<= 1;

	PutPixel(screen, x1, y1, color);
	if(dx > dy) {
		int fraction = dy - (dx >> 1);
		while(x1 != x2) {
			if(fraction >= 0) {
				y1 += stepY;
				fraction -= dx;
			}
			x1 += stepX;
			fraction += dy;
			PutPixel(screen, x1, y1, color);
		}
		return;
	}

	int fraction = dx - (dy >> 1);
	while(y1 != y2) {
		if(fraction >= 0) {
			x1 += stepX;
			fraction -= dy;
		}
		y1 += stepY;
		fraction += dx;
		PutPixel(screen, x1, y1, color);
	}
}


void drawkey(int key, bool pressed)
{
   int kbx[40]={
	6, 31, 56, 81, 106, 131, 156, 181, 206, 231,
	19, 44, 69, 94, 119, 144, 169, 194, 219,				255,
	6, 44, 69, 94, 119, 144, 169, 194, 224,				255,
	6, 56, 182, 207,					 255,255,255,255,255,255
	};

	int kby[40]={
	91,  91,  91,  91,  91,  91,  91,  91,  91,  91, 
	116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
	141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 
	166, 166, 166, 166, 166, 166, 166, 166, 166, 166
	};

	int kbw[40]={
   20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
     20, 20, 20, 20, 20, 20, 20, 20, 20,			 0,
   27,   20, 20, 20, 20, 20, 20, 20,   27,		 0,
   45, 121, 20, 44,							0,0,0,0,0,0
	};


char * kbl[40*4]={
   "q","w","e","r","t","y","u","i","o","p",
     "a","s","d","f","g","h","j","k","l",								  "",
    "shift","z","x","c","v","b","n","m", "del",								  "",
    "symbol"," ",".","enter",									"","","","","","",

   "Q","W","E","R","T","Y","U","I","O","P",
     "A","S","D","F","G","H","J","K","L",								  "",
    "shift","Z","X","C","V","B","N","M", "del",								  "",
    "symbol"," ",".","enter",									"","","","","","",

   "1","2","3","4","5","6","7","8","9","0",
	"","","","","","","","","","",
	"shift","","","","","","","","","",
    "symbol"," ",".","",									"","","","","","",

   "!","@","#","$","%","^","&","*","(",")",
     "-","+","_","=","[","]","{","}","|",								  ".",
    "shift","\\",",",";",":","<",">","?", "del",								  ".",
    "symbol"," ",".","enter",									".",".",".",".",".",".",
	};


	int x=0,y=0,size=3;;
	//PA_16cTextAlign(ALIGN_CENTER);
	int col1 = RGB15(16,14,13); // border
	int col2 = RGB15(31,31,31); // highlight
	int col3 = RGB15(24,24,24); // shaddow
	int col4 = RGB15(27,27,27); // face

		if(kbx[key]!=255)
		{
			// outline
			drawLine(0, kbx[key]+1,		kby[key]-1,	kbx[key]+kbw[key]-2,	kby[key]-1,  		col1);	   
			drawLine(0, kbx[key]+1,		kby[key]+20,	kbx[key]+kbw[key]-2,	kby[key]+20, 	col1);	   
			drawLine(0, kbx[key]-1,		kby[key]+1,	kbx[key]-1,		kby[key]+18, 				col1);	   
			drawLine(0, kbx[key]+kbw[key],	kby[key]+1,	kbx[key]+kbw[key],	kby[key]+18, 		col1);	   
			PutPixel(0, kbx[key], kby[key], col1);
			PutPixel(0, kbx[key]+kbw[key]-1, kby[key], col1);
			PutPixel(0, kbx[key], kby[key]+19, col1);
			PutPixel(0, kbx[key]+kbw[key]-1, kby[key]+19, col1);

		if(pressed==0)
		{
			// highlight
			drawLine(0, kbx[key]+1,	kby[key],		kbx[key]+kbw[key]-2,	kby[key],   col2);	   
			drawLine(0, kbx[key],		kby[key]+1,		kbx[key],	kby[key]+18,  		col2);	   
			// shaddow
			drawLine(0, kbx[key]+kbw[key]-1,	kby[key]+1,		kbx[key]+kbw[key]-1,	kby[key]+18,  col3);	   
			drawLine(0, kbx[key]+1,			kby[key]+19,		kbx[key]+kbw[key]-2,	kby[key]+19,  col3);	   
		}else{
			// highlight
			drawLine(0, kbx[key]+1,	kby[key],		kbx[key]+kbw[key]-2,	kby[key],  col3);	   
			drawLine(0, kbx[key],		kby[key]+1,		kbx[key],	kby[key]+18,  col3);	   
			// shaddow
			drawLine(0, kbx[key]+kbw[key]-1,	kby[key]+1,		kbx[key]+kbw[key]-1,	kby[key]+18,  col2);	   
			drawLine(0, kbx[key]+1,			kby[key]+19,		kbx[key]+kbw[key]-2,	kby[key]+19,  col2);	   
		}   
			// face
			for(y=1; y<19; y++){for(x=1; x<kbw[key]-1; x++){
			PutPixel(0, kbx[key]+x, kby[key]+y, col4);}}
			
			// text
			size=3;
			if(strcmp(kbl[key],"shift")==0 || strcmp(kbl[key],"del")==0 || strcmp(kbl[key],"symbol")==0 
			|| strcmp(kbl[key],"enter")==0 )size=1;
			if(size==3)
			{
			//	PA_16cTextAlign(ALIGN_CENTER);
			//	PA_16cText(0, kbx[key]+pressed,kby[key]+4+pressed, kbx[key]+kbw[key]+pressed, kby[key]+18+pressed, kbl[key+(kb_shift*40)], 15, size, 6);
				drawText(1,1,kbx[key]+pressed,
							kby[key]+4+pressed, 
							kbx[key]+kbw[key]+pressed, 
							kby[key]+18+pressed, 
							kbl[key+(kb_shift*40)],RGB15(0,0,0),1,1);
			}else{
			//	PA_16cTextAlign(ALIGN_LEFT);
				drawText(1,1,kbx[key]+pressed,
							kby[key]+4+pressed, 
							kbx[key]+kbw[key]+pressed, 
							kby[key]+18+pressed, 
							kbl[key+(kb_shift*40)],RGB15(0,0,0),0,1);
			}   			
		}//kbx[key]!=255

	//PA_16cTextAlign(ALIGN_LEFT);
}

void draw_keyboard(void)
{

	int i=0;
	for(i=0; i<40; i++)drawkey(i,0);
	for(i=63; i<76; i++){
		drawLine(0, 	128-64,	i,	128+64,	i,  		RGB15(5,5,5));	   
		drawLine(0, 	128-32,	i,	128+32,	i,  		RGB15(15,15,15));	   
	}
	
	drawLine(0, 	128-64,	62,	128+64,	62,  		RGB15(31,31,31));	   
	drawLine(0, 	128-64,	76,	128+64,	76,  		RGB15(31,31,31));	   
	drawLine(0, 	128-64,	76,	128-64,	62,  		RGB15(31,31,31));	   
	drawLine(0, 	128+64,	76,	128+64,	62,  		RGB15(31,31,31));	   

}

char check_kb()
{
	UpdatePad(); //updates both stylus and pads
char key=0;
// keyboard layout
int kbx[40]={
	6, 31, 56, 81, 106, 131, 156, 181, 206, 231,
	19, 44, 69, 94, 119, 144, 169, 194, 219,				255,
	6, 44, 69, 94, 119, 144, 169, 194, 224,				255,
	6, 56, 182, 207,					 255,255,255,255,255,255
	};

int kby[40]={
	91,  91,  91,  91,  91,  91,  91,  91,  91,  91, 
	116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
	141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 
	166, 166, 166, 166, 166, 166, 166, 166, 166, 166
	};

int kbw[40]={
   20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
     20, 20, 20, 20, 20, 20, 20, 20, 20,			 0,
   27,   20, 20, 20, 20, 20, 20, 20,   27,		 0,
   45, 121, 20, 44,							0,0,0,0,0,0
	};

char kbl[40*4]={
   'q','w','e','r','t','y','u','i','o','p',
     'a','s','d','f','g','h','j','k','l',								  0,
    '.','z','x','c','v','b','n','m', 0,								  0,
    '.',' ','.','.',									0,0,0,0,0,0,

   'Q','W','E','R','T','Y','U','I','O','P',
     'A','S','D','F','G','H','J','K','L',								  0,
    '.','Z','X','C','V','B','N','M', 0,								  0,
    '.',' ','.','.',									0,0,0,0,0,0,

   '1','2','3','4','5','6','7','8','9','0',
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
    0,' ','.',0,									0,0,0,0,0,0,

   '!','@','#','$','%','^','&','*','(',')',
     '-','+','_','=','[',']',123,125,'|',								  '.',
    '.',92,44,59,58,60,62,63, '.',								  '.',
    '.',' ','.','.',									'.','.','.','.','.','.',
	};


  int t=0;
for(t=0; t<39; t++)
{
	if(Stylus.Held)
	{
		if(Stylus.X>=kbx[t]
		&& Stylus.X<=kbx[t]+kbw[t] 
		&& Stylus.Y>=kby[t] 
		&& Stylus.Y<=kby[t]+20)
		{
			if(last_key!=t)
			{
				drawkey(last_key,0);
			   last_key=t;
				//drawkey(last_key,1);
			//}else{
			}			
				drawkey(t,1);
			//}   
		}//if button
	}else{
				drawkey(last_key,0);
				last_key=35;
	}

}// t



if(Stylus.Newpress)
{
   int t=0;
	for(t=0; t<39; t++)
	{
		if(Stylus.X>=kbx[t] && Stylus.X<=kbx[t]+kbw[t] && Stylus.Y>=kby[t] && Stylus.Y<=kby[t]+20)
		{

		   if(t==20)
			{
			   kb_shift++;
			   if(kb_shift>=2)kb_shift=0;
				draw_keyboard();
			}else if(t==30)
			{
			   kb_shift++;
			   if(kb_shift==1)kb_shift=2; // skip upper case, no need when shift works
			   if(kb_shift==4)kb_shift=0;
				draw_keyboard();
			}else if(t==33) // enter
			{
				key = 10;
			}else if(t==28) // delete
			{
				key = 8;
			}else{
			   key=kbl[t+(kb_shift*40)];
			   kb_shift=0;
			}
			
		}
	}
   
}// stylus newpress   


	return key;
}


//-------------------------------------------------------



#define BAG_Math_Cos(angle) BAG_MATH_SIN[((angle) + 128)&511]
const short BAG_MATH_SIN[512] = {
	0x0000, 0x0003, 0x0006, 0x0009, 0x000D, 0x0010, 0x0013, 0x0016,	0x0019, 0x001C, 0x001F, 0x0022, 0x0026, 0x0029, 0x002C, 0x002F,
	0x0032, 0x0035, 0x0038, 0x003B, 0x003E, 0x0041, 0x0044, 0x0047,	0x004A, 0x004D, 0x0050, 0x0053, 0x0056, 0x0059, 0x005C, 0x005F,
	0x0062, 0x0065, 0x0068, 0x006B, 0x006D, 0x0070, 0x0073, 0x0076,	0x0079, 0x007B, 0x007E, 0x0081, 0x0084, 0x0086, 0x0089, 0x008C,
	0x008E, 0x0091, 0x0093, 0x0096, 0x0098, 0x009B, 0x009D, 0x00A0,	0x00A2, 0x00A5, 0x00A7, 0x00AA, 0x00AC, 0x00AE, 0x00B1, 0x00B3,

	0x00B5, 0x00B7, 0x00B9, 0x00BC, 0x00BE, 0x00C0, 0x00C2, 0x00C4,	0x00C6, 0x00C8, 0x00CA, 0x00CC, 0x00CE, 0x00CF, 0x00D1, 0x00D3,
	0x00D5, 0x00D7, 0x00D8, 0x00DA, 0x00DC, 0x00DD, 0x00DF, 0x00E0,	0x00E2, 0x00E3, 0x00E5, 0x00E6, 0x00E7, 0x00E9, 0x00EA, 0x00EB,
	0x00ED, 0x00EE, 0x00EF, 0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4,	0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F8, 0x00F9, 0x00FA, 0x00FA,
	0x00FB, 0x00FC, 0x00FC, 0x00FD, 0x00FD, 0x00FE, 0x00FE, 0x00FE,	0x00FF, 0x00FF, 0x00FF, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100,

	0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x00FF, 0x00FF,	0x00FF, 0x00FE, 0x00FE, 0x00FE, 0x00FD, 0x00FD, 0x00FC, 0x00FC,
	0x00FB, 0x00FA, 0x00FA, 0x00F9, 0x00F8, 0x00F8, 0x00F7, 0x00F6,	0x00F5, 0x00F4, 0x00F3, 0x00F2, 0x00F1, 0x00F0, 0x00EF, 0x00EE,
	0x00ED, 0x00EB, 0x00EA, 0x00E9, 0x00E7, 0x00E6, 0x00E5, 0x00E3,	0x00E2, 0x00E0, 0x00DF, 0x00DD, 0x00DC, 0x00DA, 0x00D8, 0x00D7,
	0x00D5, 0x00D3, 0x00D1, 0x00CF, 0x00CE, 0x00CC, 0x00CA, 0x00C8,	0x00C6, 0x00C4, 0x00C2, 0x00C0, 0x00BE, 0x00BC, 0x00B9, 0x00B7,

	0x00B5, 0x00B3, 0x00B1, 0x00AE, 0x00AC, 0x00AA, 0x00A7, 0x00A5,	0x00A2, 0x00A0, 0x009D, 0x009B, 0x0098, 0x0096, 0x0093, 0x0091,
	0x008E, 0x008C, 0x0089, 0x0086, 0x0084, 0x0081, 0x007E, 0x007B,	0x0079, 0x0076, 0x0073, 0x0070, 0x006D, 0x006B, 0x0068, 0x0065,
	0x0062, 0x005F, 0x005C, 0x0059, 0x0056, 0x0053, 0x0050, 0x004D,	0x004A, 0x0047, 0x0044, 0x0041, 0x003E, 0x003B, 0x0038, 0x0035,
	0x0032, 0x002F, 0x002C, 0x0029, 0x0026, 0x0022, 0x001F, 0x001C,	0x0019, 0x0016, 0x0013, 0x0010, 0x000D, 0x0009, 0x0006, 0x0003,

	0x0000, 0xFFFD, 0xFFFA, 0xFFF7, 0xFFF3, 0xFFF0, 0xFFED, 0xFFEA,	0xFFE7, 0xFFE4, 0xFFE1, 0xFFDE, 0xFFDA, 0xFFD7, 0xFFD4, 0xFFD1,
	0xFFCE, 0xFFCB, 0xFFC8, 0xFFC5, 0xFFC2, 0xFFBF, 0xFFBC, 0xFFB9,	0xFFB6, 0xFFB3, 0xFFB0, 0xFFAD, 0xFFAA, 0xFFA7, 0xFFA4, 0xFFA1,
	0xFF9E, 0xFF9B, 0xFF98, 0xFF95, 0xFF93, 0xFF90, 0xFF8D, 0xFF8A,	0xFF87, 0xFF85, 0xFF82, 0xFF7F, 0xFF7C, 0xFF7A, 0xFF77, 0xFF74,
	0xFF72, 0xFF6F, 0xFF6D, 0xFF6A, 0xFF68, 0xFF65, 0xFF63, 0xFF60,	0xFF5E, 0xFF5B, 0xFF59, 0xFF56, 0xFF54, 0xFF52, 0xFF4F, 0xFF4D,

	0xFF4B, 0xFF49, 0xFF47, 0xFF44, 0xFF42, 0xFF40, 0xFF3E, 0xFF3C,	0xFF3A, 0xFF38, 0xFF36, 0xFF34, 0xFF32, 0xFF31, 0xFF2F, 0xFF2D,
	0xFF2B, 0xFF29, 0xFF28, 0xFF26, 0xFF24, 0xFF23, 0xFF21, 0xFF20,	0xFF1E, 0xFF1D, 0xFF1B, 0xFF1A, 0xFF19, 0xFF17, 0xFF16, 0xFF15,
	0xFF13, 0xFF12, 0xFF11, 0xFF10, 0xFF0F, 0xFF0E, 0xFF0D, 0xFF0C,	0xFF0B, 0xFF0A, 0xFF09, 0xFF08, 0xFF08, 0xFF07, 0xFF06, 0xFF06,
	0xFF05, 0xFF04, 0xFF04, 0xFF03, 0xFF03, 0xFF02, 0xFF02, 0xFF02,	0xFF01, 0xFF01, 0xFF01, 0xFF00, 0xFF00, 0xFF00, 0xFF00, 0xFF00,

	0xFF00, 0xFF00, 0xFF00, 0xFF00, 0xFF00, 0xFF00, 0xFF01, 0xFF01,	0xFF01, 0xFF02, 0xFF02, 0xFF02, 0xFF03, 0xFF03, 0xFF04, 0xFF04,
	0xFF05, 0xFF06, 0xFF06, 0xFF07, 0xFF08, 0xFF08, 0xFF09, 0xFF0A,	0xFF0B, 0xFF0C, 0xFF0D, 0xFF0E, 0xFF0F, 0xFF10, 0xFF11, 0xFF12,
	0xFF13, 0xFF15, 0xFF16, 0xFF17, 0xFF19, 0xFF1A, 0xFF1B, 0xFF1D,	0xFF1E, 0xFF20, 0xFF21, 0xFF23, 0xFF24, 0xFF26, 0xFF28, 0xFF29,
	0xFF2B, 0xFF2D, 0xFF2F, 0xFF31, 0xFF32, 0xFF34, 0xFF36, 0xFF38,	0xFF3A, 0xFF3C, 0xFF3E, 0xFF40, 0xFF42, 0xFF44, 0xFF47, 0xFF49,

	0xFF4B, 0xFF4D, 0xFF4F, 0xFF52, 0xFF54, 0xFF56, 0xFF59, 0xFF5B,	0xFF5E, 0xFF60, 0xFF63, 0xFF65, 0xFF68, 0xFF6A, 0xFF6D, 0xFF6F,
	0xFF72, 0xFF74, 0xFF77, 0xFF7A, 0xFF7C, 0xFF7F, 0xFF82, 0xFF85,	0xFF87, 0xFF8A, 0xFF8D, 0xFF90, 0xFF93, 0xFF95, 0xFF98, 0xFF9B,
	0xFF9E, 0xFFA1, 0xFFA4, 0xFFA7, 0xFFAA, 0xFFAD, 0xFFB0, 0xFFB3,	0xFFB6, 0xFFB9, 0xFFBC, 0xFFBF, 0xFFC2, 0xFFC5, 0xFFC8, 0xFFCB,
	0xFFCE, 0xFFD1, 0xFFD4, 0xFFD7, 0xFFDA, 0xFFDE, 0xFFE1, 0xFFE4,	0xFFE7, 0xFFEA, 0xFFED, 0xFFF0, 0xFFF3, 0xFFF7, 0xFFFA, 0xFFFD
};

struct stat st; // for file stuff
int number_of_files = 0; // How many files we have
typedef struct
{
	char filename[128];	// name of each .ini file
	char imagename[128]; // name of image
	char loadname[128]; // name of file to load
	char name[64]; // title of icon
	int width; // width of icon
	int height; // height of icon
	int* image;
	int number; // list order
	bool dock; // is a dock item or not?
	char note[256]; // info comment thing
	char argument[256];
}DirEntry;
DirEntry Icons[200]; // up to 200 files in list
int iconOrder[200]; // order in which the icons are displayed
int tempOrder[200]; // for sorting method
int dockOrder[4]; // which Icons for the dock!
int number_of_docks = 0;
int layout[25][4][2]; // icon layout (page)(x)(y) 25 pages = 200 icons

// cursor for d-pad controls
int* cursorImage;
int* digitsImage; // for clock
int* colonImage; // for clock
int toDay;

int HexToDec(int crap)
{
	int num=0;
	if(crap == 48){num=0;}
	if(crap == 49){num=1;}
	if(crap == 50){num=2;}
	if(crap == 51){num=3;}
	if(crap == 52){num=4;}
	if(crap == 53){num=5;}
	if(crap == 54){num=6;}
	if(crap == 55){num=7;}
	if(crap == 56){num=8;}
	if(crap == 57){num=9;}
	if(crap == 65 || crap==97){num=10;}
	if(crap == 66 || crap==98){num=11;}
	if(crap == 67 || crap==99){num=12;}
	if(crap == 68 || crap==100){num=13;}
	if(crap == 69 || crap==101){num=14;}
	if(crap == 70 || crap==102){num=15;}
	return num;   
}
int findToday(void)
{
	struct rtc Date;
	ds2_getTime(&Date);
	int day = Date.day;
	int month = Date.month;
	int year = Date.year;
	if(year < 100)year+=2000;
	
	int a = (14 - month) / 12;
	int y = year - a;
	int m = month + 12*a - 2;
	int d = (day + y + y/4 - y/100 + y/400 + (31*m)/12) % 7;

	return d;
}

int file_exists (char * fileName)
{
  FILE* dat = fopen(fileName, "r");
	if(dat){
		fclose(dat);
		return 1;
	}else{
		return 0;
	}       
}

// This part is for battery testing (lol)
void batteryCheck(void)
{

	struct rtc Date;
	ds2_getTime(&Date);
	int seconds = Date.seconds;
	int oldSeconds = seconds;
	
	int tHours=0;
	int tMinutes=0;
	int tSeconds=0;
	FILE* dat;
	int tFile=0;
	
	while(1)
	{
		// loop forever, until battery is dead
		ds2_getTime(&Date);
		seconds = Date.seconds;
		if(seconds != oldSeconds){
			oldSeconds = seconds;
			tSeconds++;
			if(tSeconds==60){
				tSeconds=0; 
				tMinutes++;
				if(tMinutes%5==0){
					// every five minutes update timer file, shouldn't kill the card.
					if(tFile==0){
						dat = fopen("fat:/batteryTime1.txt", "wb");
					}else{
						dat = fopen("fat:/batteryTime2.txt", "wb");
					}
						tFile = 1 - tFile;
					if(dat)
					{
						fprintf(dat, "%d:%d:%d", tHours, tMinutes, tSeconds);
						fclose(dat);
					}
				
				}
			}
			if(tMinutes==60){tMinutes=0; tHours++;}
			printf("\n%d:%d:%d", tHours, tMinutes, tSeconds);
		}
	}


}


int copyFile(char * from, const char * to)
{
	FILE *fp,*ft;
	char ch;
 
	fp=fopen(from,"rb");
	ft=fopen(to,"wb");
	while(!feof(fp)){
         ch=fgetc(fp);
         fputc(ch,ft);
	}
	fclose(fp);
	fclose(ft);

    return (1);
}


void File_Args(char *filedest, int argc,  ...)
{
	FILE* dat = fopen(filedest, "wb");
	if(dat)
	{
		va_list vl;
		va_start(vl, argc);
		int i = 1;
		fprintf(dat, "%s", va_arg(vl, char* ));
		for(i = 1; i < argc; i++)
		fprintf(dat, "\n%s", va_arg(vl, char* ));
		va_end(vl);
		 
		fclose(dat);
	}

}
 
void setLayout(void)
{
	int page = 0;
	int x=0;
	int y=0;
	int temp=0;

	for(temp=0; temp<=200; temp++){
	   layout[page][x][y]=-1;
	   x++;
	   if(x==4){
		   x=0; 
			y++; 
			if(y==2){
			   y=0; 
				page++;
			}
		}
	}   

	page=0; x=0; y=0;
	for(temp=0; temp<=number_of_files; temp++){
	   layout[page][x][y]=temp;
	   x++;
	   if(x==4){
		   x=0; 
			y++; 
			if(y==2){
			   y=0; 
				page++;
			}
		}
	}   
}   

int mix(int back, int front, int alpha)
{
	if(alpha<8){
		return front;
	}else{
		return back+(((front-back)*(255-alpha))>>8);	
	}
}


void drawBG(int screen)
{
	int x;
	 for(x=0; x<256*192; x++){
		if(screen){
			((unsigned short*)up_screen_addr)[x] = topBuffer[x];
		}else{
			((unsigned short*)down_screen_addr)[x] = bottomBuffer[x];
		}
	}//x	   
}

// ASCII + ordered nationals only...
int cmpistr(const char* s1, const char* s2)
{
    int    c1, c2;
    int    cmp = 0;

    if (s1 && s2)
    for (;;)
    {
        c1 = *s1++;
        c2 = *s2++;
        if (c1 && c2)
        {
            c1 = tolower(c1)&0xFF; // 8 bits
            c2 = tolower(c2)&0xFF; // only
            if (c1 < c2)
            {
                cmp = -1;
                break;
            }
            else if (c1 > c2)
            {
                cmp = 1;
                break;
            }
        }
        else
        {
            if (c1)
                cmp = 1;
            else if (c2)
                cmp = -1;
            break;
        }
    }
    return cmp;
}

int imageHeight(int * imageData)
{
	return	imageData[1];
}
int imageWidth(int * imageData)
{
	return	imageData[0];
}

void drawBMP(int *imageData, bool screen, int ix, int iy)
{
	int width = imageData[0];
	int height = imageData[1];
	int x, y, counter, mask, pixel, temp, alpha, sy;
	counter=0;
	for(y=0; y<height; y++){
		sy = height-y-1;
		for(x=0; x<width; x++){
			pixel = imageData[counter+2];
			mask = imageData[counter+3];
			if(x+ix>=0 && x+ix <=255 && sy+iy>=0 && sy+iy<=191){
				alpha = 255-mask;
				if(screen==0)temp = ((unsigned short*)down_screen_addr)[(ix+x)+(256*(sy+iy))];
				if(screen==1)temp = ((unsigned short*)up_screen_addr)[(ix+x)+(256*(sy+iy))];
				int b2 = (temp>>10)&31;
				int g2 = (temp>>5)&31;
				int r2 = temp &31;
				temp = pixel;
				int b1 = (temp>>10)&31;
				int g1 = (temp>>5)&31;
				int r1 = temp &31;
				temp = RGB15(mix(r2,r1,alpha),mix(g2,g1,alpha),mix(b2,b1,alpha));
				if(screen==0)((unsigned short*)down_screen_addr)[(ix+x)+(256*(iy+sy))] = temp;
				if(screen==1)((unsigned short*)up_screen_addr)[(ix+x)+(256*(iy+sy))] = temp;
			} // on screen?
			counter+=2;
		}
	}
}

void drawBMPframe(int *imageData, bool screen, int ix, int iy, int frame)
{
	int width = imageData[0];
	int height = imageData[1] /10;
	int x, y, counter, mask, pixel, temp, alpha, sy;
	counter = width*height*(9-frame)*2;
	for(y=0; y<height; y++){
		sy = height-y-1;
		for(x=0; x<width; x++){
			pixel = imageData[counter+2];
			mask = imageData[counter+3];
			if(x+ix>=0 && x+ix <=255 && y+iy>=0 && y+iy<=191){
				alpha = 255-mask;
				if(screen==0)temp = ((unsigned short*)down_screen_addr)[(ix+x)+(256*(sy+iy))];
				if(screen==1)temp = ((unsigned short*)up_screen_addr)[(ix+x)+(256*(sy+iy))];
				int b2 = (temp>>10)&31;
				int g2 = (temp>>5)&31;
				int r2 = temp &31;
				temp = pixel;
				int b1 = (temp>>10)&31;
				int g1 = (temp>>5)&31;
				int r1 = temp &31;
				temp = RGB15(mix(r2,r1,alpha),mix(g2,g1,alpha),mix(b2,b1,alpha));
				if(screen==0)((unsigned short*)down_screen_addr)[(ix+x)+(256*(iy+sy))] = temp;
				if(screen==1)((unsigned short*)up_screen_addr)[(ix+x)+(256*(iy+sy))] = temp;
			} // on screen?
			counter+=2;
		}
	}
}

int* loadBMP(char * filename){

	u16 width,height;
	int* imageData;
	
	FILE* imgFile=fopen(filename,"rb");	
	if(imgFile)
	{			
		// read height+width
		fseek(imgFile,18,SEEK_SET);
		fread(&width, 4, 1, imgFile);
		fread(&height, 4, 1, imgFile);
		// read bit depth of image
		u16 bytes=0;
		fseek(imgFile,28,SEEK_SET);
		fread(&bytes, 2, 1, imgFile);
		fseek(imgFile,54,SEEK_SET);
		bytes = bytes >> 3;

		//printf("%s\n",filename);
		imageData = calloc((width*height*2)+2, sizeof(int));
			// read image data

			if(bytes==1){ // 8bit
				u16 x,y,t,r,g,b,h,w;
				unsigned char col[4];
				u16 pal[256];
				u8 temp;
				for(t=0; t<256; t++){
					fread(col, sizeof(char), 4, imgFile);	   
					pal[t]= RGB15(col[2]>>3,col[1]>>3,col[0]>>3); //PA_RGB(col[2]>>3,col[1]>>3,col[0]>>3);
				}
				
				int tWidth = (width);
				int counter=0;
				imageData[0] = width;
				imageData[1] = height;
				for(y=0; y<(height); y++){
					for(x=0; x<tWidth; x++){
						fread(&temp, 1, 1, imgFile);
						imageData[2+counter] = pal[temp]; 
						if(pal[temp] == RGB15(0,31,0)){
							imageData[3+counter] = 0; 
						}else{
							imageData[3+counter] = 255; 
						}
						counter+=2;
					}
				}
			}// bytes==1
	
			if(bytes==2){ // 16bit
				//printf("15bit\n");
				u16 x,y,t,r,g,b,h,w;
				imageData[0] = width;
				imageData[1] = height;
				int tWidth = (width);
				if(tWidth%4)tWidth+=4-(tWidth%4);
				int counter=0;
				for(y=0; y<(height); y++){
					for(x=0; x<tWidth; x++){
						fread(&t, 2, 1, imgFile);
						r = (t >> 10)&31;
						g = (t >> 5)&31;
						b = t&31;
						imageData[2+counter] = RGB15(r,g,b); 
						if(r==0 && g==31 && b==0){
							imageData[3+counter] = 0; 
						}else{
							imageData[3+counter] = 255; 
						}
						counter+=2;
					}
				}
			}// bytes==2		
			if(bytes==3){ // 24bit
				//printf("15bit\n");
				u16 x,y;
				u8 RGB[3];
				imageData[0] = width;
				imageData[1] = height;
				int tWidth = width;
				int counter=0;
				
				for(y=0; y<(height); y++){
					for(x=0; x<(width); x++){
						fread(&RGB, 1, 3, imgFile);
						imageData[2+counter] = RGB15(RGB[2]>>3,RGB[1]>>3,RGB[0]>>3); 
						if(RGB[2]==0 && RGB[1]==255 && RGB[0]==0){
							imageData[3+counter] = 0; 
						}else{
							imageData[3+counter] = 255; 
						}
						counter+=2;
					}
					if(x%4){
						while(x%4){
							fread(&RGB, 1, 1, imgFile);
							x++;
						}
					}
				}
			}// bytes==3		
			if(bytes==4){ // 32bit
				//printf("15bit\n");
				u16 x,y;
				u8 A,R,G,B;
				imageData[0] = width;
				imageData[1] = height;
				int tWidth = (width);
				int counter=0;
				for(y=0; y<(height); y++){
					for(x=0; x<(width); x++){
						//fread(&ARGB, 1, 4, imgFile);
						fread(&B, 1, 1, imgFile);
						fread(&G, 1, 1, imgFile);
						fread(&R, 1, 1, imgFile);
						fread(&A, 1, 1, imgFile);
						imageData[2+counter] = RGB15(R>>3,G>>3,B>>3); 
						imageData[3+counter] = A; 
						counter+=2;
					}
				}
			}// bytes==4
			fclose(imgFile);
	}// if imgFile
	return imageData;
}

void writeIni(int fileNumber)
{
	char iniData[512]; // 512 characters should be enough for all data!
	char tempFilename[255]; // to store the new ini file
	sprintf(tempFilename,"fat:/_imenu/_ini/%s",Icons[fileNumber].filename);
	remove(tempFilename);
	sprintf(iniData,"[plug setting]\r\nicon=%s\r\nname=%s\r\nfile=%s\r\nnumber=%d\r\ndock=%d\r\nnote=%s\r\narg=%s\r\n",Icons[fileNumber].imagename,Icons[fileNumber].name,Icons[fileNumber].loadname,Icons[fileNumber].number,Icons[fileNumber].dock,Icons[fileNumber].note,Icons[fileNumber].argument);
	FILE* testRead = fopen (tempFilename, "wb"); //rb = read	
		fputs(iniData, testRead);
	fclose (testRead);
	
}

void readIni(int fileNumber)
{
	// read all ini data in one go.
	
	char tempString[128]; // temp string for line data
	char itemString[128];
	char resultString[128];
	char tempFilename[128];
	int temp2=0;
	sprintf(tempFilename,"fat:/_imenu/_ini/%s",Icons[fileNumber].filename);
	//printf("%s\n", tempFilename);
	FILE* iniFile=fopen(tempFilename,"rb");	
	if(iniFile)
	{
		// reset the default values
		Icons[fileNumber].number = 300;
		Icons[fileNumber].dock = 0;
		strcpy(Icons[fileNumber].loadname, "Error!");
		strcpy(Icons[fileNumber].name, "Error!");
		strcpy(Icons[fileNumber].imagename, "Error!");

		while(fgets(tempString, 128, iniFile) != NULL){
			int length = strlen(tempString);
			int temp=0;
			for(temp=0; temp<length; temp++){
				if(tempString[temp] == 61){
					strcpy(resultString, &tempString[temp+1]);
					for(temp2=0; temp2<temp; temp2++){
						itemString[temp2] = tempString[temp2];
					}//temp2
					itemString[temp]=0;
					strcpy(tempString, itemString);
					int y=0;
					for(temp2=0; temp2<strlen(tempString); temp2++){
						int x = tempString[temp2];
						itemString[y] = 0; // end the string
						// 0x09 - horizontal tab, 0x0a - linefeed, 0x0b - vertical tab, 0x0c - form feed, 0x0d - carriage return, 0x20 - space
						if(x != 0x09 && x != 0x0a && x != 0x0b && x != 0x0c && x != 0x0d && x != 0x20){
							itemString[y] = tolower(x);
							y++;
						}
					}//temp2					

					if(cmpistr(itemString,"icon")==0){
						//printf("Icon!\n");
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						temp=0;
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						strcpy(Icons[fileNumber].imagename, resultString);
						// set icon name
					}
					if(cmpistr(itemString,"name")==0){
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						strcpy(Icons[fileNumber].name, resultString);
						// set icon name
					}
					if(cmpistr(itemString,"file")==0){
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						strcpy(Icons[fileNumber].loadname, resultString);
						// set filename
					}
					if(cmpistr(itemString,"number")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						Icons[fileNumber].number = atoi(resultString);
					}

					if(cmpistr(itemString,"dock")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						Icons[fileNumber].dock = atoi(resultString);

					}

					if(cmpistr(itemString,"note")==0){
						//printf("Icon!\n");
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						strcpy(Icons[fileNumber].note, resultString);
						// set icon name
					}
					if(cmpistr(itemString,"arg")==0){
						//printf("arg!\n");
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						strcpy(Icons[fileNumber].argument, resultString);
						// set icon name
					}
					
					//printf("%s = %s\n", itemString,resultString);
				} // found "="
			} // temp<length
		}
		
		
		fclose(iniFile);
		//printf("Done!\n");
	}// if imgFile
		else{
						printf("No Open %s\n", Icons[fileNumber].filename);
	}// fail open
}

void readClockIni(void)
{
	clockType=0;
	clockX=128;
	clockY=61;
	
	char tempString[128]; // temp string for line data
	char itemString[128];
	char resultString[128];
	char tempFilename[128];
	int temp2=0;
	sprintf(tempFilename,"fat:/_imenu/%s","clock.ini");
	FILE* iniFile=fopen(tempFilename,"rb");	
	if(iniFile)
	{

		while(fgets(tempString, 128, iniFile) != NULL){
			int length = strlen(tempString);
			int temp=0;
			for(temp=0; temp<length; temp++){
				if(tempString[temp] == 61){
					strcpy(resultString, &tempString[temp+1]);
					for(temp2=0; temp2<temp; temp2++){
						itemString[temp2] = tempString[temp2];
					}//temp2
					itemString[temp]=0;
					strcpy(tempString, itemString);
					int y=0;
					for(temp2=0; temp2<strlen(tempString); temp2++){
						int x = tempString[temp2];
						itemString[y] = 0; // end the string
						// 0x09 - horizontal tab, 0x0a - linefeed, 0x0b - vertical tab, 0x0c - form feed, 0x0d - carriage return, 0x20 - space
						if(x != 0x09 && x != 0x0a && x != 0x0b && x != 0x0c && x != 0x0d && x != 0x20){
							itemString[y] = tolower(x);
							y++;
						}
					}//temp2					

					if(cmpistr(itemString,"type")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						clockType = atoi(resultString);
					}
					if(cmpistr(itemString,"x")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						clockX = atoi(resultString);
					}
					if(cmpistr(itemString,"y")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						clockY = atoi(resultString);
					}
				} // foud '='
			} // temp<length
		}
		
		
		fclose(iniFile);
		//printf("Done!\n");
	}// if imgFile
		else{
						printf("No Open clock.ini\n");
	}// fail open
}

void readSettignsIni(void)
{
	
	char tempString[128]; // temp string for line data
	char itemString[128];
	char resultString[128];
	char tempFilename[128];
	int temp2=0;
	sprintf(tempFilename,"fat:/_imenu/%s","settings.ini");
	FILE* iniFile=fopen(tempFilename,"rb");	
	if(iniFile)
	{

		while(fgets(tempString, 128, iniFile) != NULL){
			int length = strlen(tempString);
			int temp=0;
			for(temp=0; temp<length; temp++){
				if(tempString[temp] == 61){
					strcpy(resultString, &tempString[temp+1]);
					for(temp2=0; temp2<temp; temp2++){
						itemString[temp2] = tempString[temp2];
					}//temp2
					itemString[temp]=0;
					strcpy(tempString, itemString);
					int y=0;
					for(temp2=0; temp2<strlen(tempString); temp2++){
						int x = tempString[temp2];
						itemString[y] = 0; // end the string
						// 0x09 - horizontal tab, 0x0a - linefeed, 0x0b - vertical tab, 0x0c - form feed, 0x0d - carriage return, 0x20 - space
						if(x != 0x09 && x != 0x0a && x != 0x0b && x != 0x0c && x != 0x0d && x != 0x20){
							itemString[y] = tolower(x);
							y++;
						}
					}//temp2					

					if(cmpistr(itemString,"toptext")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						int r1=(HexToDec(resultString[0])*16+HexToDec(resultString[1]))/8;
						int g1=(HexToDec(resultString[2])*16+HexToDec(resultString[3]))/8;
						int b1=(HexToDec(resultString[4])*16+HexToDec(resultString[5]))/8;
						topText = RGB15(r1,g1,b1);						
					}

					if(cmpistr(itemString,"topshaddow")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						int r1=(HexToDec(resultString[0])*16+HexToDec(resultString[1]))/8;
						int g1=(HexToDec(resultString[2])*16+HexToDec(resultString[3]))/8;
						int b1=(HexToDec(resultString[4])*16+HexToDec(resultString[5]))/8;
						topTextShaddow = RGB15(r1,g1,b1);						
					}

					if(cmpistr(itemString,"bottomtext")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						int r1=(HexToDec(resultString[0])*16+HexToDec(resultString[1]))/8;
						int g1=(HexToDec(resultString[2])*16+HexToDec(resultString[3]))/8;
						int b1=(HexToDec(resultString[4])*16+HexToDec(resultString[5]))/8;
						botText = RGB15(r1,g1,b1);						
					}

					if(cmpistr(itemString,"bottomshaddow")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						int r1=(HexToDec(resultString[0])*16+HexToDec(resultString[1]))/8;
						int g1=(HexToDec(resultString[2])*16+HexToDec(resultString[3]))/8;
						int b1=(HexToDec(resultString[4])*16+HexToDec(resultString[5]))/8;
						botTextShaddow = RGB15(r1,g1,b1);						
					}

					if(cmpistr(itemString,"nametext")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						int r1=(HexToDec(resultString[0])*16+HexToDec(resultString[1]))/8;
						int g1=(HexToDec(resultString[2])*16+HexToDec(resultString[3]))/8;
						int b1=(HexToDec(resultString[4])*16+HexToDec(resultString[5]))/8;
						nameText = RGB15(r1,g1,b1);						
					}
					if(cmpistr(itemString,"nametextshaddow")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						int r1=(HexToDec(resultString[0])*16+HexToDec(resultString[1]))/8;
						int g1=(HexToDec(resultString[2])*16+HexToDec(resultString[3]))/8;
						int b1=(HexToDec(resultString[4])*16+HexToDec(resultString[5]))/8;
						nameTextShaddow = RGB15(r1,g1,b1);						
					}
					if(cmpistr(itemString,"notetext")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						int r1=(HexToDec(resultString[0])*16+HexToDec(resultString[1]))/8;
						int g1=(HexToDec(resultString[2])*16+HexToDec(resultString[3]))/8;
						int b1=(HexToDec(resultString[4])*16+HexToDec(resultString[5]))/8;
						noteText = RGB15(r1,g1,b1);						
					}
					if(cmpistr(itemString,"notetextshaddow")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						int r1=(HexToDec(resultString[0])*16+HexToDec(resultString[1]))/8;
						int g1=(HexToDec(resultString[2])*16+HexToDec(resultString[3]))/8;
						int b1=(HexToDec(resultString[4])*16+HexToDec(resultString[5]))/8;
						noteTextShaddow = RGB15(r1,g1,b1);						
					}
					if(cmpistr(itemString,"daytext")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						int r1=(HexToDec(resultString[0])*16+HexToDec(resultString[1]))/8;
						int g1=(HexToDec(resultString[2])*16+HexToDec(resultString[3]))/8;
						int b1=(HexToDec(resultString[4])*16+HexToDec(resultString[5]))/8;
						dayText = RGB15(r1,g1,b1);						
					}
					if(cmpistr(itemString,"dayshaddow")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						int r1=(HexToDec(resultString[0])*16+HexToDec(resultString[1]))/8;
						int g1=(HexToDec(resultString[2])*16+HexToDec(resultString[3]))/8;
						int b1=(HexToDec(resultString[4])*16+HexToDec(resultString[5]))/8;
						dayTextShaddow = RGB15(r1,g1,b1);						
					}
					if(cmpistr(itemString,"datetext")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						int r1=(HexToDec(resultString[0])*16+HexToDec(resultString[1]))/8;
						int g1=(HexToDec(resultString[2])*16+HexToDec(resultString[3]))/8;
						int b1=(HexToDec(resultString[4])*16+HexToDec(resultString[5]))/8;
						dateText = RGB15(r1,g1,b1);						
					}
					if(cmpistr(itemString,"dateshaddow")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						int r1=(HexToDec(resultString[0])*16+HexToDec(resultString[1]))/8;
						int g1=(HexToDec(resultString[2])*16+HexToDec(resultString[3]))/8;
						int b1=(HexToDec(resultString[4])*16+HexToDec(resultString[5]))/8;
						dateTextShaddow = RGB15(r1,g1,b1);						
					}

					
					if(cmpistr(itemString,"showinfoicon")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						showInfoIcon = atoi(resultString);						
					}
					if(cmpistr(itemString,"infoix")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						infoIX = atoi(resultString);						
					}
					if(cmpistr(itemString,"infoiy")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						infoIY = atoi(resultString);						
					}

					if(cmpistr(itemString,"showinfoname")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						showInfoName = atoi(resultString);						
					}
					if(cmpistr(itemString,"infonx")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						infoNX = atoi(resultString);						
					}
					if(cmpistr(itemString,"infony")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						infoNY = atoi(resultString);						
					}
					
					if(cmpistr(itemString,"showinfonote")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						showInfoNote = atoi(resultString);						
					}
					if(cmpistr(itemString,"infonox")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						infoNoX = atoi(resultString);						
					}
					if(cmpistr(itemString,"infonoy")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						infoNoY = atoi(resultString);						
					}
					
					
					
					if(cmpistr(itemString,"showday")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						showDay = atoi(resultString);						
					}

					if(cmpistr(itemString,"dayx")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						DayX = atoi(resultString);						
					}
					if(cmpistr(itemString,"dayy")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						DayY = atoi(resultString);						
					}

					if(cmpistr(itemString,"showdate")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						showDate = atoi(resultString);						
					}

					if(cmpistr(itemString,"datex")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						DateX = atoi(resultString);						
					}
					if(cmpistr(itemString,"datey")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						DateY = atoi(resultString);						
					}



					if(cmpistr(itemString,"quietboot")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						quietboot = atoi(resultString);						
					}
					if(cmpistr(itemString,"hideicontext")==0){
						// set list position
						strcpy(tempString, resultString);
						temp2=0;
						while(tempString[temp2]<=0x20){
							temp2++;
						}
						temp=0;
						int ending = strlen(tempString);
						while(tempString[ending]<0x20){
							ending--;
						}
						while(temp2<=ending){
							resultString[temp] = tempString[temp2];
							temp2++;
							temp++;
						}
						resultString[temp]=0; // end the string
						hideicontext = atoi(resultString);						
					}
	
					
				} // found '='
			} // temp<length
		}
		
		
		fclose(iniFile);
		//printf("Done!\n");
	}// if imgFile
		else{
						printf("No Open clock.ini\n");
	}// fail open
}

void firstRun(void)
{
	char tempFilename[255]; // temp filename for opening
	char currentFilename[255];
	char iniData[512];

	char imagename[256];
	char name[256];
	char loadname[256];
	char note[256];

	
    DIR* current_dir;
    dirent *current_file;
    current_dir = opendir("fat:/_dstwoplug/");
	int tt=200;
    while((current_file = readdir_ex(current_dir, &st)) != NULL)
	{
		if(!S_ISDIR(st.st_mode))
		{
		tt++;
			// copy the file name to struct
			strcpy(currentFilename, current_file->d_name);
			// make filename lower case
			int i=0;
			for(i = 0; currentFilename[i]; i++) currentFilename[i] = tolower(currentFilename[i]);
			if(cmpistr(&currentFilename[strlen(currentFilename)-4], ".ini")==0){
				sprintf(tempFilename,"fat:/_imenu/_ini/%s",currentFilename);
				if(file_exists(tempFilename)==0){

					currentFilename[strlen(currentFilename)-4]=0; // trim .ini from the filename

					sprintf(imagename,"/_imenu/_images/icons/%s.bmp",currentFilename);
					sprintf(name,"%s",currentFilename);

					sprintf(tempFilename,"fat:/_dstwoplug/%s.plg",currentFilename);
					if(file_exists(tempFilename)==1){
						sprintf(loadname,"/_dstwoplug/%s.plg",currentFilename);
					}else{
						sprintf(loadname,"/_dstwoplug/%s.nds",currentFilename);
					}

					sprintf(tempFilename,"/_imenu/_ini/%s.ini",currentFilename);
					sprintf(iniData,"[plug setting]\r\nicon=%s\r\nname=%s\r\nfile=%s\r\nnumber=%d\r\ndock=0\r\nnote=Change description in .ini file.\r\narg=\r\n",imagename,name,loadname,tt);
					FILE* testRead = fopen (tempFilename, "wb"); //rb = read	
						fputs(iniData, testRead);
					fclose (testRead);
					printf("Imported %s\n",currentFilename);

					sprintf(tempFilename,"fat:/_imenu/_images/icons/%s.bmp",currentFilename);
					if(file_exists(tempFilename)==0){
						char sourcefile[255];
						sprintf(sourcefile,"fat:/_dstwoplug/%s.bmp",currentFilename);
						if(file_exists(sourcefile)==1){
							copyFile(sourcefile, tempFilename);
							printf("Copied %s\n",tempFilename);
						}
					}
					
					
				} // file_exists=0
			} // if is .ini
		} // if not DIR
	
	}// while readdir
    // attempt to return to root
	current_dir = opendir("fat:/");

}

void readFilenames(void)
{
	char tempFilename[255]; // temp filename for opening

    DIR* current_dir;
    dirent *current_file;
	number_of_files=0;
    current_dir = opendir("fat:/_imenu/_ini/");
    while((current_file = readdir_ex(current_dir, &st)) != NULL)
	{
		if(!S_ISDIR(st.st_mode))
		{
			// copy the file name to struct
			strcpy(Icons[number_of_files].filename, current_file->d_name);
			// make filename lower case
			int i=0;
			for(i = 0; Icons[number_of_files].filename[i]; i++) Icons[number_of_files].filename[i] = tolower(Icons[number_of_files].filename[i]);
			if(cmpistr(&Icons[number_of_files].filename[strlen(Icons[number_of_files].filename)-4], ".ini")==0){
				sprintf(tempFilename,"fat:/_imenu/_ini/%s",Icons[number_of_files].filename);
				number_of_files++;
			} // if is .ini
		} // if not DIR
	
	}// while readdir
}

void show_time(void)
{
int clockx = 147; // clock X
int clocky = 51; // clock Y
   
// clock size = 91x91, center = 50,50
u8 clock_x[60]= {
50,55,59,64,68,72,76,80,83,86,
89,91,93,94,95,95,95,94,93,91,
89,86,83,80,76,72,68,64,59,55,
50,45,41,36,32,28,24,20,17,14,
11,9,7,6,5,5,5,6,7,9,
11,14,17,20,24,27,32,36,41,45};
u8 clock_y[60]= {
5,5,6,7,9,11,14,17,20,24,
28,32,36,41,45,50,55,59,64,68,
72,76,80,83,86,89,91,93,94,95,
95,95,94,93,91,89,86,83,80,76,
72,68,64,59,55,50,45,41,36,32,
28,24,20,17,14,11,9,7,6,5};   


	// The coors for the seconds
	struct rtc Date;
	ds2_getTime(&Date);
	int temp = Date.seconds;
	// then clock part
	int t=0;
/*
	for(t=0; t<temp; t++)
	{
		((unsigned short*)up_screen_addr)[(clockX+clock_x[t]  -51)+(256*(clockY+clock_y[t]  -51))] = RGB15(31,31,31);
		((unsigned short*)up_screen_addr)[(clockX+clock_x[t]+1-51)+(256*(clockY+clock_y[t]  -51))] = RGB15(31,31,31);
		((unsigned short*)up_screen_addr)[(clockX+clock_x[t]  -51)+(256*(clockY+clock_y[t]+1-51))] = RGB15(31,31,31);
		((unsigned short*)up_screen_addr)[(clockX+clock_x[t]+1-51)+(256*(clockY+clock_y[t]+1-51))] = RGB15(31,31,31);
	}	
*/

	temp = Date.hours;
	t=temp/10;
	temp=temp%10;
	drawBMPframe(digitsImage, 1, clockX,clockY,t);
	drawBMPframe(digitsImage, 1, clockX+imageWidth(digitsImage),clockY,temp);
	if(Date.seconds & 1)drawBMP(colonImage, 1, clockX+(imageWidth(digitsImage)<<1),clockY);
	temp = Date.minutes;
	t=temp/10;
	temp=temp%10;
	drawBMPframe(digitsImage, 1, clockX+(imageWidth(digitsImage)<<1)+imageWidth(colonImage),clockY,t);
	drawBMPframe(digitsImage, 1, clockX+(imageWidth(digitsImage)<<1)+imageWidth(colonImage)+imageWidth(digitsImage),clockY,temp);
	
}

void sortIcons(void){
	//----------------------------------
	int x,y,temp;;
	int tempDockOrder[4];
	
	x=0; number_of_docks=0;
	for(temp=0; temp<=number_of_files; temp++){
		if(Icons[temp].dock == 1 && number_of_docks < 4){
			tempDockOrder[number_of_docks] = Icons[temp].number;
			dockOrder[number_of_docks] = temp;
			number_of_docks++;
		}else{
			tempOrder[x] = Icons[temp].number;
			iconOrder[x] = temp;
			Icons[temp].dock = 0;
			x++;
		}
	}

	number_of_files = x-1;

	// sort icons by order number
	// rearange the order, then record the new ini files
//	while(x==0){
//	x=0;
	for(x=0; x<number_of_files; x++){
		for(y=1; y<number_of_files; y++){
			if(tempOrder[y-1] > tempOrder[y]){
				temp = tempOrder[y-1];
				tempOrder[y-1] = tempOrder[y];
				tempOrder[y] = temp;
				temp = iconOrder[y-1];
				iconOrder[y-1] = iconOrder[y];
				iconOrder[y] = temp;
//				x=1;
			}
		}
	}

	for(x=0; x<number_of_docks; x++){
		for(y=1; y<number_of_docks; y++){
			if(tempDockOrder[y-1] > tempDockOrder[y]){
				temp = tempDockOrder[y-1];
				tempDockOrder[y-1] = tempDockOrder[y];
				tempDockOrder[y] = temp;
				temp = dockOrder[y-1];
				dockOrder[y-1] = dockOrder[y];
				dockOrder[y] = temp;
			}
		}
	}
	for(temp=0; temp<number_of_files; temp++){
		Icons[iconOrder[temp]].number = temp;
	}
	for(temp=0; temp<number_of_docks; temp++){
		Icons[dockOrder[temp]].number = temp;
	}
	for(temp=0; temp<number_of_files + number_of_docks; temp++){
		writeIni(temp);
	}	
}

void drawHands(void)
{

	int iWidth = hourHand[0];
	int iHeight = hourHand[1];
	int ix=clockX-(iHeight/2), iy=clockY-(iHeight/2);
	int x,y,alpha,temp, pix, pixm;
	struct rtc Date;
	ds2_getTime(&Date);
	int angle = (Date.hours % 12) * 42.66666666666667 + ((Date.minutes * 8.53)/12);

	for(y=0; y<iHeight; y++){
		for(x=0; x<iHeight; x++){
			int rx = (x-(iHeight/2)) * (BAG_Math_Cos(511-angle)) - (y-(iHeight/2)) * (BAG_MATH_SIN[511-angle])>>8;
			int ry = (x-(iHeight/2)) * (BAG_MATH_SIN[511-angle]) + (y-(iHeight/2)) * (BAG_Math_Cos(511-angle))>>8;
			if(rx>-(iWidth/2) && rx<(iWidth/2) && ry>-(iHeight/2) && ry<(iHeight/2)){
				pix = hourHand[2+((rx+(iWidth/2))+iWidth*(ry+(iHeight/2)))*2];
				pixm = hourHand[3+((rx+(iWidth/2))+iWidth*(ry+(iHeight/2)))*2];
				alpha = 255-pixm;
				temp = ((unsigned short*)up_screen_addr)[(ix+x)+(256*(iy+y))];
				int b2 = (temp>>10)&31;
				int g2 = (temp>>5)&31;
				int r2 = temp &31;
				temp = pix;
				int b1 = (temp>>10)&31;
				int g1 = (temp>>5)&31;
				int r1 = temp &31;
				temp = RGB15(mix(r2,r1,alpha),mix(g2,g1,alpha),mix(b2,b1,alpha));
				((unsigned short*)up_screen_addr)[(ix+x)+(256*(iy+y))] = temp;
			}
		}
	}		

	angle = Date.minutes * 8.53;
	iWidth = minuteHand[0];
	iHeight = minuteHand[1];
	ix=clockX-(iHeight/2);
	iy=clockY-(iHeight/2);
	for(y=0; y<iHeight; y++){
		for(x=0; x<iHeight; x++){
			int rx = (x-(iHeight/2)) * (BAG_Math_Cos(511-angle)) - (y-(iHeight/2)) * (BAG_MATH_SIN[511-angle])>>8;
			int ry = (x-(iHeight/2)) * (BAG_MATH_SIN[511-angle]) + (y-(iHeight/2)) * (BAG_Math_Cos(511-angle))>>8;
			if(rx>-(iWidth/2) && rx<(iWidth/2) && ry>-(iHeight/2) && ry<(iHeight/2)){
				pix = minuteHand[2+((rx+(iWidth/2))+iWidth*(ry+(iHeight/2)))*2];
				pixm = minuteHand[3+((rx+(iWidth/2))+iWidth*(ry+(iHeight/2)))*2];
				alpha = 255-pixm;
				temp = ((unsigned short*)up_screen_addr)[(ix+x)+(256*(iy+y))];
				int b2 = (temp>>10)&31;
				int g2 = (temp>>5)&31;
				int r2 = temp &31;
				temp = pix;
				int b1 = (temp>>10)&31;
				int g1 = (temp>>5)&31;
				int r1 = temp &31;
				temp = RGB15(mix(r2,r1,alpha),mix(g2,g1,alpha),mix(b2,b1,alpha));
				((unsigned short*)up_screen_addr)[(ix+x)+(256*(iy+y))] = temp;
			}
		}
	}		

}

void flyOut(void)
{
	// Originally had a cool animation, but it caused problems, now just clears screens.
	int temp=0;
	for(temp=0; temp<256*192; temp++){
		((unsigned short*)down_screen_addr)[temp] = 0;
		((unsigned short*)up_screen_addr)[temp] = 0;
	}
	ds2_flipScreen(UP_SCREEN, 1);
	ds2_flipScreen(DOWN_SCREEN, 1);
}

void grab_word()
{
	int x, y, temp;
	char letter=0;

	// dim the background
	int i=0;
	for(i=0; i<256*192; i++){
		int r =	((unsigned short*)down_screen_addr)[i]&31;
		int g =	(((unsigned short*)down_screen_addr)[i]>>5)&31;
		int b =	(((unsigned short*)down_screen_addr)[i]>>10)&31;
		((unsigned short*)down_screen_addr)[i] = RGB15(r>>2,g>>2,b>>2);
	}

	int* tempBuffer;
	tempBuffer = calloc((256*192*2)+2, sizeof(int));
	tempBuffer[0]=256;
	tempBuffer[1]=192;
	temp=2;
	for(y=191; y>0; y--){
		for(x=0; x<256; x++){
			tempBuffer[temp++]=((unsigned short*)down_screen_addr)[x+256*y];
			tempBuffer[temp++]=255;
		}
	}
	char text[256];
	struct rtc Date;
	char text2[256];
	sprintf(text2,"%s",text_string);
	bool escape=0;
	while(letter != 10 && escape==0){
		drawBMP(tempBuffer,0,0,0);
		draw_keyboard();
			letter = check_kb();
		if(letter)
		{
			if(letter==8)// delete
			{
				if(strlen(text_string)>0)text_string[strlen(text_string)-1]=0;  
			}else{
				//strcat(text_string, letter);
				text_string[strlen(text_string)+1]=0;
				text_string[strlen(text_string)]=letter;
			}
		}
		
		UpdatePad();
		if(Pad.Held.B)escape=1;
		
		ds2_getTime(&Date);
		if(Date.seconds & 1){sprintf(text,"%s|",text_string);}else{sprintf(text,"%s ",text_string);}
		drawText(1,1, 2, 65, 255, 191, text ,RGB15(0,0,0),0,1);
		drawText(1,1, 1, 64, 255, 191, text ,RGB15(31,31,31),0,1);
		ds2_flipScreen(DOWN_SCREEN, 1);
	}
	if(strlen(text_string)>0)text_string[strlen(text_string)-1]=0;  // remove trailing <enter>
	free(tempBuffer);
	if(escape==1)sprintf(text_string,"%s",text2);
}


void browseImage(void)
{
//	ds2_flipScreen(DOWN_SCREEN, 1);

	char tempFilename[255]; // temp filename for opening
	typedef struct
	{
		char filename[128];	// name of each .ini file
	}imageEntry;
	imageEntry images[512]; // up to 512 files in list

	int x,y,temp,temp1,temp2,line,item_num;
	char tempString[128];

	// dim the background
	int i=0;
	for(i=0; i<256*192; i++){
		int r =	((unsigned short*)down_screen_addr)[i]&31;
		int g =	(((unsigned short*)down_screen_addr)[i]>>5)&31;
		int b =	(((unsigned short*)down_screen_addr)[i]>>10)&31;
		((unsigned short*)down_screen_addr)[i] = RGB15(r>>2,g>>2,b>>2);
	}

	int* tempBuffer;
	tempBuffer = calloc((256*192*2)+2, sizeof(int));
	tempBuffer[0]=256;
	tempBuffer[1]=192;
	temp=2;
	for(y=191; y>0; y--){
		for(x=0; x<256; x++){
			tempBuffer[temp++]=((unsigned short*)down_screen_addr)[x+256*y];
			tempBuffer[temp++]=255;
		}
	}
		drawBMP(tempBuffer,0,0,0);
	u32 numf=0;

			sprintf(tempString,"%d files found", numf);
			line = 0;
			drawText(1,1, 22, line+1, 255, 191, tempString ,RGB15(0,0,0),1,0);
			drawText(1,1, 21, line, 255, 191, tempString ,RGB15(31,31,31),1,0);

		ds2_flipScreen(DOWN_SCREEN, 1);

    DIR* current_dir;
    dirent *current_file;
    current_dir = opendir("fat:/_imenu/_images/icons/");
    while((current_file = readdir_ex(current_dir, &st)) != NULL)
	{
		if(!S_ISDIR(st.st_mode))
		{
			// copy the file name to struct
			strcpy(images[numf].filename, current_file->d_name);
			// make filename lower case
			int i=0;
			for(i = 0; images[numf].filename[i]; i++) images[numf].filename[i] = tolower(images[numf].filename[i]);
			if(cmpistr(&images[numf].filename[strlen(images[numf].filename)-4], ".bmp")==0){
				numf++;
			} // if is .bmp
		} // if not DIR
	}// while readdir
//	if(numf>0)numf--;

	for(y=0; y<numf; y++){
		for(x=1; x<numf; x++){
			if(cmpistr(images[x].filename, images[x-1].filename)<0){
				sprintf(tempString,"%s",images[x].filename);
				sprintf(images[x].filename,"%s",images[x-1].filename);
				sprintf(images[x-1].filename,"%s",tempString);
			}
		}
	}
	
	item_num=0;
	bool all_done=0;

	int* tempIcon;
	sprintf(tempString,"fat:/_imenu/_images/icons/%s", images[item_num].filename);
	tempIcon=loadBMP(tempString);

	while(all_done==0){
		drawBMP(tempBuffer,0,0,0);

		temp=item_num-5;
		if(temp<0)temp=0;
		temp1=temp+11;
		if(temp1>numf)temp1=numf;
		line=0;
		for(temp2=temp; temp2<temp1; temp2++){
			sprintf(tempString,"%s", images[temp2].filename);
			line += 15;//(temp-temp2)*10;
			drawText(1,1, 17, line+1, 255, 191, tempString ,RGB15(0,0,0),1,0);
			drawText(1,1, 16, line, 255, 191, tempString ,RGB15(31,31,31),1,0);
			if(item_num==temp2){
				drawText(1,1, 5, line+1, 255, 191, ">" ,RGB15(0,0,0),1,0);
				drawText(1,1, 4, line, 255, 191, ">" ,RGB15(31,31,31),1,0);
			}
		}

		UpdatePad();
		if((Pad.Held.Up || Pad.Held.Down)){
			keyCounter++; 
			if(keyCounter==keyRepeattime)keyCounter=0;
		}
		if(Pad.Newpress.Up || Pad.Newpress.Down || Pad.Newpress.Left || Pad.Newpress.Right)keyCounter=0;		
		
		if(Pad.Held.Up && item_num>0 && keyCounter==0){
			item_num--;
			sprintf(text_string,"fat:/_imenu/_images/icons/%s", images[item_num].filename);
			tempIcon=loadBMP(text_string);
		}
		if(Pad.Held.Down && item_num<numf-1 && keyCounter==0){
			item_num++;
			sprintf(text_string,"fat:/_imenu/_images/icons/%s", images[item_num].filename);
			tempIcon=loadBMP(text_string);
		}
		if(Pad.Newpress.Left && item_num>10 && keyCounter==0){
			item_num-=9;
			sprintf(text_string,"fat:/_imenu/_images/icons/%s", images[item_num].filename);
			tempIcon=loadBMP(text_string);
		}
		if(Pad.Newpress.Right && item_num<numf-10 && keyCounter==0){
			item_num+=9;
			sprintf(text_string,"fat:/_imenu/_images/icons/%s", images[item_num].filename);
			tempIcon=loadBMP(text_string);
		}



		if(Pad.Newpress.A)all_done=1;
		drawBMP(tempIcon,0,256-imageWidth(tempIcon),0);
		ds2_flipScreen(DOWN_SCREEN, 1);
	}
	
		free(tempBuffer);
		free(tempIcon);
}


void browseNDS(void)
{
//	ds2_flipScreen(DOWN_SCREEN, 1);

	char tempFilename[255]; // temp filename for opening
	typedef struct
	{
		char filename[512];	// name of each .ini file
		bool filetype; // 0 = folder, 1 = file
	}imageEntry;
	imageEntry files[512]; // up to 512 files in list

	int x,y,temp,temp1,temp2,line,item_num;
	char tempString[128];

	// dim the background
	int i=0;
	for(i=0; i<256*192; i++){
		int r =	((unsigned short*)down_screen_addr)[i]&31;
		int g =	(((unsigned short*)down_screen_addr)[i]>>5)&31;
		int b =	(((unsigned short*)down_screen_addr)[i]>>10)&31;
		((unsigned short*)down_screen_addr)[i] = RGB15(r>>2,g>>2,b>>2);
	}

	int* tempBuffer;
	tempBuffer = calloc((256*192*2)+2, sizeof(int));
	tempBuffer[0]=256;
	tempBuffer[1]=192;
	temp=2;
	for(y=191; y>0; y--){
		for(x=0; x<256; x++){
			tempBuffer[temp++]=((unsigned short*)down_screen_addr)[x+256*y];
			tempBuffer[temp++]=255;
		}
	}
		drawBMP(tempBuffer,0,0,0);
	u32 numf=0;

    DIR* current_dir;
    dirent *current_file;
	char directory[512]; // name of directory
	sprintf(directory,"fat:/");
    current_dir = opendir(directory);
    while((current_file = readdir_ex(current_dir, &st)) != NULL)
	{
		if(!S_ISDIR(st.st_mode))
		{
			// copy the file name to struct
			strcpy(files[numf].filename, current_file->d_name);
			// make filename lower case
			int i=0;
			for(i = 0; files[numf].filename[i]; i++) files[numf].filename[i] = tolower(files[numf].filename[i]);
			if(cmpistr(&files[numf].filename[strlen(files[numf].filename)-4], ".nds")==0  || cmpistr(&files[numf].filename[strlen(files[numf].filename)-4], ".plg")==0){
				files[numf].filetype=1;
				numf++;
			} // if is .nds
		} // if not DIR
		if(S_ISDIR(st.st_mode) && cmpistr(current_file->d_name, "."))
		{
			// copy the file name to struct
			strcpy(files[numf].filename, current_file->d_name);
			// make filename lower case
			int i=0;
			for(i = 0; files[numf].filename[i]; i++) files[numf].filename[i] = tolower(files[numf].filename[i]);
			files[numf].filetype=0;
			numf++;
		} // is DIR
	}// while readdir
//	if(numf>0)numf--;

	for(y=0; y<numf; y++){
		for(x=1; x<numf; x++){
			if(cmpistr(files[x].filename, files[x-1].filename)<0){
				sprintf(tempString,"%s",files[x].filename);
				sprintf(files[x].filename,"%s",files[x-1].filename);
				sprintf(files[x-1].filename,"%s",tempString);
				temp = files[x].filetype;
				files[x].filetype = files[x-1].filetype;
				files[x-1].filetype = temp;
			}
		}
	}
	for(y=0; y<numf; y++){
		for(x=1; x<numf; x++){
			if(files[x].filetype < files[x-1].filetype){
				sprintf(tempString,"%s",files[x].filename);
				sprintf(files[x].filename,"%s",files[x-1].filename);
				sprintf(files[x-1].filename,"%s",tempString);
				temp = files[x].filetype;
				files[x].filetype = files[x-1].filetype;
				files[x-1].filetype = temp;
			}
		}
	}
	
	item_num=0;
	bool all_done=0;

	while(all_done==0){
		drawBMP(tempBuffer,0,0,0);

		temp=item_num-5;
		if(temp<0)temp=0;
		temp1=temp+10;
		if(temp1>numf)temp1=numf;
		line=12;
		for(temp2=temp; temp2<=temp1; temp2++){
			if(files[temp2].filetype==0){
				sprintf(tempString,"[%s]", files[temp2].filename);
			}else{
				sprintf(tempString,"%s", files[temp2].filename);
			}
			line += 15;//(temp-temp2)*10;
			drawText(1,1, 17, line+1, 255, 191, tempString ,RGB15(0,0,0),1,0);
			drawText(1,1, 16, line, 255, 191, tempString ,RGB15(31,31,31),1,0);
			if(item_num==temp2){
				drawText(1,1, 5, line+1, 255, 191, ">" ,RGB15(0,0,0),1,0);
				drawText(1,1, 4, line, 255, 191, ">" ,RGB15(31,31,31),1,0);
			}
		}

		drawText(1,1, 17, 1, 255, 191, directory ,RGB15(0,0,0),1,0);
		drawText(1,1, 16, 0, 255, 191, directory ,RGB15(31,31,31),1,0);

		UpdatePad();
		if((Pad.Held.Up || Pad.Held.Down)){
			keyCounter++; 
			if(keyCounter==keyRepeattime)keyCounter=0;
		}
		if(Pad.Newpress.Up || Pad.Newpress.Down || Pad.Newpress.Left || Pad.Newpress.Right)keyCounter=0;		
		
		if(Pad.Held.Up && item_num>0 && keyCounter==0){
			item_num--;
			sprintf(text_string,"%s", files[item_num].filename);
		}
		if(Pad.Held.Down && item_num<numf && keyCounter==0){
			item_num++;
			sprintf(text_string,"%s", files[item_num].filename);
		}
		if(Pad.Newpress.Left && item_num>10 && keyCounter==0){
			item_num-=9;
			sprintf(text_string,"%s", files[item_num].filename);
		}
		if(Pad.Newpress.Right && item_num<numf-10 && keyCounter==0){
			item_num+=9;
			sprintf(text_string,"%s", files[item_num].filename);
		}



		if(Pad.Newpress.A && files[item_num].filetype==1){
			//strcat(directory,files[item_num].filename);
			//strcat(directory,"/");
			all_done=1;
		}
		if(Pad.Newpress.A && files[item_num].filetype==0){
		
			if(cmpistr(files[item_num].filename, "..")==0){
				for(temp=1; temp<strlen(directory)-1; temp++){
					if(directory[temp] == 47)temp2 = temp+1;
				}
				directory[temp2]=0;
			}else{
				text_string[0]=0;
				strcat(directory,files[item_num].filename);
				strcat(directory,"/");
			}

			current_dir = opendir(directory);
			numf=0;
			while((current_file = readdir_ex(current_dir, &st)) != NULL)
			{
				if(!S_ISDIR(st.st_mode))
				{
					// copy the file name to struct
					strcpy(files[numf].filename, current_file->d_name);
					// make filename lower case
					int i=0;
					for(i = 0; files[numf].filename[i]; i++) files[numf].filename[i] = tolower(files[numf].filename[i]);
					if(cmpistr(&files[numf].filename[strlen(files[numf].filename)-4], ".nds")==0  || cmpistr(&files[numf].filename[strlen(files[numf].filename)-4], ".plg")==0){
						files[numf].filetype=1;
						numf++;
					} // if is .nds
				} // if not DIR
				if(S_ISDIR(st.st_mode) && cmpistr(current_file->d_name, "."))
				{
					// copy the file name to struct
					strcpy(files[numf].filename, current_file->d_name);
					// make filename lower case
					int i=0;
					for(i = 0; files[numf].filename[i]; i++) files[numf].filename[i] = tolower(files[numf].filename[i]);
					files[numf].filetype=0;
					numf++;
				} // is DIR
			}// while readdir
			if(numf>0)numf--;

			for(y=0; y<numf; y++){
				for(x=1; x<numf; x++){
					if(cmpistr(files[x].filename, files[x-1].filename)<0){
						sprintf(tempString,"%s",files[x].filename);
						sprintf(files[x].filename,"%s",files[x-1].filename);
						sprintf(files[x-1].filename,"%s",tempString);
						temp = files[x].filetype;
						files[x].filetype = files[x-1].filetype;
						files[x-1].filetype = temp;
					}
				}
			}
			for(y=0; y<numf; y++){
				for(x=1; x<numf; x++){
					if(files[x].filetype < files[x-1].filetype){
						sprintf(tempString,"%s",files[x].filename);
						sprintf(files[x].filename,"%s",files[x-1].filename);
						sprintf(files[x-1].filename,"%s",tempString);
						temp = files[x].filetype;
						files[x].filetype = files[x-1].filetype;
						files[x-1].filetype = temp;
					}
				}
			}
			item_num=0;

		
		}//Press A

		ds2_flipScreen(DOWN_SCREEN, 1);
	}
	
	sprintf(text_string,"%s%s",directory,files[item_num].filename);
	free(tempBuffer);
}

void browseArg(void)
{

	char tempFilename[255]; // temp filename for opening
	typedef struct
	{
		char filename[512];	// name of each .ini file
		bool filetype; // 0 = folder, 1 = file
	}imageEntry;
	imageEntry files[512]; // up to 512 files in list

	int x,y,temp,temp1,temp2,line,item_num;
	char tempString[128];

	// dim the background
	int i=0;
	for(i=0; i<256*192; i++){
		int r =	((unsigned short*)down_screen_addr)[i]&31;
		int g =	(((unsigned short*)down_screen_addr)[i]>>5)&31;
		int b =	(((unsigned short*)down_screen_addr)[i]>>10)&31;
		((unsigned short*)down_screen_addr)[i] = RGB15(r>>2,g>>2,b>>2);
	}

	int* tempBuffer;
	tempBuffer = calloc((256*192*2)+2, sizeof(int));
	tempBuffer[0]=256;
	tempBuffer[1]=192;
	temp=2;
	for(y=191; y>0; y--){
		for(x=0; x<256; x++){
			tempBuffer[temp++]=((unsigned short*)down_screen_addr)[x+256*y];
			tempBuffer[temp++]=255;
		}
	}
		drawBMP(tempBuffer,0,0,0);
	u32 numf=0;

    DIR* current_dir;
    dirent *current_file;
	char directory[512]; // name of directory
	sprintf(directory,"fat:/");
    current_dir = opendir(directory);
    while((current_file = readdir_ex(current_dir, &st)) != NULL)
	{
		if(!S_ISDIR(st.st_mode))
		{
			// copy the file name to struct
			strcpy(files[numf].filename, current_file->d_name);
			// make filename lower case
			int i=0;
			for(i = 0; files[numf].filename[i]; i++) files[numf].filename[i] = tolower(files[numf].filename[i]);
//			if(cmpistr(&files[numf].filename[strlen(files[numf].filename)-4], ".nds")==0  || cmpistr(&files[numf].filename[strlen(files[numf].filename)-4], ".plg")==0){
				files[numf].filetype=1;
				numf++;
//			} // if is .nds
		} // if not DIR
		if(S_ISDIR(st.st_mode) && cmpistr(current_file->d_name, "."))
		{
			// copy the file name to struct
			strcpy(files[numf].filename, current_file->d_name);
			// make filename lower case
			int i=0;
			for(i = 0; files[numf].filename[i]; i++) files[numf].filename[i] = tolower(files[numf].filename[i]);
			files[numf].filetype=0;
			numf++;
		} // is DIR
	}// while readdir
	if(numf>0)numf--;

	for(y=0; y<numf; y++){
		for(x=1; x<numf; x++){
			if(cmpistr(files[x].filename, files[x-1].filename)<0){
				sprintf(tempString,"%s",files[x].filename);
				sprintf(files[x].filename,"%s",files[x-1].filename);
				sprintf(files[x-1].filename,"%s",tempString);
				temp = files[x].filetype;
				files[x].filetype = files[x-1].filetype;
				files[x-1].filetype = temp;
			}
		}
	}
	for(y=0; y<numf; y++){
		for(x=1; x<numf; x++){
			if(files[x].filetype < files[x-1].filetype){
				sprintf(tempString,"%s",files[x].filename);
				sprintf(files[x].filename,"%s",files[x-1].filename);
				sprintf(files[x-1].filename,"%s",tempString);
				temp = files[x].filetype;
				files[x].filetype = files[x-1].filetype;
				files[x-1].filetype = temp;
			}
		}
	}
	
	item_num=0;
	bool all_done=0;

	while(all_done==0){
		drawBMP(tempBuffer,0,0,0);

		temp=item_num-5;
		if(temp<0)temp=0;
		temp1=temp+10;
		if(temp1>numf)temp1=numf;
		line=12;
		for(temp2=temp; temp2<temp1; temp2++){
			if(files[temp2].filetype==0){
				sprintf(tempString,"[%s]", files[temp2].filename);
			}else{
				sprintf(tempString,"%s", files[temp2].filename);
			}
			line += 15;//(temp-temp2)*10;
			drawText(1,1, 17, line+1, 255, 191, tempString ,RGB15(0,0,0),1,0);
			drawText(1,1, 16, line, 255, 191, tempString ,RGB15(31,31,31),1,0);
			if(item_num==temp2){
				drawText(1,1, 5, line+1, 255, 191, ">" ,RGB15(0,0,0),1,0);
				drawText(1,1, 4, line, 255, 191, ">" ,RGB15(31,31,31),1,0);
			}
		}

		drawText(1,1, 17, 1, 255, 191, directory ,RGB15(0,0,0),1,0);
		drawText(1,1, 16, 0, 255, 191, directory ,RGB15(31,31,31),1,0);

		UpdatePad();
		if((Pad.Held.Up || Pad.Held.Down)){
			keyCounter++; 
			if(keyCounter==keyRepeattime)keyCounter=0;
		}
		if(Pad.Newpress.Up || Pad.Newpress.Down || Pad.Newpress.Left || Pad.Newpress.Right)keyCounter=0;		
		
		if(Pad.Held.Up && item_num>0 && keyCounter==0){
			item_num--;
			sprintf(text_string,"%s", files[item_num].filename);
		}
		if(Pad.Held.Down && item_num<numf-1 && keyCounter==0){
			item_num++;
			sprintf(text_string,"%s", files[item_num].filename);
		}
		if(Pad.Newpress.Left && item_num>10 && keyCounter==0){
			item_num-=9;
			sprintf(text_string,"%s", files[item_num].filename);
		}
		if(Pad.Newpress.Right && item_num<numf-10 && keyCounter==0){
			item_num+=9;
			sprintf(text_string,"%s", files[item_num].filename);
		}



		if(Pad.Newpress.A && files[item_num].filetype==1){
			//strcat(directory,files[item_num].filename);
			//strcat(directory,"/");
			all_done=1;
		}
		if(Pad.Newpress.A && files[item_num].filetype==0){
		
			if(cmpistr(files[item_num].filename, "..")==0){
				for(temp=1; temp<strlen(directory)-1; temp++){
					if(directory[temp] == 47)temp2 = temp+1;
				}
				directory[temp2]=0;
			}else{
				text_string[0]=0;
				strcat(directory,files[item_num].filename);
				strcat(directory,"/");
			}

			current_dir = opendir(directory);
			numf=0;
			while((current_file = readdir_ex(current_dir, &st)) != NULL)
			{
				if(!S_ISDIR(st.st_mode))
				{
					// copy the file name to struct
					strcpy(files[numf].filename, current_file->d_name);
					// make filename lower case
					int i=0;
					for(i = 0; files[numf].filename[i]; i++) files[numf].filename[i] = tolower(files[numf].filename[i]);
//					if(cmpistr(&files[numf].filename[strlen(files[numf].filename)-4], ".nds")==0  || cmpistr(&files[numf].filename[strlen(files[numf].filename)-4], ".plg")==0){
						files[numf].filetype=1;
						numf++;
//					} // if is .nds
				} // if not DIR
				if(S_ISDIR(st.st_mode) && cmpistr(current_file->d_name, "."))
				{
					// copy the file name to struct
					strcpy(files[numf].filename, current_file->d_name);
					// make filename lower case
					int i=0;
					for(i = 0; files[numf].filename[i]; i++) files[numf].filename[i] = tolower(files[numf].filename[i]);
					files[numf].filetype=0;
					numf++;
				} // is DIR
			}// while readdir
//			if(numf>0)numf--;

			for(y=0; y<numf; y++){
				for(x=1; x<numf; x++){
					if(cmpistr(files[x].filename, files[x-1].filename)<0){
						sprintf(tempString,"%s",files[x].filename);
						sprintf(files[x].filename,"%s",files[x-1].filename);
						sprintf(files[x-1].filename,"%s",tempString);
						temp = files[x].filetype;
						files[x].filetype = files[x-1].filetype;
						files[x-1].filetype = temp;
					}
				}
			}
			for(y=0; y<numf; y++){
				for(x=1; x<numf; x++){
					if(files[x].filetype < files[x-1].filetype){
						sprintf(tempString,"%s",files[x].filename);
						sprintf(files[x].filename,"%s",files[x-1].filename);
						sprintf(files[x-1].filename,"%s",tempString);
						temp = files[x].filetype;
						files[x].filetype = files[x-1].filetype;
						files[x-1].filetype = temp;
					}
				}
			}
			item_num=0;

		
		}//Press A

		ds2_flipScreen(DOWN_SCREEN, 1);
	}
	
	sprintf(text_string,"%s%s",directory,files[item_num].filename);
	free(tempBuffer);
}


void editIni(char fileNumber)
{
	ds2_setCPUclocklevel(14);
	int x,y,temp;

	int i=0;
	for(i=0; i<256*192; i++){
		int r =	((unsigned short*)down_screen_addr)[i]&31;
		int g =	(((unsigned short*)down_screen_addr)[i]>>5)&31;
		int b =	(((unsigned short*)down_screen_addr)[i]>>10)&31;
		((unsigned short*)down_screen_addr)[i] = RGB15(r>>2,g>>2,b>>2);
	}

	int* tempBuffer;
	tempBuffer = calloc((256*192*2)+2, sizeof(int));
	tempBuffer[0]=256;
	tempBuffer[1]=192;
	temp=2;
	for(y=191; y>0; y--){
		for(x=0; x<256; x++){
			tempBuffer[temp++]=((unsigned short*)down_screen_addr)[x+256*y];
			tempBuffer[temp++]=255;
		}
	}

	int  m_item=0;
	bool all_done=0;
	while(all_done==0){
	drawBMP(tempBuffer,0,0,0);
	char tempString[512];
	int line=13;


	int temp2=0;
	for(temp=0; temp< strlen(Icons[fileNumber].imagename); temp++){
		if(Icons[fileNumber].loadname[temp] == 47)temp2 = temp+1;
	}
	sprintf(tempString,"File: %s", &Icons[fileNumber].loadname[temp2]);
	drawText(1,1, 22, line+1, 255, 191, tempString ,RGB15(0,0,0),1,0);
	drawText(1,1, 21, line, 255, 191, tempString ,RGB15(31,31,31),1,0);
	line+=15;

	for(temp=1; temp< strlen(Icons[fileNumber].imagename); temp++){
		if(Icons[fileNumber].imagename[temp] == 47)temp2 = temp+1;
	}
	
	sprintf(tempString,"Icon: %s", &Icons[fileNumber].imagename[temp2]);
	drawText(1,1, 22, line+1, 255, 191, tempString ,RGB15(0,0,0),1,0);
	drawText(1,1, 21, line, 255, 191, tempString ,RGB15(31,31,31),1,0);
	line+=15;
	sprintf(tempString,"Name: %s",Icons[fileNumber].name);
	drawText(1,1, 22, line+1, 255, 191, tempString ,RGB15(0,0,0),1,0);
	drawText(1,1, 21, line, 255, 191, tempString ,RGB15(31,31,31),1,0);
	line+=15;

	sprintf(tempString,"Note: %s",Icons[fileNumber].note);
	drawText(1,1, 22, line+1, 255, 191, tempString ,RGB15(0,0,0),1,0);
	drawText(1,1, 21, line, 255, 191, tempString ,RGB15(31,31,31),1,0);
	line+=15;
	sprintf(tempString,"Arg: %s",Icons[fileNumber].argument);
	drawText(1,1, 22, line+1, 255, 191, tempString ,RGB15(0,0,0),1,0);
	drawText(1,1, 21, line, 255, 191, tempString ,RGB15(31,31,31),1,0);
	line+=15;
	sprintf(tempString,"IniName: %s",Icons[fileNumber].filename);
	drawText(1,1, 22, line+1, 255, 191, tempString ,RGB15(0,0,0),1,0);
	drawText(1,1, 21, line, 255, 191, tempString ,RGB15(31,31,31),1,0);
	line+=15;
	drawText(1,1, 22, line+1, 255, 191, "Save" ,RGB15(0,0,0),1,0);
	drawText(1,1, 21, line, 255, 191, "Save" ,RGB15(31,31,31),1,0);
	line+=15;

	drawText(1,1, 8, 14+(m_item*15), 255, 191, ">" ,RGB15(0,0,0),1,0);
	drawText(1,1, 7, 13+(m_item*15), 255, 191, ">" ,RGB15(31,31,31),1,0);

		UpdatePad(); //updates both stylus and pads

		if(Pad.Newpress.Down && m_item <6)m_item++;
		if(Pad.Newpress.Up && m_item >0)m_item--;
		if(Pad.Newpress.A){
			if(m_item==0){
				// add nds/plg browser here
				text_string[0]=0; // clear the input string
				browseNDS();
				// remove "fat:" from start of string
				for(temp=4; temp<strlen(text_string); temp++){
					text_string[temp-4]=text_string[temp];
				}
				text_string[temp-4]=0;
				sprintf(Icons[fileNumber].loadname,"%s",text_string);
				text_string[temp-8]=0; // remove ".nds" from name
				temp2=1;
				for(temp=1; temp< strlen(text_string); temp++){
					if(text_string[temp] == 47)temp2 = temp+1;
				}
				sprintf(Icons[fileNumber].name,"%s",&text_string[temp2]);
				sprintf(Icons[fileNumber].note,"%s",&text_string[temp2]);
				sprintf(Icons[fileNumber].imagename,"fat:/_imenu/_images/icons/%s.bmp",&text_string[temp2]);
				if(!file_exists(Icons[fileNumber].imagename))
					sprintf(Icons[fileNumber].imagename,"fat:/_imenu/_images/icons/default.bmp");
				sprintf(Icons[fileNumber].filename,"fat:/_imenu/_images/icons/%s.ini",&text_string[temp2]);
				if(!file_exists(Icons[fileNumber].filename)){
					sprintf(Icons[fileNumber].filename,"%s.ini",&text_string[temp2]);
				}else{
					sprintf(Icons[fileNumber].filename,"newini.ini");
				}
			}

			if(m_item==1){
				// add image browser here
				text_string[0]=0; // clear the input string
				browseImage();
				sprintf(Icons[fileNumber].imagename,"%s",text_string);
				Icons[fileNumber].image = loadBMP(Icons[fileNumber].imagename);
				//all_done=1;
			}
			if(m_item==2){
				for(temp=0; temp<strlen(Icons[fileNumber].name); temp++){
					text_string[temp]=Icons[fileNumber].name[temp];
				}
				text_string[temp]=0;
				
				grab_word();
				sprintf(Icons[fileNumber].name,"%s",text_string);
			}
			if(m_item==3){
				for(temp=0; temp<strlen(Icons[fileNumber].note); temp++){
					text_string[temp]=Icons[fileNumber].note[temp];
				}
				text_string[temp]=0;
				grab_word();
				sprintf(Icons[fileNumber].note,"%s",text_string);
			}
			if(m_item==4){
				// add nds/plg browser here
				text_string[0]=0; // clear the input string
				browseArg();
				// remove "fat:" from start of string
				for(temp=4; temp<strlen(text_string); temp++){
					text_string[temp-4]=text_string[temp];
				}
				text_string[temp-4]=0;
				sprintf(Icons[fileNumber].argument,"%s",text_string);

				temp2=1;
				for(temp=1; temp< strlen(text_string); temp++){
					if(text_string[temp] == 47)temp2 = temp+1;
				}
				sprintf(Icons[fileNumber].name,"%s",&text_string[temp2]);
				sprintf(Icons[fileNumber].note,"%s",&text_string[temp2]);
				sprintf(Icons[fileNumber].imagename,"fat:/_imenu/_images/icons/%s.bmp",&text_string[temp2]);
				if(!file_exists(Icons[fileNumber].imagename))
					sprintf(Icons[fileNumber].imagename,"fat:/_imenu/_images/icons/default.bmp");
				sprintf(Icons[fileNumber].filename,"fat:/_imenu/_images/icons/%s.ini",&text_string[temp2]);
				if(!file_exists(Icons[fileNumber].filename)){
					sprintf(Icons[fileNumber].filename,"%s.ini",&text_string[temp2]);
				}else{
					sprintf(Icons[fileNumber].filename,"newini.ini");
				}


			}
			if(m_item==5){
				for(temp=0; temp<strlen(Icons[fileNumber].filename); temp++){
					text_string[temp]=Icons[fileNumber].filename[temp];
				}
				text_string[temp]=0;
				grab_word();
				sprintf(Icons[fileNumber].filename,"%s",text_string);
			}
			if(m_item==6){ // save
		
				if(cmpistr(Icons[fileNumber].filename,"newini.ini")==0 || Icons[fileNumber].filename[0]==0){
					drawBMP(tempBuffer,0,0,0);
					drawText(1,1, 22, 65, 255, 191, "Rename your new file!" ,RGB15(0,0,0),1,0);
					drawText(1,1, 21, 64, 255, 191, "Rename your new file!" ,RGB15(31,31,31),1,0);
					drawText(1,1, 22, 85, 255, 191, "[A] Continue." ,RGB15(0,0,0),1,0);
					drawText(1,1, 21, 84, 255, 191, "[A] Continue." ,RGB15(31,31,31),1,0);
					ds2_flipScreen(DOWN_SCREEN, 1);
					UpdatePad();
					while(!Pad.Newpress.A){UpdatePad();}
				}else{
					char iniData[512]; // 512 characters should be enough for all data!
					char tempFilename[255]; // to store the new ini file
					sprintf(tempFilename,"fat:/_imenu/_ini/%s",Icons[fileNumber].filename);
					remove(tempFilename);
					sprintf(iniData,"[plug setting]\r\nicon=%s\r\nname=%s\r\nfile=%s\r\nnumber=%d\r\ndock=%d\r\nnote=%s\r\narg=%s\r\n",Icons[fileNumber].imagename,Icons[fileNumber].name,Icons[fileNumber].loadname,Icons[fileNumber].number,Icons[fileNumber].dock,Icons[fileNumber].note,Icons[fileNumber].argument);
					FILE* testRead = fopen (tempFilename, "wb"); //rb = read	
						fputs(iniData, testRead);
					fclose (testRead);
					all_done=1; // ok to exit
					ds2_plug_exit();
				}
			}

		} // press A
	
		if(Pad.Newpress.B)all_done=1;
		if(Pad.Newpress.Start){ Screen_Cap(UP_SCREEN, "/top.bmp"); Screen_Cap(DOWN_SCREEN, "/bottom.bmp");}
		ds2_flipScreen(DOWN_SCREEN, 1);
	}
	ds2_setCPUclocklevel(4);

}

void newIni(void)
{
	number_of_files++;
	sprintf(Icons[number_of_files].filename,"newini.ini");
	sprintf(Icons[number_of_files].imagename,"fat:/_imenu/_images/icons/error.bmp");
	sprintf(Icons[number_of_files].name,"New Icon");
	sprintf(Icons[number_of_files].loadname,"fat:/_imenu/imenu.plg");
	Icons[number_of_files].number = 400;
	Icons[number_of_files].dock = 0;
	sprintf(Icons[number_of_files].note,"New Icon");
	sprintf(Icons[number_of_files].argument," :-)");

	editIni(number_of_files);
}

////////////////////////////////////////////////////////////////////////////////
void main(int argc, char* argv[])
{
	ds2_setCPUclocklevel(14);
	readSettignsIni();
	if(quietboot==1){
		int x,y;
		for(x=0; x<256*192; x++){
			((unsigned short*)up_screen_addr)[x] = 0;
		}
		for(x=0; x<64; x++){
			for(y=0; y<64; y++){
				((unsigned short*)up_screen_addr)[(96+x)+256*(64+y)] = loading_Pal[loading_Texture[x+64*y]];
			}
		}
		ds2_flipScreen(UP_SCREEN, 1);
	} // show logo if quietboot
	if(quietboot==0)printf_clock();

	if(file_exists("fat:/_imenu/nfr.dat")==0){
		if(quietboot==0)printf("Updating Plugin List\n");
		firstRun();
		FILE* firstrunfile=fopen("fat:/_imenu/nfr.dat","wb");	
		fclose(firstrunfile);
	}
	
	if(quietboot==0)printf("Reading plugins\n");
	readFilenames();
	int temp=0;
	if(quietboot==0)printf("Loading icons\n");
	for(temp=0; temp<number_of_files;  temp++){
		readIni(temp);
		if(file_exists(Icons[temp].imagename)){
			Icons[temp].image = loadBMP(Icons[temp].imagename);
		}else{
			Icons[temp].image = loadBMP("fat:/_imenu/_images/icons/error.bmp");
		}
		tempOrder[temp] = Icons[temp].number;
		iconOrder[temp] = temp;
	}
	
	//readIni(2);
	int t1,t2;
	if(quietboot==0)printf("Loading backgrounds\n");
	topBG = loadBMP("fat:/_imenu/_images/gui/top_bk.bmp");
	bottomBG = loadBMP("fat:/_imenu/_images/gui/lower_bk.bmp");
	dockImage = loadBMP("fat:/_imenu/_images/gui/dock.bmp");
	menuImage = loadBMP("fat:/_imenu/_images/gui/menubg.bmp");

	if(quietboot==0)printf("Loading fonts\n");
	loadFont(); loadFont1();

	if(quietboot==0)printf("Loading clock images\n");
	cursorImage = loadBMP("fat:/_imenu/_images/gui/cursor.bmp");
	moveImage = loadBMP("fat:/_imenu/_images/gui/move_cursor.bmp");
	digitsImage = loadBMP("fat:/_imenu/_images/gui/clock_digits.bmp");
	colonImage = loadBMP("fat:/_imenu/_images/gui/clock_colon.bmp");
	hourHand = loadBMP("fat:/_imenu/_images/gui/clock_hour.bmp");
	minuteHand = loadBMP("fat:/_imenu/_images/gui/clock_minute.bmp");

	if(quietboot==0)printf("Sorting Icons\n");
	sortIcons();
	if(quietboot==0)printf("Setting Layout\n");
	setLayout(); // arange the icons into pages
	if(quietboot==0)printf("Reading clock settings\n");
	readClockIni();
	
	int x,y;

	char text[100];
	int page=0,temp2=0;
	int press_time=0;
	int firstClick = 0;
	int clickTime=0;
	int stylusSpeed=0;
	bool dpad_controls=1;
	bool dock_cursor=0;
	int currentApp=0;
	bool sorting=0;
	toDay = findToday();

//	batteryCheck();
	
	if(quietboot==0)printf("Reducing CPU Speed\n");
	ds2_setCPUclocklevel(1);	
	if(quietboot==0)printf_clock();
	
	//while(!Pad.Newpress.Start)UpdatePad();
	int bgx=0;
	bgx = icon_offset - click_position - (current_page*256);
	if(bgx > 0) bgx = 0;
	if(bgx < -imageWidth(bottomBG)+256) bgx = -imageWidth(bottomBG)+256;

bool useDebug=false;	
	int oldSeconds=0;
	int seconds=1;
	int tempPage=0;
	int stylusDistance = 0;
	while(1)
	{
		//if(firstClick==1)
		if(firstClick==1)clickTime++;
//if(useDebug) printf("UpdatePad\n");
		UpdatePad(); //updates both stylus and pads
		
		int ix = 0, iy=0;



		if(Stylus.Newpress){
			press_time =0;
			dragging = 1;
			Old_Stylus_X = Stylus.X;
			click_position = Stylus.X;
			dpad_controls=0;
			
			if(firstClick==1){
				if(clickTime < 9){
					//ds2_plug_exit();
					if(cmpistr(Icons[currentApp].loadname,"none")!=0){
						char temp_text[512];
						File_Args("fat:/loadfile.dat", 2, Icons[currentApp].loadname, Icons[currentApp].argument);

						ds2_plug_exit();
					}
				}else{
					firstClick==0;
					clickTime = 0;
				}
			}else{
				firstClick=1;
				clickTime=0;
			}
		}   

		if(Stylus.Held && dragging ==1){
			stylusDistance = click_position - Stylus.X + 256;
			icon_offset = Old_Stylus_X;
			Old_Stylus_X = Stylus.X;
		} 		

		if(Stylus.Released){
			press_time=0;
			dragging = 0;
			dpad_controls = 1;
			if(stylusDistance > 356 && current_page < number_of_files>>3){
				current_page++;
				click_position-=256;
				cursor_pos=current_page<<3;
			}
			if(stylusDistance < 156 && current_page > 0){
				current_page--;
				click_position+=256;
				cursor_pos=current_page<<3;
			}
		}

		if(dragging == 0){
		   icon_offset -= ((icon_offset - click_position)/6);
		   if(icon_offset - click_position < 0.5 && icon_offset - click_position > -0.5) icon_offset = click_position;
		}   
/*		
		if(dpad_controls==0 && (Pad.Newpress.A || Pad.Newpress.Up || Pad.Newpress.Down || Pad.Newpress.Left || Pad.Newpress.Right)){
			dpad_controls=1;
			cursor_pos = current_page * 8;
		}
*/		
		
		if(Pad.Held.A && dpad_controls && sorting == 1){
			sorting = 0;
			for(temp=0; temp<number_of_files + number_of_docks; temp++){
				writeIni(temp);
			}	
//			sortIcons();
			setLayout(); // arange the icons into pages
			while(Pad.Held.A){UpdatePad();}
		}
/*
		if(Pad.Held.L && Pad.Held.R && dpad_controls && sorting == 0){
			dpad_controls = 1;
			sorting = 1;
			moveNumber = cursor_pos;
//	if(useDebug) printf("dpad, sorting, %d\n", cursor_pos);

			while(Pad.Held.L || Pad.Held.R){UpdatePad();}
		}
		
		if(Pad.Held.L && Pad.Held.R && dpad_controls && sorting == 1){
			sorting = 0;
			for(temp=0; temp<number_of_files + number_of_docks; temp++){
				writeIni(temp);
			}	
			setLayout(); // arange the icons into pages
			while(Pad.Held.L || Pad.Held.R){UpdatePad();}
		}
*/
		
		if(dpad_controls){
		if(dock_cursor==0)currentApp = iconOrder[cursor_pos];
		if(dock_cursor==1)currentApp = dockOrder[cursor_pos];
	
		if(dock_cursor==0 && Pad.Newpress.R && (((cursor_pos+8)>>3)<<3)<number_of_files){
			cursor_pos +=8;
			click_position-=256;
			current_page++;
			if(cursor_pos > number_of_files-1)cursor_pos = number_of_files-1;
		}
		if(dock_cursor==0 && Pad.Newpress.L && cursor_pos>7){cursor_pos -=8; click_position+=256; current_page--;}
		
		if(Pad.Newpress.A && sorting == 0){
			if(cmpistr(Icons[currentApp].loadname,"none")!=0){
				File_Args("loadfile.dat", 2, Icons[currentApp].loadname, Icons[currentApp].argument);
				flyOut(); // exit animation
				ds2_plug_exit();
			}
		}
		
		if((Pad.Held.Left || Pad.Held.Right)){
			keyCounter++; 
			if(keyCounter==keyRepeattime)keyCounter=0;
		}
		if(Pad.Newpress.Left || Pad.Newpress.Right){
			keyCounter=0;
//			if(useDebug) printf("Reset keyrepeat\n");
		}

		
		if(Pad.Held.Right && keyCounter==0){
		//if(useDebug) printf("Right\n");

			if(dock_cursor==0){
				temp=0;
				bool done=0;
				for(page=0; page<=number_of_files>>3; page++){
					for(y=0; y<2; y++){
						for(x=0; x<4; x++){
							if(temp<number_of_files){
								if(cursor_pos == layout[page][x][y]){
									if(done==0 && x<3 && cursor_pos+1 < number_of_files){cursor_pos++; done=1;}
									if(done==0 && x==3 && layout[page+1][0][y] == cursor_pos+5 && cursor_pos+5 < number_of_files){
										cursor_pos = layout[page+1][0][y]; 
										temp1 = current_page; current_page=cursor_pos>>3; 
										done=1; 
										if(temp1!=current_page)click_position-=256;
									}
									if(y==1 && done==0 && x==3 && layout[page+1][0][0] != -1 && cursor_pos+1 < number_of_files){
										cursor_pos = layout[page+1][0][0]; 
										temp1 = current_page; 
										current_page=cursor_pos>>3; 
										done=1; 
										if(temp1!=current_page)click_position-=256;
									}
								}
							} // temp<number_of_files
							temp++;
						}   // x 
					} // y
				} // page
			}else{
				if(cursor_pos < number_of_docks-1)cursor_pos++;
			}
		}

		if(Pad.Held.Left && keyCounter==0){
		//if(useDebug) printf("Left\n");
			if(dock_cursor==0){
				temp=0;
				bool done=0;
				for(page=0; page<=number_of_files>>3; page++){
					for(y=0; y<2; y++){
						for(x=0; x<4; x++){
							if(temp<number_of_files){
								if(cursor_pos == layout[page][x][y]){
									if(done==0 && x>0 && cursor_pos >0){cursor_pos--; done=1;}
									if(done==0 && x==0 && page > 0 && layout[page-1][3][y] >0){
										cursor_pos = layout[page-1][3][y]; 
										temp1 = current_page; 
										current_page=cursor_pos>>3; 
										done=1; 
										if(temp1!=current_page)click_position+=256;
									}
								}
							} // temp<number_of_files
							temp++;
						}   // x 
					} // y
				} // page
			}else{
				if(cursor_pos >0)cursor_pos--;
			}
		}

		if(Pad.Newpress.Up && (((cursor_pos%8)>3) || (dock_cursor==1 && number_of_files > cursor_pos))){
		//if(useDebug) printf("Up\n");

			bool done=0;
			if(dock_cursor==1 && (sorting == 0 || number_of_docks > 1)){
		//if(useDebug) printf("ok to 'up'\n");
			if((layout[current_page][cursor_pos%4][1] != number_of_files && layout[current_page][cursor_pos%4][1] !=-1)
				|| (layout[current_page][cursor_pos%4][0] != number_of_files && layout[current_page][cursor_pos%4][0] !=-1))
					dock_cursor=0;

				if(layout[current_page][cursor_pos%4][1] < number_of_files && layout[current_page][cursor_pos%4][1] >=0){
		//if(useDebug) printf("layout < numfiles\n");
					cursor_pos = (current_page*8)+4+cursor_pos;
					done=1;
					if(sorting){
						//if(useDebug) printf("sorting ok\n");

						// read current icon
						temp1 = dockOrder[moveNumber];
						// remove selection from list
						for(temp=moveNumber; temp<number_of_docks-1; temp++){
							dockOrder[temp] = dockOrder[temp+1];
						}
						number_of_files++;
						number_of_docks--;
//		if(useDebug) printf("files= %d  docks= %d\n", number_of_files, number_of_docks);
						// move list from cursor position down 1
		//if(useDebug) printf("sorting icons\n");
						for(temp=number_of_files-1; temp>cursor_pos; temp--){
							iconOrder[temp] = iconOrder[temp-1];
						}
		//if(useDebug) printf("adding cursor position\n");
						// replace cursor position with selection
						iconOrder[cursor_pos] = temp1; //moveNumber;
						moveNumber = cursor_pos; // as we are in a loop, recapture the icon
						Icons[iconOrder[cursor_pos]].dock = 0;
					}
		//if(useDebug) printf("so far so good!\n");
				}else if(done==0 && layout[current_page][cursor_pos%4][0] < number_of_files && layout[current_page][cursor_pos%4][0] >=0){
					cursor_pos = (current_page*8)+cursor_pos;
					done=1;
					//	dock_cursor=0;
					if(sorting){
						// read current icon
						temp1 = dockOrder[moveNumber];
						// remove selection from list
						for(temp=moveNumber; temp<number_of_docks-1; temp++){
							dockOrder[temp] = dockOrder[temp+1];
						}
						number_of_files++;
						number_of_docks--;
						// move list from cursor position down 1
						for(temp=number_of_files-1; temp>cursor_pos; temp--){
							iconOrder[temp] = iconOrder[temp-1];
						}
						// replace cursor position with selection
						iconOrder[cursor_pos] = temp1; //moveNumber;
						moveNumber = cursor_pos; // as we are in a loop, recapture the icon
						Icons[iconOrder[cursor_pos]].dock = 0;
					}
				}
		//if(useDebug) printf("seems ok\n");
			}else{
				if(cursor_pos >3 && done==0) cursor_pos-=4;
			}
		}

		if(Pad.Newpress.Down){
		//if(useDebug) printf("Down\n");

			bool done=0;
			if(dock_cursor==0){
				int ty=0;
				if(cursor_pos%8 > 3)ty=1;
			
				if(ty==0 && layout[current_page][cursor_pos%4][1] < number_of_files && layout[current_page][cursor_pos%4][1] >=0){
					cursor_pos +=4;
					done=1;
				}else if(ty==0 && sorting==0){
					dock_cursor=1;
					cursor_pos = cursor_pos%4;
					if(cursor_pos > number_of_docks-1)cursor_pos = number_of_docks-1;
					done=1;
				}else if(ty==0 && sorting==1 && number_of_docks<4){
					dock_cursor=1;
					cursor_pos = cursor_pos%4;
					if(cursor_pos > number_of_docks-1)cursor_pos = number_of_docks-1;
					done=1;

					temp1 = iconOrder[moveNumber];
					// remove selection from list
					for(temp=moveNumber; temp<number_of_files-1; temp++){
						iconOrder[temp] = iconOrder[temp+1];
					}
					number_of_docks+=1;
					iconOrder[number_of_files] =-1;
					number_of_files-=1;
					// move list from cursor position down 1
					for(temp=number_of_docks-1; temp>cursor_pos; temp--){
						dockOrder[temp] = dockOrder[temp-1];
					}
					// replace cursor position with selection
					dockOrder[cursor_pos] = temp1; //moveNumber;
					moveNumber = cursor_pos; // as we are in a loop, recapture the icon
					Icons[dockOrder[cursor_pos]].dock = 1;
				}
				
//				if(sorting==0){
					if(done==0 && ty==1 && layout[current_page][cursor_pos%4][1]!=-1 && ((sorting==1 && number_of_docks<4) || sorting==0)){
						dock_cursor=1;
						cursor_pos = cursor_pos%4;
						if(cursor_pos > number_of_docks-1)cursor_pos = number_of_docks-1;
						done=1;
						if(sorting){
							// read current icon
							temp1 = iconOrder[moveNumber];
							// remove selection from list
							for(temp=moveNumber; temp<number_of_files-1; temp++){
								iconOrder[temp] = iconOrder[temp+1];
							}
							number_of_docks+=1;
							iconOrder[number_of_files] =-1;
							number_of_files-=1;
							// move list from cursor position down 1
							for(temp=number_of_docks-1; temp>cursor_pos; temp--){
								dockOrder[temp] = dockOrder[temp-1];
							}
							// replace cursor position with selection
							dockOrder[cursor_pos] = temp1; //moveNumber;
							moveNumber = cursor_pos; // as we are in a loop, recapture the icon
							Icons[dockOrder[cursor_pos]].dock = 1;
						}
					}
/*
					if(sorting==0 && done==0 && ty==0 && layout[current_page][cursor_pos%4][1]==-1){
						dock_cursor=1;
						cursor_pos = cursor_pos%4;
						if(cursor_pos > number_of_docks-1)cursor_pos = number_of_docks-1;
						done=1;

						if(sorting){
							// read current icon
							temp1 = iconOrder[moveNumber];
							// remove selection from list
							for(temp=moveNumber; temp<number_of_files-1; temp++){
								iconOrder[temp] = iconOrder[temp+1];
							}
							number_of_docks+=1;
							iconOrder[number_of_files] =-1;
							number_of_files-=1;
							// move list from cursor position down 1
							for(temp=number_of_docks-1; temp>cursor_pos; temp--){
								dockOrder[temp] = dockOrder[temp-1];
							}
							// replace cursor position with selection
							dockOrder[cursor_pos] = temp1; //moveNumber;
							moveNumber = cursor_pos; // as we are in a loop, recapture the icon
							Icons[dockOrder[cursor_pos]].dock = 1;
						} //sorting

					}
*/
//				}
			}
		}

	} // if dpad_controls

	if(sorting){
		//if(useDebug) printf("still sorting!\n");
		if(!dock_cursor){
			// read current icon
			temp1 = iconOrder[moveNumber];
			// remove selection from list
			for(temp=moveNumber; temp<number_of_files-1; temp++){
				iconOrder[temp] = iconOrder[temp+1];
			}
			// move list from cursor position down 1
			for(temp=number_of_files-1; temp>cursor_pos; temp--){
				iconOrder[temp] = iconOrder[temp-1];
			}
			// replace cursor position with selection
			iconOrder[cursor_pos] = temp1; //moveNumber;
			moveNumber = cursor_pos; // as we are in a loop, recapture the icon
		}else{
			// read current icon
			temp1 = dockOrder[moveNumber];
			// remove selection from list
			for(temp=moveNumber; temp<number_of_docks-1; temp++){
				dockOrder[temp] = dockOrder[temp+1];
			}
			// move list from cursor position down 1
			for(temp=number_of_docks-1; temp>cursor_pos; temp--){
				dockOrder[temp] = dockOrder[temp-1];
			}
			// replace cursor position with selection
			dockOrder[cursor_pos] = temp1; //moveNumber;
			moveNumber = cursor_pos; // as we are in a loop, recapture the icon
		}
	}
		//if(useDebug) printf("draw bg\n");

		bgx = icon_offset - click_position - (current_page*256);
		if(bgx > 0) bgx = 0;
		if(bgx < -imageWidth(bottomBG)+256) bgx = -imageWidth(bottomBG)+256;
//		drawBMP(topBG,1,0,0);
		drawBMP(bottomBG,0,bgx,0);
		drawBMP(dockImage,0,128-(imageWidth(dockImage)>>1),192-imageHeight(dockImage));
		
	// draw all of the icons (if on screen)
	// crash happens in here someplace!
		temp=0;
		for(page=0; page<=number_of_files>>3; page++){
			for(y=0; y<2; y++){
				for(x=0; x<4; x++){
					if(temp < number_of_files){
//	if(useDebug) printf("%d, ", temp);
						int currentIcon = iconOrder[layout[page][x][y]];
						Icons[currentIcon].number = layout[page][x][y];
						temp1 = icon_offset + (x*64) - click_position+32-(imageWidth(Icons[currentIcon].image)>>1)  + (page*256) - (current_page*256);
						temp2 = icon_offset + (x*64) - click_position + (page*256) - (current_page*256);
						
						if(Stylus.Held && Stylus.X > temp1 && Stylus.X < temp1 + imageWidth(Icons[currentIcon].image) && Stylus.Y > (y*58)+29-(imageHeight(moveImage)>>1) && Stylus.Y < (y*58)+29+(imageHeight(moveImage)>>1)){
							hitIcon=1; 
							currentApp = Icons[currentIcon].number; 
							cursor_pos = Icons[currentIcon].number;
						}
						
						if(temp1 > -64 && temp1 < 320){
							//if(!dock_cursor && sorting==0 && dpad_controls && cursor_pos == layout[page][x][y]) drawCursor(temp2,(y*58)+32-(cursorHeight>>1));
							drawBMP(Icons[currentIcon].image, 0,temp1 , (y*58)+29-(imageHeight(Icons[currentIcon].image)>>1));
							if(!dock_cursor && sorting==0 && dpad_controls && cursor_pos == layout[page][x][y])
								drawBMP(cursorImage,0,temp2+32-(imageWidth(cursorImage)>>1),(y*58)+29-(imageHeight(cursorImage)>>1));
								
							//drawIcon(0,temp1 , (y*58)+32-(Icons[currentIcon].height>>1), currentIcon);
							if(!dock_cursor && sorting && dpad_controls && cursor_pos == layout[page][x][y]){
								drawBMP(moveImage,0,temp2,(y*58)+29-(imageHeight(moveImage)>>1));
							}
						if(hideicontext==0){
							sprintf(text,"%s", Icons[currentIcon].name);
							drawText(1,1,temp2+1, (y*58)+21+(imageHeight(moveImage)>>1)+1 ,temp2+64, (y*58)+32+(imageHeight(moveImage)>>1)+16,text,botTextShaddow,0,1);
							drawText(1,1,temp2, (y*58)+21+(imageHeight(moveImage)>>1),temp2+62,(y*58)+32+(imageHeight(moveImage)>>1)+16,text,botText,0,1);
						}//hideicontext
							//							if(Stylus.Held && Stylus.X > temp1 && Stylus.X < temp1+Icons[currentIcon].width && Stylus.Y > y*58 && Stylus.Y < y*58 + Icons[currentIcon].height)currentApp = currentIcon;
						} // temp1 on screen
					temp++;
					} // temp<number_of_files

				}   // x 
			} // y
		} // page
		
		ix=0;
		//if(useDebug) printf("draw docks\n");
		while(ix<number_of_docks){
			Icons[dockOrder[ix]].number = ix;
			x = (ix*64)+32-(imageWidth(Icons[dockOrder[ix]].image)>>1)+((256-(number_of_docks*64))/2);
			y = (2*64)+29-(imageHeight(Icons[dockOrder[ix]].image)>>1);
			drawBMP(Icons[dockOrder[ix]].image,0,x,y);
			if(dock_cursor && sorting && dpad_controls && cursor_pos == ix){
				drawBMP(moveImage,0,(ix*64)+32-(imageWidth(moveImage)>>1)+((256-(number_of_docks*64))/2),(2*64)+32-(imageHeight(moveImage)>>1));
			}else if (dpad_controls && cursor_pos == ix){
				if(dock_cursor && dpad_controls && cursor_pos == ix)
					drawBMP(cursorImage,0,(ix*64)+32-(imageWidth(cursorImage)>>1)+((256-(number_of_docks*64))/2),(128)+29-(imageHeight(cursorImage)>>1));
			}
			if(hideicontext==0){
				sprintf(text,"%s", Icons[dockOrder[ix]].name);
				drawText(1,1,(ix*64)+((256-(number_of_docks*64))/2), (2*64) + 54,(ix*64)+63+((256-(number_of_docks*64))/2),(2*64) + 70,text,botTextShaddow,0,1);
				drawText(1,1,(ix*64)+((256-(number_of_docks*64))/2), (2*64) + 53,(ix*64)+63+((256-(number_of_docks*64))/2),(2*64) + 70,text,botText,0,1);
			}
			if(Stylus.Held && Stylus.X > x && Stylus.X < x+Icons[dockOrder[ix]].width && Stylus.Y > y && Stylus.Y < y + Icons[dockOrder[ix]].height)currentApp = dockOrder[ix];
			ix++;
		}
		
	//if(useDebug) printf("get time\n");
	struct rtc Date;
	ds2_getTime(&Date);
// top screen
	seconds = Date.seconds;
	if(seconds != oldSeconds){
		oldSeconds = seconds;
		drawBMP(topBG,1,0,0);
	
	if(clockType==1) show_time();
	if(clockType==2) drawHands();
	if(showDay!=0){
		if(toDay==0)sprintf(text,"Sunday");
		if(toDay==1)sprintf(text,"Monday");
		if(toDay==2)sprintf(text,"Tuesday");
		if(toDay==3)sprintf(text,"Wednesday");
		if(toDay==4)sprintf(text,"Thursday");
		if(toDay==5)sprintf(text,"Friday");
		if(toDay==6)sprintf(text,"Saturday");
		drawText(0,1,DayX+1, DayY+1,256,16,text,dayTextShaddow,1,0);
		drawText(0,1,DayX, DayY,255,16,text,dayText,1,0);		
	}
	
	if(showDate!=0){
		sprintf(text,"%d/%s",Date.day, months[Date.month-1]);
		drawText(0,1,DateX+1, DateY+1,256,16,text,dateTextShaddow,1,0);
		drawText(0,1,DateX, DateY,255,16,text,dateText,1,0);		
	}

	if(showInfoIcon!=0){
		drawBMP(Icons[currentApp].image,1,infoIX, infoIY);
	}
	if(showInfoName!=0){
		sprintf(text,"%s",Icons[currentApp].name);
		drawText(0,1,1+infoNX, 1+infoNY,255,191,text,nameTextShaddow,1,0);
		drawText(0,1,infoNX, infoNY,255,191,text,nameText,1,0);
	}
	if(showInfoNote!=0){
		sprintf(text,"%s",Icons[currentApp].note);
		drawText(0,1,1+infoNoX, 1+infoNoY,255,191,text,noteTextShaddow,1,0);
		drawText(0,1,infoNoX, infoNoY,255,191,text,noteText,1,0);
	}

		sprintf(text,"%d",stylusDistance);
		drawText(0,1,1,1,256,16,text,dateTextShaddow,1,0);
		drawText(0,1,0,0,255,16,text,dateText,1,0);		
	if(useDebug==false)ds2_flipScreen(UP_SCREEN, 1);
	}// top screen	


	if(Pad.Newpress.Start){ Screen_Cap(UP_SCREEN, "/top.bmp"); Screen_Cap(DOWN_SCREEN, "/bottom.bmp");}

		if(Pad.Held.Select && dpad_controls && sorting == 0){
			while(Pad.Held.Select){UpdatePad();}
				// dim the background
				int i=0;
				for(i=0; i<256*192; i++){
					int r =	((unsigned short*)down_screen_addr)[i]&31;
					int g =	(((unsigned short*)down_screen_addr)[i]>>5)&31;
					int b =	(((unsigned short*)down_screen_addr)[i]>>10)&31;
					((unsigned short*)down_screen_addr)[i] = RGB15(r>>2,g>>2,b>>2);
				}
			int itemNumber=0;
			int* tempBuffer;
			tempBuffer = calloc((256*192*2)+2, sizeof(int));
			tempBuffer[0]=256;
			tempBuffer[1]=192;
			temp=2;
			for(y=191; y>=0; y--){
				for(x=0; x<256; x++){
					tempBuffer[temp++]=((unsigned short*)down_screen_addr)[x+256*y];
					tempBuffer[temp++]=255;
				}
			}
			
			bool exit=0;
			while(exit==0){
				UpdatePad();
				if(Pad.Newpress.B){itemNumber = -1; exit=1;}
				if(Pad.Newpress.Up && itemNumber>0){itemNumber -=1;}
				if(Pad.Newpress.Down && itemNumber<3){itemNumber +=1;}
				if(Pad.Newpress.A){exit=1; while(Pad.Held.A)UpdatePad();}

				drawBMP(tempBuffer,0,0,0);
				drawBMP(menuImage,0,128-(imageWidth(menuImage)/2), 96-(imageHeight(menuImage)/2));
				drawText(1,1,15+ 128-(imageWidth(menuImage)/2)+1, 96-(imageHeight(menuImage)/2)+11, 255,191,"Move",botTextShaddow,1,0);
				drawText(1,1,15+ 128-(imageWidth(menuImage)/2), 96-(imageHeight(menuImage)/2)  +10, 255,191,"Move",botText,1,0);
				drawText(1,1,15+ 128-(imageWidth(menuImage)/2)+1, 96-(imageHeight(menuImage)/2)+26, 255,191,"Edit",botTextShaddow,1,0);
				drawText(1,1,15+ 128-(imageWidth(menuImage)/2), 96-(imageHeight(menuImage)/2)  +25, 255,191,"Edit",botText,1,0);
				drawText(1,1,15+ 128-(imageWidth(menuImage)/2)+1, 96-(imageHeight(menuImage)/2)+41, 255,191,"Delete",botTextShaddow,1,0);
				drawText(1,1,15+ 128-(imageWidth(menuImage)/2), 96-(imageHeight(menuImage)/2)  +40, 255,191,"Delete",botText,1,0);
				drawText(1,1,15+ 128-(imageWidth(menuImage)/2)+1, 96-(imageHeight(menuImage)/2)+56, 255,191,"New",botTextShaddow,1,0);
				drawText(1,1,15+ 128-(imageWidth(menuImage)/2), 96-(imageHeight(menuImage)/2)  +55, 255,191,"New",botText,1,0);
			if(itemNumber!=-1){
				drawText(1,1,4+ 128-(imageWidth(menuImage)/2)+1, 96-(imageHeight(menuImage)/2)+11+(15*itemNumber), 255,191,">",botTextShaddow,1,0);
				drawText(1,1,4+ 128-(imageWidth(menuImage)/2), 96-(imageHeight(menuImage)/2)  +10+(15*itemNumber), 255,191,">",botText,1,0);
			}
				ds2_flipScreen(DOWN_SCREEN, 1);

				
			}
			free(tempBuffer);
			if(itemNumber==0){
				sorting = 1;
				moveNumber = cursor_pos;
				exit=1;
			}
			if(itemNumber==1){
				editIni(currentApp);
			}
			if(itemNumber==2){
				// dim the background
				int i=0;
				for(i=0; i<256*192; i++){
					int r =	((unsigned short*)down_screen_addr)[i]&31;
					int g =	(((unsigned short*)down_screen_addr)[i]>>5)&31;
					int b =	(((unsigned short*)down_screen_addr)[i]>>10)&31;
					((unsigned short*)down_screen_addr)[i] = RGB15(r>>2,g>>2,b>>2);
				}
				int* tempBuffer;
				tempBuffer = calloc((256*192*2)+2, sizeof(int));
				tempBuffer[0]=256;
				tempBuffer[1]=192;
				temp=2;
				for(y=191; y>0; y--){
					for(x=0; x<256; x++){
						tempBuffer[temp++]=((unsigned short*)down_screen_addr)[x+256*y];
						tempBuffer[temp++]=255;
					}
				}
				bool ok = 0;
				while(ok==0){
					UpdatePad();
					drawBMP(tempBuffer,0,0,0);
					sprintf(text,"Delete  %s ?",Icons[currentApp].name);
					drawText(1,1,  5, 65, 255,191,text,botTextShaddow,1,1);
					drawText(1,1,  4, 64, 255,191,text,botText,1,1);
					sprintf(text,"(Requires reboot)");
					drawText(1,1,  5, 85, 255,191,text,botTextShaddow,1,1);
					drawText(1,1,  4, 84, 255,191,text,botText,1,1);

					drawText(1,1,  5, 105, 255,191,"[A] Yes,  [B] No",botTextShaddow,1,1);
					drawText(1,1,  4, 104, 255,191,"[A] Yes,  [B] No",botText,1,1);
					if(Pad.Newpress.A){
						text[0]=0;
						sprintf(text,"fat:/_imenu/_ini/%s",Icons[currentApp].filename);
						remove(text);
						ds2_plug_exit();
						ok=1;
					}
					if(Pad.Newpress.B){
						ok=1;
					}
					ds2_flipScreen(DOWN_SCREEN, 1);
				}
			}
			if(itemNumber==3){
				newIni();
			}

		}


		ds2_flipScreen(DOWN_SCREEN, 1);
	}

}


