#include<string.h>
#include<time.h>
#include<allegro.h>
#include"error.h"
#include"graph.h"   // graphics
#include"game.h"
#include"menu.h"
#include"consts.h"
#include"player.h"
#include"globals.h"

bool invert=false;

COLOR_MAP additive;

volatile int counter;
void frameskiphandle(...)
{
 counter++;
}
END_OF_FUNCTION(frameskiphandle);

volatile int framecounter;
volatile int fps;
void framecounterhandle(...)
{
 fps=framecounter;
 framecounter=0;
}
END_OF_FUNCTION(framecounterhandle);

void additive_calc(PALETTE pal, int x, int y,RGB *rgb)
{
 int r, g, b;

 r = (int)pal[x].r/* *2 */ + (int)pal[y].r;
 g = (int)pal[x].g/* *2 */ + (int)pal[y].g;
 b = (int)pal[x].b/* *2 */ + (int)pal[y].b;

 rgb->r = MIN(r, 63);
 rgb->g = MIN(g, 63);
 rgb->b = MIN(b, 63);

}

void swhelp()
{
 allegro_message("Commandline help:\7\n-help, -h and -?     \7shows the commandline help\n\7\n-invert    inverts the colors");
 exit(0);
}

void select_gfx_mode()
{
 int card,w,h,ret;

 set_gfx_mode(GFX_SAFE,320,200,0,0);
 do
 {
  if(!gfx_mode_select(&card,&w,&h)) gen_error(ERR_ABORT);
 } while(set_gfx_mode(card,w,h,0,0)<0);
}

void invert_palette()
{
 PALETTE pal;
 get_palette(pal);
 for(int n=0;n<256;n++)
 {
  pal[n].r=63-pal[n].r;
  pal[n].g=63-pal[n].g;
  pal[n].b=63-pal[n].b;
 }
 set_palette(pal);
}

void init()
{
 allegro_init();
 install_timer();

 srand(time(NULL));

 LOCK_VARIABLE(counter);
 LOCK_VARIABLE(framecounter);
 LOCK_VARIABLE(fps);
 LOCK_FUNCTION(frameskiphandle);
 LOCK_FUNCTION(framecounterhandle);
 install_int_ex(frameskiphandle,MSEC_TO_TIMER(1000/framerate));
 install_int_ex(framecounterhandle,BPS_TO_TIMER(1));

 install_keyboard();
 install_mouse();
 select_gfx_mode();

 screen2=create_bitmap(SCREEN_W,SCREEN_H);
 if(screen2==NULL) gen_error(ERR_MEMORY);

 graph=load_datafile("graph.dat");
 if(graph==NULL) gen_error(ERR_FILE,"graph.dat");
 set_palette((PALETTE)graph[gamepal].dat);
 if(invert)
 {
  invert_palette();
 }

 // create nescessary color tables:
 create_color_table(&additive,(PALETTE)graph[gamepal].dat,additive_calc,NULL);

}

int main(int argc, char *argv[])       // MAIN handels the menu
{
 if(argc>1)
 {
  for(int l=1;l<argc;l++)
  {
   if(strcmp(argv[l],"-help")==0
      || strcmp(argv[l],"-h")==0
      || strcmp(argv[l],"-?")==0) swhelp();
   if(strcmp(argv[l],"-invert")==0) invert=true;
  }
 }

 init();

 stretch_blit((BITMAP*)graph[title].dat,screen,0,0,640,480,0,0,SCREEN_W,SCREEN_H);
 readkey();

 int sel;
 do
 {
  sel=menu();

  if(sel==1) play();

 } while(sel!=3);


 return 0;
}
END_OF_MAIN()
