/**********************************************************************
 
	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	<sys/types.h>
#include	<stdio.h>
#include	<errno.h>
#include	<sys/types.h>
#include	"r64.h"
#include	"r64_types.h"
#include	"machine/include.h"

int
_r64_flush(R64_FILE * f,R64_CACHE_ENT * ce)
{
unsigned int ofs1,ofs2;
int vol;
int er;
unsigned int size;
	ofs1 = CH_OFS2_FILE(f,ce);
	size = lseek64(f->fd,0,SEEK_END);
	if ( ofs1 > size )
		_fill_background(f,ofs1-size);
	ofs2 = lseek64(f->fd,ofs1,SEEK_SET);
/*
if ( ofs1 > 0x7fffffff )
printf("W over %x %x %x\n",ofs1,size,ofs2);
*/
	if ( ofs2 == 0xffffffff ) {
		r64_error = E_SYS;
		return -1;
	}
retry:
	er = write(f->fd,(char*)ce->buf,vol = ENT_VOL(f,ce));
	if ( er < vol ) {
		if ( errno == EAGAIN )
			goto retry;
		r64_error = E_SYS;
		return -1;
	}
	ce->flags |= ~EF_DIRTY;
	return 0;
}
