/*
 * libnqs/db/seekdb.c
 * 
 * DESCRIPTION:
 *
 *
 *
 *	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 <unistd.h>

/*** seekdb
 *
 *
 *	void seekdb():
 *
 *	Seek on the specified NQS database file.
 */
void seekdb (struct confd *file, long newposition)
{
  	assert (file != NULL);
  
	if (newposition > file->size) newposition = file->size;
	else if (newposition < 0) newposition = 0;
	file->rposition = blockdb (newposition) * ATOMICBLKSIZ;
	file->vposition = newposition;
	if (lseek (file->fd, file->rposition, 0) == -1) {
		sal_dprintf (SAL_DEBUG_INFO, SAL_DEBUG_MSG_WARNING, "Lseek error in seekdb().\n");
	}
	if (file->rposition < file->size) {
		/*
		 *  The file has at least one block in it that we
		 *  can read.
		 *
		 *  Read the current block into the cache.  We ALWAYS
		 *  throw away the current cache block, since many of
		 *  the NQS utilities scan NQS database files AFTER an
		 *  update has been made BY THE NQS DAEMON, and with-
		 *  out this forced reloading of the cache block, such
		 *  programs would not necessarily get the updated
		 *  version of the database file....
		 */
		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 += ATOMICBLKSIZ;
	}
}
