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

long
Fwrite(int fd, void *aaddr, long nbytes)
{
	Fbuffer *f;
	long n, nnbytes = nbytes;
	char *addr;

	addr = aaddr;

	FIOSET(f, fd);
	f->flags |= FIO_WRITING;
	n = &f->buf[FIOBSIZE] - f->next;
	if(nbytes < n)
		n = nbytes;
	memmove(f->next, addr, n);
	f->end = (f->next += n);
	f->offset += n;
	nbytes -= n;
	addr += n;
	if(nbytes) {
		if(_F_flush(f, fd))
			return -1;
		while(nbytes >= FIOBSIZE) {
			if(write(fd, addr, FIOBSIZE) != FIOBSIZE)
				return -1;
			addr += FIOBSIZE;
			nbytes -= FIOBSIZE;
			f->offset += FIOBSIZE;
		}
		memmove(f->buf, addr, n = nbytes);
		f->end = f->next = f->buf+n;
		f->offset += n;
		f->flags |= FIO_WRITING;
	}
	return nnbytes;
}
