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

// A cell can be at most 16 wide by 32 high
// Rows are arranged left->right, top->bottom
// ie row 0 is the top row of the character cell
typedef struct
	{
	unsigned short row[32];
	} Cell;

struct Font
	{
	char *name;
	int width;
	int height;
	Cell map[256];
	};

main(int argc, char *argv[])
	{
	char *fname = argv[1];
	char *ptr,line[128];
	FILE *in,*out;
	Cell *cur;
	int i,row;
	struct Font f;

	for(i=0; i<256; ++i)
	   for(row=0; row<32; ++row)
		f.map[i].row[row]=0;

	in = fopen(fname,"r");
	if (!in) {
	   printf("Usage: compilefont font-file\n");
	   exit(1);
	   }

	while(1) {
	   if (fgets(line,127,in) == NULL) break;
	   ptr = line + strlen(line)-1;
	   while(ptr != line && *ptr<32) *(ptr--)=0;

	   if (line[0] == '#') {
		if (!strncmp(line+2,"font ",5)) 
		   f.name = strdup(line+7);
		if (!strncmp(line+2,"width ",6)) 
		   f.width = atoi(line+8);
		if (!strncmp(line+2,"height ",7)) 
		   f.height = atoi(line+9);
		if (!strncmp(line+2,"ASCII ",6)) {
		   cur = f.map + atoi(line+8);
		   row = 0;
		   }
		}
	   else if (line[0] == '+') {
		unsigned int mask=1,val=0;
		for(i=1; line[i]; ++i,mask<<=1)
		   if (line[i] != '.') val += mask;
		cur->row[row++] = val;
		}
	   }

	fclose(in);

	sprintf(line,"font_%s.c",f.name);
	out = fopen(line,"w");

	fprintf(out,"#define FONT_WIDTH 16\n");
	fprintf(out,"#define FONT_HEIGHT 32\n\n");

	fprintf(out,"static unsigned short FontMap[256 * 32 + 1] = {\n",f.name);

	for(i=0; i<256; ++i) {
	   for(row=0; row<32; ++row)
		fprintf(out,"%d,",f.map[i].row[row]);
	   fprintf(out,"\n");
	   }
	fprintf(out," 0  };\n");
	fclose(out);
	}
