/*
 * libnqs/db/freedb.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 <errno.h>
#include <unistd.h>

/*** freedb
 *
 *
 *	void freedb():
 *
 *	Free the descriptor entry at the specified file offset
 *	in the specified NQS database/configuration file.  The
 *	current position of the database file is placed at the
 *	descriptor record FOLLOWING the deleted descriptor.
 */
void freedb (struct confd *file, long position)
{
	register struct gendescr *descr1;
	register struct gendescr *descr2;
	register long offset;
	register long doffset;

  	assert (file != NULL);
  
	offset = position % ATOMICBLKSIZ;	/* Offset within block */
	descr1 = (struct gendescr *) file->cache->v.chars;
	seekdbb (file, position);	/* Set virtual position to reference */
					/* descriptor targeted for deletion. */
	if (offset) {
		/*
		 *  Merge deleted descriptor with the previous descriptor
		 *  in the block.
		 */
		doffset = descr1->size;
		if (doffset < 0) {
			/*
			 *  The very first descriptor in the block is free.
			 *  (Only the size of the very FIRST descriptor in
			 *   a block can be negative).
			 */
			doffset = -doffset;
		}
		while (doffset < offset) {
			/*
			 *  We still have not found the descriptor immediately
			 *  previous to the descriptor that we are trying to
			 *  delete.
			 */
			descr1 = (struct gendescr *)
				 (file->cache->v.chars + doffset);
			doffset += descr1->size;
		}
		/*
		 *  Descr1 now points at the descriptor immediately previous
		 *  to the descriptor being deleted.
		 */
		descr2 = (struct gendescr *) (file->cache->v.chars+offset);
		file->vposition += descr2->size;/* Position at next descr */
		/*
		 *  Merge the deleted descriptor with the previous descriptor.
		 */
		if (descr1->size < 0) {
			descr1->size -= descr2->size;
		}
		else descr1->size += descr2->size;
	}
	else {
		file->vposition += descr1->size;/* Position at next descr */
		descr1->size = -descr1->size;	/* Mark descriptor at head of */
						/* block as free */
	}
	/*
	 *  File->vposition has the position of the next descriptor after
	 *  the deleted descriptor in the database file.
	 *  Now, rewrite the updated block.
	 */
	lseek (file->fd, file->rposition - ATOMICBLKSIZ, 0);
						/* Seek back to block */
	errno = 0;				/* Set to zero so partial */
						/* writes do not give spurious*/
						/* error message in nqs_abort.*/
	if (write (file->fd, file->cache->v.chars,
		   ATOMICBLKSIZ) != ATOMICBLKSIZ) {
		sal_dprintf (SAL_DEBUG_INFO, SAL_DEBUG_MSG_ERRORDATA, "Unable to write out %d bytes.\n", ATOMICBLKSIZ);
	}
}
