#include <allegro5\allegro.h>
#include <allegro5\allegro_primitives.h>
#include <allegro5\allegro_font.h>

#include <iostream>
#include <stdio.h>

const int WIDTH = 800;
const int HEIGHT = 600;

bool moveup = false;
bool movedown = false;
bool moveleft = false;
bool moveright = false;

int x = 300;
int y = 300;

bool trueevent = false;
bool done = false;

double fps, curTime, lastTime;

int main(void)
{      
  //Allegro variables
  ALLEGRO_DISPLAY *display = NULL;
  ALLEGRO_EVENT_QUEUE *event_queue = NULL;
  ALLEGRO_FONT *stdFont = NULL;
  
  //Initialization Functions
  if(!al_init())
    return -1;

  al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_REQUIRE);

  display = al_create_display(WIDTH, HEIGHT);

  if(!display)
    return - 1;

  al_init_primitives_addon();
  al_init_font_addon();
  al_install_keyboard();  

  stdFont = al_create_builtin_font();

  event_queue = al_create_event_queue();    

  al_register_event_source(event_queue, al_get_keyboard_event_source());  
  al_register_event_source(event_queue, al_get_display_event_source(display));

  lastTime = 0.0;

  while(!done)
  {
    ALLEGRO_EVENT ev;  
    
    trueevent = al_get_next_event(event_queue, &ev);

     if(trueevent)
    {
      if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
      { 
        done = true; 
      }

      else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
      {
		printf("Allegro Event %d %f\n", ev.keyboard.keycode, al_get_time());
        switch(ev.keyboard.keycode)
        {
        case ALLEGRO_KEY_ESCAPE:
          done = true;
          break;
        case ALLEGRO_KEY_UP:
          moveup = true;
          movedown = false;
          break;
        case ALLEGRO_KEY_DOWN:
          movedown = true;
          moveup = false;
          break;
        case ALLEGRO_KEY_LEFT:
          moveleft = true;
          moveright = false;
          break;
        case ALLEGRO_KEY_RIGHT:
          moveright = true;
          moveleft = false;
          break;        
        }        
      }      
    }

    if(al_is_event_queue_empty(event_queue)) // Added To Try And Fix Delay Problem !!!
    {
    curTime = al_get_time();
      if(moveup)    
        y -= 1;      
      if(movedown)    
        y += 1;    
      if(moveleft)    
        x -= 1;    
      if(moveright)    
        x += 1;    
    
    fps = 1.0 / (curTime - lastTime);
      al_draw_filled_rectangle(x, y, x + 50, y + 50, al_map_rgb(0, 200, 0));    
    //al_draw_textf(stdFont, al_map_rgb(100,100,100), 5, 5, ALLEGRO_ALIGN_LEFT, "FPS: %f", fps);    
      al_flip_display();
      al_clear_to_color(al_map_rgb(0,0,0));
    lastTime = curTime;
    }    
  }
  al_destroy_event_queue(event_queue);
  al_destroy_display(display);
  al_destroy_font(stdFont);
  return 0;
}
