#include	<stdio.h>
#include	"defs.h"
#include	"bifont.h"
#include	"jsub.h"

char header[4*2];
char width[4*256];
int id, nt, lh, bc, ec, nw, ds;
struct jfmfntinfo *jfmfi;

readjfm(fntfp)
register FILE *fntfp;
{
    register struct jfmtype_entry *te;
    register struct jfmchar_entry *ce;
    register int i;
    char *alloc_check();

    if ((id=getuint(fntfp, 2)) != JFM_ID && id != TJFM_ID)
	return (FALSE);
    nt = getuint(fntfp, 2);
    fseek(fntfp, 2, 1);		/* lf */
    lh = getuint(fntfp, 2);
    bc = getuint(fntfp, 2);	/* bc should be 0 */
    ec = getuint(fntfp, 2);
    nw = getuint(fntfp, 2);
    fseek(fntfp, 7*4, 0);
    getbytes(fntfp, header, 2*4);
    ds = makeuint(header+4, 4);
    fseek(fntfp, (7+lh+nt+(ec-bc)+1)*4, 0);
    getbytes(fntfp, width, 4*nw);
    fseek(fntfp, (7+lh)*4, 0);	/* ready to read char_type and char_info */

    jfmfi = NEW(struct jfmfntinfo, "jfmfont info");
    jfmfi->nctype = nt;
    jfmfi->ctype = NEWTAB(struct jfmtype_entry, nt, "jfmtype table");
    for (i = 0, te = jfmfi->ctype; i < nt; i++, te++) {
	te->jfm_code = getuint(fntfp, 2);
	te->jfm_type = getuint(fntfp, 2);
    }
    jfmfi->lasttypecode = (te-1)->jfm_code;
    jfmfi->ch = NEWTAB(struct jfmchar_entry, ec+1, "jfmchar table");
    for (i = bc, ce = (jfmfi->ch)+bc; i <= ec; i++, ce++) {
	ce->tfmw = makeuint(width+4*getuint(fntfp,1),4);
	fseek(fntfp, 3, 1);
    }
    return (TRUE);
}

getctype(c, jfmfi)
int c;
struct jfmfntinfo *jfmfi;
{
    register int m;
    register int left, right;
    register struct jfmtype_entry *te;
    int code;

    if (c > jfmfi->lasttypecode)
	return (0);
    for (left = 0, right = jfmfi->nctype, te = jfmfi->ctype; left <= right;) {
	m = (left+right)/2;
	if (c < (code = (te+m)->jfm_code))
	    right = m-1;
	else if (c > code)
	    left = m+1;
	else if (c == code)
	    return ((te+m)->jfm_type);
    }
    return (0);
}
