#!/bin/sh
#   font2c - convert a pcb font to simplified embedded font structs for pcb-rnd
#   Copyright (C) 2016 Tibor 'Igor2' Palinkas
#
#   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.
#
#   You should have received a copy of the GNU General Public License along
#   with this program; if not, write to the Free Software Foundation, Inc.,
#   31 Milk Street, # 960789 Boston, MA 02196 USA.
#
#   http://www.repo.hu/projects/pcb-rnd
#   http://www.repo.hu/projects/librnd

awk '

BEGIN {
	minx = 100000
	miny = 100000
	maxx = 0
	maxy = 0
	print "/* This file is autogenerated by font2c.sh - DO NOT EDIT */"
	print ""
	print "/* Internal copy of the default font; used when no font file is found */"
	print ""
}

function bump(x, y)
{
	if (x < minx) minx = x
	if (y < miny) miny = y
	if (x > maxx) maxx = x
	if (y > maxy) maxy = y
}

/Symbol[(]/ {
	sym=substr($0, 9, 1)
	ADV[sym]=int(substr($0, 11, length($0)))
	NLINE[sym] = 0
}

/SymbolLine[(]/ {
	sub("[ \t]*SymbolLine[(]", "", $0)
	X1[sym, NLINE[sym]] = int($1)
	Y1[sym, NLINE[sym]] = int($2)
	X2[sym, NLINE[sym]] = int($3)
	Y2[sym, NLINE[sym]] = int($4)
	TH[sym, NLINE[sym]] = int($5)
	bump(int($1), int($2))
	bump(int($3), int($4))
	NLINE[sym]++
}

END {
	for(n = 0; n < 128; n++) {
		c = sprintf("%c", n)
		if (c in ADV) {
			if ((n > 32) && !(c ~ "[{}()]"))
				annot = " /* " c " */"
			else
				annot = ""
			print "static embf_line_t embf_line_" n "[] = {" annot
			for(l = 0; l < NLINE[c]; l++)
				print "	{" X1[c, l] ", " Y1[c, l] ",\t\t" X2[c, l] ", " Y2[c, l] ",\t\t" TH[c, l] "}" ((l < NLINE[c]-1) ? "," : "")
			if (NLINE[c] == 0)
				print "	{0,0,0,0}"
			print "};"
		};
	}

	print "/***************************************************************/"
	print "static int embf_minx = " minx ";"
	print "static int embf_miny = " miny ";"
	print "static int embf_maxx = " maxx ";"
	print "static int embf_maxy = " maxy ";"

	print "static embf_font_t embf_font[] = {"
	for(n = 0; n < 128; n++) {
		c = sprintf("%c", n)
		comma = ((n < 127) ? "," : "")
		if (c in ADV) {
			print "	{" ADV[c] ", embf_line_" n ", " NLINE[c] "}" comma
		}
		else {
			print "	{0, NULL, 0}" comma
		}
	}
	print "};"
}
'
