/**********************************************************************
 
	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	"r64.h"
#include	"r64_types.h"

int
r64_set(R64_FILE * f,int w,int h,int level,unsigned char * buf)
{
R64_CACHE_ENT * ce;
	if ( f->level_ofs[level] == 0 ) {
		r64_error = E_NOLEV;
		return -1;
	} 
	if ( w < 0 || w >= f->level_w[level] ||
			h < 0 || h >= f->level_h[level] ) {
		r64_error = E_OVER;
		return -1;
	}
	if ( _search_ce(f,w,h,level) < 0 )
		return -1;
	ce = f->cache[0].next;
	if ( f->header.type == 'B' ) {
	int pos,bit;
		pos = (h - ce->h_ofs)*
			(ce->w_len/8 + (ce->w_len%8 ? 1 : 0)) +
			w/8;
		bit = 7-w%8;
		if ( *buf )
			ce->buf[pos] |= 1<<bit;
		else	ce->buf[pos] &= ~(1<<bit);
	}
	else {
		memcpy(&ce->buf[BIT_OFS_IN_CH(f,ce,w,h)],buf,
			ENT_UNIT_VOL(f));
	}
	ce->flags |= EF_DIRTY;
	r64_error = E_OK;
	return 0;
}
