//
//  If you have any questions regarding the code, contact me
//  via the method specified at  http://www.sebastianmihai.com
//  (operational in 2012), and I will try my best to help.
//
//                             Sebastian Mihai, 2012
//
#include <lynx.h>
#include <tgi.h>
#include <joystick.h>
#include <conio.h>
#include <6502.h>
#include "../resident/resident.h"
#include "../resident/abcmusic.h"

#define tgi_sprite(spr) tgi_ioctl(0, (unsigned)(spr))

extern char lynxtgi[]; // I am going to link in the tgi driver statically 
extern char lynxjoy[]; // I am going to link in the joy driver statically 

extern void init_irq(void);
extern void install_irq(unsigned char num, unsigned func );
extern void vbl(void);
#define enable_irq(n)\
  asm(" lda #$80\n"\
      " tsb $fd01+"#n"*4\n")	/* enable interrupt of timer n */

extern unsigned char drawPending;
extern unsigned char drawpage;

char a = 1;
char *dummy = "dummy";

//
// Display the back buffer
// Note: Lynx resolution is 160 x 102
//
void SwapBuffers( void ) {
	// Signal the interrupt routine to display our hidden buffer
	drawPending = 1;
	// Wait until buffer is on screen
	while (drawPending) ;
}

int intro(void) 
{
	unsigned char joy;
	char *title = "C A T K A N O I D";
	unsigned char titleColour = 0;

    SwapBuffers();

    // Make screen black
    tgi_clear();
    
	SwapBuffers();

	// wait for any button press
	joy = joy_read(JOY_1);
	while ( !joy ) {
		// Now we can draw something on the hidden buffer
		tgi_setpalette(tgi_getdefpalette());
		tgi_setcolor(COLOR_BLACK);
		tgi_bar(0,0,159,101);

		tgi_setbgcolor(COLOR_BLACK);
		tgi_setcolor( titleColour );
		tgi_outtextxy(12,20, "C");
		tgi_setcolor( (titleColour+1) % 16 );
		tgi_outtextxy(28,20, "A");
		tgi_setcolor( (titleColour+2) % 16 );
		tgi_outtextxy(44,20, "T");
		tgi_setcolor( (titleColour+3) % 16 );
		tgi_outtextxy(60,20, "K");
		tgi_setcolor( (titleColour+4) % 16 );
		tgi_outtextxy(76,20, "A");
		tgi_setcolor( (titleColour+5) % 16 );
		tgi_outtextxy(92,20, "N");
		tgi_setcolor( (titleColour+6) % 16 );
		tgi_outtextxy(108,20, "O");
		tgi_setcolor( (titleColour+7) % 16 );
		tgi_outtextxy(124,20, "I");
		tgi_setcolor( (titleColour+8) % 16 );
		tgi_outtextxy(140,20, "D");
		
		titleColour++;
		if( titleColour > 15 ) titleColour = 0;
		
		tgi_setcolor(COLOR_LIGHTPURPLE);
		tgi_outtextxy(16,60, "Press any button");
		tgi_outtextxy(46,68, "to start");
		
		tgi_setcolor(COLOR_GREY);
		tgi_outtextxy(8,94, "by Sebastian Mihai");

		SwapBuffers();
		joy = joy_read(JOY_1);
	}
	// and wait for the release!
	while( joy ) {
		joy = joy_read(JOY_1);
	}

    return MAINGAME;
} 

void start_irqs(void)
{
    tgi_install(&lynxtgi);
    joy_install(&lynxjoy);
    tgi_setdrawpage(drawpage); // Set page for drawing stuff on. Can be 0 or 1.     tgi_init();
    silence();
    init_irq();
    //install_uploader(_9600Bd);
    install_irq(2, (int)&vbl);
    enable_irq(2);
    CLI();
}
