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

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

#include "fonts.c"

/*struct font
{
  struct fontchar
  {
    unsigned char bitmap[8];
  } chr[256];
} font;

void draw_chr(unsigned x, unsigned y, unsigned char color, unsigned char chr)
{
  unsigned char *chrptr = font.chr[chr].bitmap;
  unsigned char n;
  unsigned char w;

  for(n=0;n<8;n++)
  {
    for(w=0;w<8;w++)
    {
      if((*chrptr >> w) & 1)
        put_pixel(x+w, y, color);
    }
    chrptr++;
    y++;
  }
}

void print_text(unsigned x, unsigned y, unsigned char color, char *str)
{
  unsigned n = 0;

  while(*str)
  {
    if(*str == '\n')
    {
      y += 9;
      n = 0;
    }
    else
    {
      draw_chr(x+n, y, color, *str);
      n += 9;
    }
    str++;
  }
}*/

void set_font_pixel(unsigned char chr, unsigned char x, unsigned char y)
{
  unsigned char *chrptr = &font.chr[chr].bitmap[y];

  if(!((*chrptr >> x) & 1))
    *chrptr |= 1 << x;
  else
    *chrptr &= ~(1 << x);
}

void reset_chr(unsigned char chr)
{
  unsigned char *chrptr = font.chr[chr].bitmap;

  memset(chrptr, 0, 8);
}

/*int load_font(char *filename)
{
  FILE *fp = fopen(filename, "rb");
  if(!fp) return -1;

  if(!fread(&font, sizeof(struct font), 1, fp))
    return -1;

  fclose(fp);
}*/

int save_font(char *filename)
{
  FILE *fp = fopen(filename, "wb");
  if(!fp) return -1;

  if(!fwrite(&font, sizeof(struct font), 1, fp))
    return -1;

  return fclose(fp);
}

int main(int argc, char *argv[])
{
  unsigned x = 0;
  unsigned y = 0;
  unsigned char chr = 0;
  SDL_Scancode i;
  unsigned char width, height;
  char msg[100];

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

  if(argc == 2)
  {
    load_font(argv[1]);
  }

  init_screen_sdl("Font editor");

  while(1)
  {
    fill_screen(7);

    sprintf(msg, "Character: %c (hex: %.2X)", chr, chr);
    print_text(20, 10, 0, msg);

    draw_rectangle(20, 20, 8, 8, 0);
    draw_chr(20, 20, 0xF, chr);

    print_text(10, 40, 0, "The quick brown fox jumps over\nthe lazy dog.");

    print_text(10, 60, 0, "ABCDEFGHIJKLMNOPQRSTUVWXYZ?\nabcdefghijklmnopqrstuvwxyz!");
    print_text(10, 80, 0, "1234567890+-*/");

    update_screen();

    i = get_input(20+x, 20+y);
    if(i == KEY_PLUS) chr++;
    if(i == KEY_MINUS) chr--;
//    if(i == KEY_PLUS || i == KEY_MINUS)
//      printf("Hex code: %.2X - Character: %c\n", chr, chr);

    if(i == KEY_0)
      reset_chr(chr);

    if(i == KEY_RIGHT) if(x < 7) x++;
    if(i == KEY_LEFT) if(x) x--;
    if(i == KEY_UP) if(y) y--;
    if(i == KEY_DOWN) if(y < 7) y++;
    if(i == KEY_SPACE)
    {
      set_font_pixel(chr, x, y);
    }
    if(i == KEY_F2)
      save_font(argv[1]);

  }

  return 0;
}
