/*static char *SCCSID = "@(#)bldalb.c	6.2 92/01/31";*/
#define BSWAP0 BSWAP0

#include <os2def.h>

#include "heap.h"
#include "const.h"
#include "misc.h"
#include "chain.h"
#include "buf.h"
#include "dir.h"
#include "storage.h"
#include "ea.h"
#include "fnode.h"
#include "volume.h"
#include "tables.h"
#include "pbmacros.h"
#include "superb.h"
#include "lw.h"
#include "frame.h"
#include "fsdata.h"

#ifdef DEBUG
#include "pr_debug.h"
#endif
#include "pr_ea.h"
#include "pr_cache.h"
#include "pr_misc.h"
#include "pr_heap.h"
#include "pr_read.h"

/*
 ***	BuildAlBlk - Build an AlBlk Record
 *
 *	The allocation B+TREE routines work from a root ALBLK
 *	record.  We don't store such a record in the fnode for
 *	aux info to save space, BuildAlBlk builds an AlBlk from
 *	an AUXINFO or a EAAT record when necessary.
 *
 *	WARNING - BuildAlBLK is called pointing to an EAAT or an AUXINFO
 *		record.  The relevant fields in each must line up.
 *
 *
 *	ENTRY	pstp = address of STP in AUXINFO or EAAT structure
 *		fSingleExt = 1 if disk space is a single extent
 *			     ignored if length = 0
 *
 *	RETURNS	 address of AlBlk record, NULL if error.
 *
 *	HISTORY
 *	    19-Sep-89 by JR (John Rogers, JohnRo@Microsoft)
 *		- Avoid warnings from Microsoft C 5.2 (on slash-slash comments).
 *	    16-May-1989 by John Rogers [JohnRo@Microsoft]
 *		- Changed names of rounding macros in <pbmacros.h>.
 *		- Minor #include changes per Leif Pederson.
 */

PALBLK
BuildAlBlk (PSPTR pstp, BOOL fSingleExt, PFRAME pfrm)
{
	PALLEAF pall;
	PALBLK palblk;

	if ((palblk = GHS(sizeof(ALBLK) + sizeof(ALLEAF),pfrm)) == NULL) {
	    return (NULL);
	}

	/* wipe flags and zero file sector number of data block */
	palblk->bFlag = 0;
	pall = (PALLEAF) ((PBYTE) palblk + sizeof (ALBLK));
	pall->lsnLog = 0;

	if( (USHORT)pstp->cbRun == 0 ) {

		/* show the alblk as empty */
		palblk->cFree = 1;
		palblk->cUsed = 0;
		palblk->oFree = sizeof (ALBLK);
		return (palblk);
	}
/* bab10: */

	palblk->cFree = 0;
	palblk->cUsed = 1;

	/*
	 * There is some stuff in the disk tree.  See if it's a leaf entry
	 * or a root.
	 */
	if (fSingleExt) {
		palblk->oFree = sizeof (ALBLK) + sizeof (ALLEAF); /* one leaf */

		pall->lsnPhys = pstp->lsn;	/* set sector */
		pall->csecRun =
		    SAFE_ROUND_UP_DIV ((USHORT)pstp->cbRun, SECSIZE);
		return (palblk);
	}

/* bab20: */

	/* It's a root node for an allocation BTREE */
	palblk->oFree = sizeof (ALBLK) + sizeof (ALNODE); /* one node */
	palblk->bFlag = ABF_NODE;
	(((PALNODE) pall)->lsnLog)--;
	((PALNODE) pall)->lsnPhys = pstp->lsn;
	return (palblk);
}
