/**********************************************************************
 
	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	"pdb.h"
#include	"utils.h"
#include	<fcntl.h>
#include	<string.h>

unsigned int
d_lseek(PDB * p,unsigned int where)
{
	if ( p->buf_ptr < 0 ) {
		if ( p->seek_ptr != where )
			u_lseek(p->fid,where,SEEK_SET);
		p->seek_ptr = where;
		p->buf_ptr = -1;
		return where;
	}
	if ( p->seek_ptr <= where && where < p->seek_ptr + p->buf_len ) {
		p->buf_ptr = where - p->seek_ptr;
		return where;
	}
	p->seek_ptr = where;
	p->buf_ptr = -1;
	if ( p->seek_ptr + p->buf_len != where )
		lseek(p->fid,where,SEEK_SET);
	return where;
}

int
d_read(PDB * p,void * data,int len)
{
int s;
int rs;
int er;
	rs = 0;
	for ( ; len ; ) {
		if ( p->buf_ptr == -1 ) {
			er = u_read(p->fid,p->data,DF_BUF);
			if ( er == 0 )
				return rs;
			if ( er < 0 )
				return er;
			p->buf_len = er;
			p->buf_ptr = 0;
		}
		if ( len + p->buf_ptr > p->buf_len )
			s = p->buf_len - p->buf_ptr;
		else	s = len;
		memcpy(data,&p->data[p->buf_ptr],s);
		data = (void*)(((char*)data) + s);
		len -= s;
		p->buf_ptr += s;
		rs += s;
		if ( p->buf_ptr == p->buf_len ) {
			p->buf_ptr = -1;
			p->seek_ptr += p->buf_len;
		}
	}
	return rs;
}
