
/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	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.

**********************************************************************/


#include	<stdio.h>
#include	<stdlib.h>
#include	"memory_debug.h"
#include	"gbf.h"
#include	"utils.h"
#include	"long_char.h"

char * font_root;
int gbf_get_font();

LC_FONT_ENGINE_TYPE gbf_font_engine_type = {
	"gbf",
	gbf_get_font,
	gbf_get_string_pic,
	0,
	{0.0},
	0
};

LC_FONT_ENGINE gbf_font_engine = {
	0,
	"gbf",
	&gbf_font_engine_type,
	0,
};

void
gbf_init()
{
	insert_font_engine(&gbf_font_engine);
}

GBF_DATA *
get_gbf_dat(char * fontname,int fontsize)
{
GBF_HEADER head;
GBF_DATA * dat;
FILE * f;

	dat = d_alloc(sizeof(GBF_DATA));
	dat->path = d_alloc(strlen(font_root)+strlen(fontname)+20);
	sprintf(dat->path, "%s/%s/%i.gbf", font_root, fontname,fontsize);
	fprintf(stderr, "gbf load : %s\t", dat->path);
	f = fopen(dat->path, "r");
	if ( f == 0 || fread(&head, sizeof(head), 1, f) != 1 ) {
		perror(" ");
		d_f_ree(dat->path);
		d_f_ree(dat);
		return 0;
	}
	fclose(f);
	
	dat->size = fontsize;

	dat->st_no = head.st_no;
	dat->end_no = head.end_no;
	dat->nos = head.nos;
	dat->ofs = 0;

	return dat;
}

int
gbf_get_font(
	LC_FONT * font,
	LC_FONT_ENGINE * fe)
{
FILE * f;
char * path;
char cmd[20];
GBF_FONT * d;
int i;
LC_FONT_SIZE_LIST sl;
	path = d_alloc(strlen(font_root)+
			l_strlen(font->fontname)*sizeof(L_CHAR)+40);
	sprintf(path,"%s/%s/sizelist.txt",font_root,
		n_string(std_cm,font->fontname));
	f = fopen(path, "r");
	if ( f == 0 ) {
		perror(" ");
		d_f_ree(path);
		return -1;
	}
	d_f_ree(path);
	d = d_alloc(sizeof(*d));
	d->len = 0;
	for ( ; ; ) {
		fscanf(f,"%s",cmd);
		if ( strcmp(cmd,"end") )
			break;
		i = d->len;
		d = d_re_alloc(d,sizeof(*d)+sizeof(GBF_DATA*)*(i+1));
		d->dat[i] = get_gbf_dat(
				n_string(std_cm,font->fontname),atoi(cmd));
		if ( d->dat[i] == 0 )
			continue;
		d->len = i + 1;
	}
	fclose(f);

	for ( i = 0 ; i < d->len ; i ++ ) {
		sl.size = d->dat[i]->size;
		sl.from = font->lcz[0] | d->dat[i]->st_no;
		sl.to = font->lcz[0] | d->dat[i]->end_no;
		_insert_lc_font_size_list(font,&sl);
	}

	insert_font_work(font,fe,d);

	return 0;
}

