#define MAX_SPRITES_ON_SCREEN 64
#define MAX_TEXT_ON_SCREEN 32

union screen_bitmap
{
  struct bitmap *bitmap;
  struct entitybitmap *mobmap;
};

struct screen_sprite
{
  unsigned x;
  unsigned y;
  unsigned char type;
  unsigned char side;
  unsigned char dist;
  union screen_bitmap scrbitmap;
} sprite_stack[MAX_SPRITES_ON_SCREEN];

unsigned char screen_sprite_count = 0;

struct screen_text
{
  char *str;
  unsigned x, y;
  unsigned char color;
} screen_text[MAX_TEXT_ON_SCREEN];

unsigned char screen_text_count = 0;

#define SPRTYPE_SPRITE 0
#define SPRTYPE_MOB 1

unsigned find_scrsprite_index(unsigned char dist)
{
  unsigned n;

  if(screen_sprite_count == MAX_SPRITES_ON_SCREEN) return -1;

  for(n=0;n<screen_sprite_count;n++)
    if(sprite_stack[n].dist > dist) break;

  memmove(&sprite_stack[n+1], &sprite_stack[n], (screen_sprite_count-n)*sizeof(struct screen_sprite));

  return n;
}

void push_scrbitmap(unsigned x, unsigned y, struct bitmap *bitmap, unsigned char dist)
{
  unsigned index = find_scrsprite_index(dist);

  if(index == -1) return;

  sprite_stack[index].type = SPRTYPE_SPRITE;
  sprite_stack[index].x = x;
  sprite_stack[index].y = y;
  sprite_stack[index].dist = dist;
  sprite_stack[index].scrbitmap.bitmap = bitmap;

  screen_sprite_count++;
}

void push_scrmobmap(unsigned x, unsigned y, struct entitybitmap *bitmap, unsigned char side, unsigned char dist)
{
  unsigned index = find_scrsprite_index(dist);

  if(index == -1) return;

  sprite_stack[index].type = SPRTYPE_MOB;
  sprite_stack[index].x = x;
  sprite_stack[index].y = y;
  sprite_stack[index].dist = dist;
  sprite_stack[index].scrbitmap.mobmap = bitmap;
  sprite_stack[index].side = side;

  screen_sprite_count++;
}

void push_text(unsigned x, unsigned y, unsigned char color, char *text)
{
  unsigned char index = screen_text_count;

  if(index == MAX_TEXT_ON_SCREEN) return;

  screen_text[index].color = color;
  screen_text[index].x = x;
  screen_text[index].y = y;
  screen_text[index].str = text;

  screen_text_count++;
}

void draw_screen_texts(void)
{
  while(screen_text_count)
  {
    screen_text_count--;
    print_text(screen_text[screen_text_count].x, screen_text[screen_text_count].y, 
               screen_text[screen_text_count].color, screen_text[screen_text_count].str);
  }
}

void draw_screen_sprites(void)
{
  unsigned n;

  memset(usedpixels, 0, sizeof(usedpixels));

  for(n=0;n<screen_sprite_count;n++)
  {

    if(sprite_stack[n].type == SPRTYPE_SPRITE)
      draw_bitmap(sprite_stack[n].x,
                  sprite_stack[n].y,
                  sprite_stack[n].scrbitmap.bitmap);
    else if(sprite_stack[n].type == SPRTYPE_MOB)
      draw_mob_side(sprite_stack[n].x,
                    sprite_stack[n].y,
                    sprite_stack[n].scrbitmap.mobmap,
                    sprite_stack[n].side);
  }

  screen_sprite_count = 0;
}
