/*
 * libnqs/db/seekdbb.c
 * 
 * DESCRIPTION:
 *
 *	Seek on an NQS database file without throwing away the current
 *	block cache, if the block in the cache is the one that we are
 *	interested in.  This function should only be called by the NQS
 *	daemon.
 *
 *	Original Author:
 *	-------
 *	Brent A. Kingsbury, Sterling Software Incorporated.
 *	August 12, 1985.
 */

#include <libnqs/license.h>
#include <libnqs/proto.h>
#include <libsal/license.h>
#include <libsal/proto.h>
#include <libsal/defines.h>
#include <errno.h>
#include <unistd.h>

/*** seekdbb
 *
 *
 *	void seekdbb():
 *
 *	Seek on an NQS database file without throwing away the current
 *	block cache, if the block in the cache is the one that we are
 *	interested in.  This function should only be called by the NQS
 *	daemon.
 */
void seekdbb (struct confd *file, long position)
{
	long blockoffset;
	register int i;
	register char *cp;

  	assert (file != NULL);
  
	if (position > file->size) position = file->size;
	else if (position < 0) position = 0;
	blockoffset = blockdb (position) * ATOMICBLKSIZ;
	if (position < file->size) {
		/*
		 *  There is a block in the file that we can read.
		 */
		if (file->rposition - ATOMICBLKSIZ != blockoffset) {
			/*
			 *  We do not have the proper block in the cache.
			 *  Correct this situation!
			 */
			lseek (file->fd, blockoffset, 0);
			errno = 0;	/* Set to zero, so that partial reads */
					/* do not cause a spurious error */
					/* message in nqs_abort(). */
			if (read (file->fd, file->cache->v.chars,
				  ATOMICBLKSIZ) != ATOMICBLKSIZ) {
				sal_dprintf (SAL_DEBUG_INFO, SAL_DEBUG_MSG_WARNING, "Unable to read %d bytes.\n", ATOMICBLKSIZ);
			}
			file->rposition = blockoffset + ATOMICBLKSIZ;
		}
	}
	else {
		/*
		 *  We are at the very end of the file.  Fill the cache
		 *  buffer with all zero.  (allodb uses this fact).
		 */
		lseek (file->fd, blockoffset, 0);
		file->rposition = blockoffset;
		cp = file->cache->v.chars;
		for (i=0; i < ATOMICBLKSIZ; i++) *cp++ = '\0';
	}
	file->vposition = position;
}
