// include files ---------------
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bmpload.h"

char   *opt_bmpfile;
char   *opt_fontfile;
char    opt_asciilow;
char    numChars = 0;

typedef struct {
  short  w;
  short  h;
  char   bmBits[1024];
} FontChar;


BMPImage  *bmp;
FontChar   font[256];


void Help()
{
  printf(
    "Usage:  BMPFONT [.bmp file] [.fnt file] [ascii-low]\n"
    "\n"
    "BMPFONT converts a windows 256 color bitmap file into a k/os v2 font."
  );

}


unsigned imagesize(int w, int h)
{
  return w * ((h + 7)/8)+4;
}


int getPixel( int x, int y )
{
  return  bmp->bmBits[x+y*bmp->w];
}


void convChar(int left, int top, int w, int h)
{
  FontChar *fc = &font[numChars];
  memset(fc, 0, sizeof(FontChar));
  
  char *d = fc->bmBits;
  fc->w = w;
  fc->h = h;

  for (int y=0; y < h; y+= 8)
    for (int x=0; x < w; x++) {
      for (int b=0; b<8; b++)
        if (getPixel(x+left,y+b+top) == 15)
          *d |= 1<<b;
      *d++;
    }
}


void Convert()
{
  numChars = 0;

  for (int y=0; y < bmp->h; y++)  {
    int maxCh = 0;

    for (int x=0;  x < bmp->w; x++)  {
      int cw = 0, ch = 0;
      // find out width and height of the character
      //
      while (getPixel(x+cw, y) != 0 && (x+cw < bmp->w))
        cw++;
      while (getPixel(x, y+ch) != 0 && (y+ch < bmp->h))
        ch++;

      if (cw != 0 && ch != 0) {
        convChar(x, y, cw, ch);
        printf( "# %3d:  %d x %d pixels\n",
                numChars+opt_asciilow, cw, ch );
        numChars++;
      }

      // advance to next character, and note down the
      // maximum character height
      //
      x += cw;
      if (ch > maxCh)
        maxCh = ch;
    }

    // advance to the next line
    //
    y += maxCh;
    if (maxCh)
      printf("\n");
  }

  printf("%d characters converted.\n", numChars);
}


void Save()
{
  FILE *f = fopen(opt_fontfile, "wb");
  if (!f) {
    perror("");
    return;
  }

  fwrite(&numChars,     sizeof(numChars), 1, f);
  fwrite(&opt_asciilow, sizeof(numChars), 1, f);

  for (int i=0; i<numChars; i++)
    fwrite(&font[i], imagesize(font[i].w, font[i].h), 1, f);

  fclose(f);
}



void main( int argc, char *argv[] )
{
  printf( "Bitmap to Font converter v0.2\n"
          "Copyright (c)2001 by thomas.kindler@gmx.de.\n\n" );

  if (argc != 4) {
    Help();
    return;
  }

  opt_bmpfile  = argv[1];
  opt_fontfile = argv[2];
  opt_asciilow = atoi(argv[3]);

  bmp = BMP_Load( opt_bmpfile );
  if (!bmp) return;

  Convert();
  Save();
}


