#include <stdio.h>
#include <stdlib.h>

#include "structs.c"
#include "sdlfuncs.c"
#include "dbuff.c"

#include "bitmap.c"

int save_bitmap(char *filename, struct bitmap *bitmap)
{
  unsigned write_count;
  FILE *fp = fopen(filename, "wb");
  if(!fp) return 1;

  fputc(bitmap->width, fp);
  fputc(bitmap->height, fp);

  write_count = bitmap->width * bitmap->height;
  if(!fwrite(bitmap->bitmap, write_count, 1, fp))
  {
    error1:
    puts("Error while saving");
    exit(1);
  }

  return fclose(fp);
}

int main(int argc, char *argv[])
{
  unsigned x = 0;
  unsigned y = 0;
  unsigned char color = 1;
  SDL_Scancode i;
  struct bitmap bitmap;
  unsigned char width, height;

  if(argc < 2)
  {
    noargs:
    puts("Not enough arguments!");
    puts(">sprtedit [filename] [width] [height]");
    exit(1);
  }

  if(argc == 2)
  {
    load_bitmap(argv[1], &bitmap, &width, &height);
  }

  else if(argc < 4)
    goto noargs;
  else
  {
    width = atoi(argv[2]);
    height = atoi(argv[3]);

    if(allocate_bitmap(width, height, &bitmap))
    {
      error1:
      puts("Out of memory!");
      exit(1);
    }
    fill_bitmap(&bitmap, -1);
  }

  init_screen_sdl("Sprite editor");

  while(1)
  {
    fill_screen(1);

    draw_rectangle(20, 20, bitmap.width, bitmap.height, ~color);
    draw_bitmap(20, 20, &bitmap);

    update_screen();

    i = get_input(20+x, 20+y);
    if(i == KEY_0) color = 0;
    if(i >= KEY_1 && i <= KEY_9) color = 1+i-KEY_1;
    if(i >= KEY_A && i <= KEY_F) color = 10+i-KEY_A;
    if(i == KEY_G) color = -1;

    if(i == KEY_RIGHT) if(x < 320) x++;
    if(i == KEY_LEFT) if(x) x--;
    if(i == KEY_UP) if(y) y--;
    if(i == KEY_DOWN) if(y < 200) y++;
    if(i == KEY_SPACE)
    {
      store_pixel(&bitmap, x, y, color);
    }
    if(i == KEY_F2)
      save_bitmap(argv[1], &bitmap);
  }

  return 0;
}
