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

#include "ttf.h"

/* Fonts come from the DAM, so every read is bounds checked. */
static uint32_t
rd(const struct ttf *t, size_t off, int n)
{
	uint32_t v = 0;
	int i;

	if (off + (size_t)n > t->len)
		return 0;
	for (i = 0; i < n; i++)
		v = v << 8 | t->data[off + i];
	return v;
}
#define RD16(t, o) ((uint16_t)rd((t), (o), 2))
#define RD32(t, o) rd((t), (o), 4)

static uint32_t
find_table(const struct ttf *t, const char *tag)
{
	int i, n = RD16(t, 4);

	for (i = 0; i < n; i++)
		if (12 + (size_t)i * 16 + 16 <= t->len &&
		    memcmp(t->data + 12 + i * 16, tag, 4) == 0)
			return RD32(t, 12 + i * 16 + 8);
	return 0;
}

int
ttf_load(struct ttf *t, const char *path)
{
	FILE *f;
	long sz;
	uint32_t head, hhea, maxp, cmap, sub;
	int i, n, score, best = 0;

	memset(t, 0, sizeof(*t));
	if ((f = fopen(path, "rb")) == NULL)
		return -1;
	if (fseek(f, 0, SEEK_END) != 0 || (sz = ftell(f)) < 12 ||
	    sz > 16 * 1024 * 1024) {
		fclose(f);
		return -1;
	}
	rewind(f);
	t->len = (size_t)sz;
	if ((t->data = malloc(t->len)) == NULL ||
	    fread(t->data, 1, t->len, f) != t->len) {
		fclose(f);
		ttf_free(t);
		return -1;
	}
	fclose(f);

	/* glyf-flavoured TrueType only: CFF/OTTO cannot go in a FontFile2 */
	if (RD32(t, 0) != 0x00010000 && RD32(t, 0) != 0x74727565)
		goto bad;
	head = find_table(t, "head");
	hhea = find_table(t, "hhea");
	maxp = find_table(t, "maxp");
	cmap = find_table(t, "cmap");
	t->hmtx = find_table(t, "hmtx");
	if (!head || !hhea || !maxp || !cmap || !t->hmtx ||
	    !find_table(t, "glyf"))
		goto bad;
	t->units = RD16(t, head + 18);
	for (i = 0; i < 4; i++)
		t->bbox[i] = (int16_t)RD16(t, head + 36 + i * 2);
	t->ascent = (int16_t)RD16(t, hhea + 4);
	t->descent = (int16_t)RD16(t, hhea + 6);
	t->nhmetrics = RD16(t, hhea + 34);
	t->nglyphs = RD16(t, maxp + 4);
	if (t->units == 0 || t->nhmetrics == 0)
		goto bad;

	n = RD16(t, cmap + 2);
	for (i = 0; i < n; i++) {
		int plat = RD16(t, cmap + 4 + i * 8);
		int enc = RD16(t, cmap + 6 + i * 8);
		int fmt;

		sub = cmap + RD32(t, cmap + 8 + i * 8);
		fmt = RD16(t, sub);
		score = 0;
		if (fmt == 12 && ((plat == 3 && enc == 10) || plat == 0))
			score = 3;
		else if (fmt == 4 && ((plat == 3 && enc == 1) || plat == 0))
			score = 2;
		if (score > best) {
			best = score;
			t->cmap = sub;
			t->cmap_fmt = fmt;
		}
	}
	if (best == 0)
		goto bad;
	return 0;
bad:
	ttf_free(t);
	return -1;
}

void
ttf_free(struct ttf *t)
{
	free(t->data);
	memset(t, 0, sizeof(*t));
}

uint16_t
ttf_gid(const struct ttf *t, uint32_t cp)
{
	uint32_t s = t->cmap, i, n;
	uint16_t gid = 0;

	if (t->cmap_fmt == 12) {
		n = RD32(t, s + 12);
		for (i = 0; i < n; i++) {
			uint32_t g = s + 16 + i * 12;
			uint32_t start = RD32(t, g), end = RD32(t, g + 4);

			if (g + 12 > t->len)
				break;
			if (cp >= start && cp <= end) {
				gid = (uint16_t)(RD32(t, g + 8) + (cp - start));
				break;
			}
		}
	} else if (cp <= 0xFFFF) {
		uint32_t sc = RD16(t, s + 6) / 2;
		uint32_t ends = s + 14, starts = s + 16 + sc * 2;
		uint32_t deltas = starts + sc * 2, ros = deltas + sc * 2;

		for (i = 0; i < sc; i++) {
			uint16_t end = RD16(t, ends + i * 2), start, ro, g;

			if (end < cp)
				continue;
			start = RD16(t, starts + i * 2);
			if (start > cp)
				break;
			ro = RD16(t, ros + i * 2);
			if (ro == 0) {
				gid = (uint16_t)(cp + RD16(t, deltas + i * 2));
			} else {
				g = RD16(t, ros + i * 2 + ro + (cp - start) * 2);
				if (g != 0)
					gid = (uint16_t)(g + RD16(t, deltas + i * 2));
			}
			break;
		}
	}
	return gid < t->nglyphs ? gid : 0;
}

int
ttf_advance(const struct ttf *t, uint16_t gid)
{
	if (gid >= t->nhmetrics)
		gid = (uint16_t)(t->nhmetrics - 1);
	return RD16(t, t->hmtx + (uint32_t)gid * 4);
}
