#include	"all.h"
#include	<fio.h>

long
Fseek(int fd, long n, int cmd)
{
	Fbuffer *f;
	long dest, k;

	FIOSET(f, fd);
	switch(cmd)
	{
	case 0:
		dest = n;
		break;
	case 1:
		/* allow for the fact we are beyond where we think we are */
		dest = f->offset + n + f->next-f->end;
		break;
	case 2:
		if(f->flags & FIO_WRITING)
			_F_flush(f, fd);
		dest = lseek(fd, n, cmd);
		_F_reset(f);
		f->offset = dest;
		break;
	}
	if(dest < 0)
		return dest;
	k = f->end - ((f->flags&FIO_WRITING)? f->buf: f->lnext);
	if(dest >= f->offset || dest < f->offset-k) {
		if(f->flags & FIO_WRITING)
			_F_flush(f, fd);
		_F_reset(f);
		f->offset = dest;
		lseek(fd, f->offset, 0);
	} else {
		f->next = f->lnext + (dest-(f->offset-k));
		if(f->flags & FIO_WRITING) {
			f->offset -= f->end - f->next;
			f->end = f->next;
		}
		lseek(fd, f->offset, 0);
	}
	return dest;
}
