/* Stolen from bdf2psf:

     convert unicode BDF fonts to Linux console fonts
     Copyright © 2005 Anton Zinoviev <anton@lml.bas.bg>
     Contains code from the bdftopsf.pl utility (Terminus font suite)
     Copyright © 2004 Dimitar Toshkov Zhekov

     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 2 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.

     If you have not received a copy of the GNU General Public License
     along with this program, write to the Free Software Foundation, Inc.,
     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdio.h>
#include <wchar.h>
#include <locale.h>
#include <langinfo.h>
#include <string.h>
#include <stdlib.h>
#include "psf.h"

int version;
void header(int width, int height, int font_size, int sfm) {
	int matrix_row_size = (width + 7) / 8;
	int matrix_size = matrix_row_size * height;
	
	version = width != 8 || height >= 256 || (font_size != 256 && font_size != 512);
	if (!version) {
		printf("%c%c", 0x36, 0x4);
		printf("%c%c", (font_size == 512) + sfm*2, height);
	} else {
		setlocale(LC_ALL,"");
		if (strcmp(nl_langinfo(CODESET), "UTF-8")) {
			printf("erf, need UTF-8 locale\n");
			exit(1);
		}
		printf("%c%c%c%c", 0x72, 0xb5, 0x4a, 0x86);
		printf("%c%c%c%c", 0x00, 0x00, 0x00, 0x00);
		printf("%c%c%c%c", 0x20, 0x00, 0x00, 0x00);
		printf("%c", sfm);
		printf("%c%c%c", 0x00, 0x00, 0x00);
		printf("%c%c", font_size & 0xff, font_size >> 8);
		printf("%c%c", 0x00, 0x00);
		printf("%c%c%c", matrix_size & 0xff, (matrix_size >> 8) & 0xff, (matrix_size >> 16));
		printf("%c", 0x00);
		printf("%c%c", height & 0xff, height >> 8);
		printf("%c%c", 0x00, 0x00);
		printf("%c%c", width & 0xff, width >> 8);
		printf("%c%c", 0x00, 0x00);
	}
}

void sfm(wchar_t wc) {
	if (version)
		printf("%lc%c", wc, 0xFF);
	else
		printf("%c%c%c%c", wc & 0xff, wc >> 8, 0xFF, 0xFF);
}
