/**********************************************************************
 
	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 "long_char.h"
#include "gbf.h"
#include "memory_debug.h"

void
gbf_read_char(V_STRING_PIC * p, FILE * file, int no)
{
GBF_HEADER header;
GBF_OFS ofs;
int w, h;
int i, j, len;
unsigned char * pixmap, *ptr;

	fseek(file, 0, SEEK_SET);
	fread(&header, sizeof(header), 1, file);
	if ( no < header.st_no || no >= header.end_no )
		goto undef;
	fseek(file, sizeof(GBF_HEADER) + sizeof(GBF_OFS)*(no-header.st_no), SEEK_SET);
	fread(&ofs, sizeof(ofs), 1, file);
	p->r.tl.x = ofs.st_x;
	p->r.tl.y = ofs.st_y;
	p->r.br.x = ofs.end_x;
	p->r.br.y = ofs.end_y;
	p->width = ofs.w;
	w = ofs.end_x - ofs.st_x;
	h = ofs.end_y - ofs.st_y;
	
	printf("(%d,%d)-(%d,%d) width = %d\t",p->r.tl.x, p->r.tl.y, p->r.br.x, p->r.br.y, p->width);
	printf("%d x %d\tpos = %d\n", w, h, ofs.ofs);

	if ( w*h == 0 )
		goto undef;
	
	len = gbf_get_len(&ofs);
	ptr = pixmap = d_alloc(len,235);
	fseek(file, ofs.ofs, SEEK_SET);
	fread(pixmap, len, 1, file);
	
	switch( ofs.type ) {
	case FT_GRAY :
		p->pic = pixmap;
		break;
	case FT_BITMAP :
		p->pic = d_alloc(w*h,235);
		for ( i = 0 ; i < w*h ; ptr++ ) {
			for ( j = 7 ; j >= 0 && i < w*h ; i++, j-- )
				p->pic[i] = (*ptr&(1<<j)) ? 255 : 0;
		}
		d_f_ree(pixmap);
		break;
	}
	
/**/
	for ( i = 0 ; i < h ; i++ ) {
		for ( j = 0 ; j < w ; j++ )
			printf("%c", p->pic[i*w+j] ? ' ' : 'o');
		printf("\n");
	}
/**/

	return;

undef:
	p->pic = 0;
	printf("undef.\n");
	return;
}


void
gbf_test(FILE * file)
{
V_STRING_PIC p;
char buf[256];
int no;
	do {
		printf("no > ");
		fgets(buf,256,stdin);
		no = atoi(buf);
		gbf_read_char(&p, file, no);
	} while ( no > 0 );
}