/* 
   J. Dean Brock, 1998

   Written for UNCA CSCI 343

   Various useful routines for the B+-tree

*/

#include <stdio.h>
#include <string.h>

#include "btree.h"

/* Search for slot less then or equal to key
 *    Used in search of LEAF nodes
 */
void findLEpos(blockRecT *p,	/* Block to search */
	       simpRecT *n,	/* Record searched for */
	       int *pos,	/* index of the slot,
				   set to p->head.numUsed if search
				   key exceeds all slot values */
	       int *eq)		/* set to 1 iff key is exact match */
{
  int i, lc ;
  for (i=0; i < p->head.numUsed &&
            (lc=strncmp(p->data[i].name, n->name, KEYSIZE)) < 0; ++i) ;
  *pos = i ;
  *eq = !lc ;
}

/* Find for slot less then or equal to key
 *    Used in search of Interior nodes.
 */
void findSubLoc(blockRecT *p,	/* Block to search */
		simpRecT *n,	/* Record searched for */
		int *pos,	/* index of the slot,
				   set to p->head.numUsed if search
				   key exceeds all slot values */
		int *addr)	/* set to address of subtree containing
				   the appropriate key */
{
  int i ;
  for (i=0; i < p->head.numUsed &&
            strncmp(p->data[i].name, n->name, KEYSIZE) < 0; ++i) ;
  *pos = i ;
  if (i == p->head.numUsed)
    *addr = p->head.value ;
  else
    *addr = p->data[i].value ;
}


void insertRec(blockRecT *r,	/* Block to contain record */
	       simpRecT *n,	/* Record to be inserted */
	       int i)		/* Place for insertion */
{
  int j ;
  for (j = r->head.numUsed; j > i; --j)
    r->data[j] = r->data[j-1] ;
  r->data[i] = *n ;
  r->head.numUsed++ ;
}

void splitBlock(blockRecT *r,	/* The existing block to be split */
		simpRecT *n,	/* New record to be inserted */
		int i,		/* Place for insertion */
		blockRecT *p,	/* New block 1 */
		blockRecT *q)	/* New block 2 */
{
  int h, j ;
  h = (RECINBLK+1)/2 ;
  /* ain't this a mess */
  if (i<h) {
    for (j = 0; j<i; ++j)
      p->data[j] = r->data[j] ;
    p->data[i] = *n ;
    for (j = i+1; j<h; ++j)
      p->data[j] = r->data[j-1] ;
    for (j = h; j<=RECINBLK; ++j)
      q->data[j-h] = r->data[j-1] ;
  } else {
    for (j = 0; j<h; ++j)
      p->data[j] = r->data[j] ;
    for (j = h; j<i; ++j)
      q->data[j-h] = r->data[j] ;
    q->data[i-h] = *n ;
    for (j = i+1; j<=RECINBLK; ++j)
      q->data[j-h] = r->data[j-1] ;
  }
  p->head.numUsed = h ;
  q->head.numUsed = (RECINBLK+1)-h ;
  p->head.type = r->head.type ;
  q->head.type = r->head.type ;
  p->head.value = 0 ;		/* Why not */
  q->head.value = r->head.value ;
}

int badBlock(blockRecT *r)
{
  int badRec = 0 ;

  if ( r->head.type != BLKINTERIOR && r->head.type != BLKLEAF ) {
    badRec = 1 ;
    (void) fprintf(stderr, "**** Bad type: %02x\n", r->head.type) ;
  }

  if ( r->head.numUsed < 0 || r->head.numUsed > RECINBLK ) {
    badRec = 1 ;
    (void) fprintf(stderr, "**** Bad numUsed: %d\n", r->head.numUsed) ;
  }

  return(badRec) ;
}
