/*
	getbuff.c
	94/11/27 94/11/28 95/02/18
	ret : 0 : normal
	      1 : eof
	      2 : memory full
	      3 : buffur full
*/

#include <malloc.h>
#include <io.h>

#define byte unsigned char
#define uint unsigned int

#define BUFFSIZE ( 1024 * 2 )
#define BUFPAGE 20

static byte *mp[BUFPAGE];
static int mpg = -1;
static uint mp_buf = BUFFSIZE;

byte getbuff( int fp, uint offset, byte *c ){

	int cpg,cby;
	int flag = NULL;

	cpg = offset / BUFFSIZE;
	cby = offset % BUFFSIZE;
	while( cpg > mpg && mpg < BUFPAGE && mp_buf == BUFFSIZE ){
	/* バッファメモリの確保 */
		if( ++mpg > BUFPAGE ){
			flag = 2 ;
			break;
		}
		if(( mp[mpg] = (byte *)malloc(BUFFSIZE) ) == NULL ){
			flag = 3 ;
			break;
		}
	/* 読み込み */
		mp_buf = read(fp,mp[mpg],BUFFSIZE);
	}
	if( mp_buf <= cby && cpg == mpg ) flag = 1 ;
	if( flag != NULL ){
		*c = NULL ;
	} else {
		*c = *(mp[cpg]+cby);
	}
	return flag;
}
