#include "lib9.h"
#include "kernel.h"
#include "draw.h"

Subfont*
readsubfonti(Display*d, char *name, int fd, Image *ai, int dolock)
{
	char hdr[3*12+4+1];
	int n;
	uchar *p;
	Fontchar *fc;
	Subfont *f;
	Image *i;

	i = ai;
	if(i == nil){
		i = readimage(d, fd, dolock|2);
		if(i == nil)
			return nil;
	}
	if(libreadn(fd, hdr, 3*12) != 3*12){
		if(ai == nil)
			freeimage(i);
		kwerrstr("rdsubfonfile: header read error: %r");
		return nil;
	}
	n = atoi(hdr);
	p = malloc(6*(n+1));
	if(p == nil)
		return nil;
	if(libreadn(fd, p, 6*(n+1)) != 6*(n+1)){
		kwerrstr("rdsubfonfile: fontchar read error: %r");
    Err:
		free(p);
		return nil;
	}
	fc = malloc(sizeof(Fontchar)*(n+1));
	if(fc == nil)
		goto Err;
	_unpackinfo(fc, p, n);
	if(dolock)
		lockdisplay(d);
	f = allocsubfont(name, n, atoi(hdr+12), atoi(hdr+24), fc, i);
	if(dolock)
		unlockdisplay(d);
	if(f == nil){
		free(fc);
		goto Err;
	}
	free(p);
	return f;
}

Subfont*
readsubfont(Display*d, char *name, int fd, int dolock)
{
	return readsubfonti(d, name, fd, nil, dolock);
}
