/*
 * Kangaroo Punch MultiPlayer Game Server Mark II
 * Copyright (C) 2020-2021  Scott Duensing
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */


#include <stdio.h>

#define MEMWATCH
#include "memwatch/memwatch.h"

#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#include "stb_image.h"

#include "stddclmr.h"


void makeFont(char *source, char *target, int pixelsW, int pixelsH, int charsW, int charCount) {
	unsigned char *font  = NULL;
	unsigned char  data  = 0;
	FILE          *out   = NULL;
	int            bits  = 0;
	int            x;
	int            y;
	int            n;
	int            w;
	int            h;

	// Load font atlas from disk.
	font = stbi_load(source, (int *)&w, (int *)&h, (int *)&n, 3);
	if (!font) return;

	// Create data file for font.
	out = fopen(target, "wb");
	if (!out) {
		stbi_image_free(font);
		return;
	}

	// Provide some metadata for enhancement later.
	fputc(pixelsW,   out);  // Width of characters
	fputc(pixelsH,   out);  // Height of characters
	fputc(charsW,    out);  // Number of characters per row
	fputc(charCount, out);  // Number of characters - 1

	// Convert bitmap to actual bits.
	for (y=0; y<h; y++) {
		for (x=0; x<w; x++) {
			data <<= 1;
			data |= (font[(y * w * 3) + (x * 3)] != 0);
			bits++;
			if (bits > 7) {
				bits = 0;
				fputc(data, out);
			}
		}
	}

	fclose(out);

	// Clean up.
	stbi_image_free(font);
}


int main(int argc, char *argv[]) {
	(void)argc;
	(void)argv;

	makeFont("/home/scott/code/kpmpgsmkii/font/data/vga8x8.png",  "/home/scott/code/kpmpgsmkii/bin/data/vga8x8.dat",  8,  8, 16, 255);
	makeFont("/home/scott/code/kpmpgsmkii/font/data/vga8x14.png", "/home/scott/code/kpmpgsmkii/bin/data/vga8x14.dat", 8, 14, 16, 255);
	makeFont("/home/scott/code/kpmpgsmkii/font/data/vga8x16.png", "/home/scott/code/kpmpgsmkii/bin/data/vga8x16.dat", 8, 16, 16, 255);

	return 0;
}
