/* 
   J. Dean Brock, 1998

   Written for UNCA CSCI 343

   Various I/O routines for the B+-tree

*/

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

#include "btree.h"

int addBlock(FILE *f,			/* B+-tree file */
	     blockRecT *b)		/* block to be added */
				/* Returns
				 *    index of new block, on success
 				 *    -1, on failure
				 */
{
  int r ;
  long int p ;
  if (fseek(f, 0L, SEEK_END)) {
    (void) fputs("Failed to seek to end of file\n", stderr) ;
    return(-1) ;
  }
  if ((p = ftell(f)) == (long) -1) {
    /* how can this possibly fail */
    (void) fputs("ftell failed\n", stderr) ;
    return(-1) ;
  }
  r = p/sizeof(blockRecT) ;
  if (fwrite((void *)b, sizeof(blockRecT), 1, f) != 1) {
    (void) fputs("Unable to extend file\n", stderr) ;
    return(-1) ;
  }
  return(r) ;
}

int updateBlock(FILE *f,		/* B+-tree file */
		int p,			/* position for block */
	        blockRecT *b)		/* new contents for block */
				/* Returns
				 *    0, on success
 				 *    -1, on failure
				 */
{
  if (fseek(f, (long) (p*sizeof(blockRecT)), SEEK_SET)) {
    (void) fprintf(stderr, "Unable to seek to block %d\n", p) ;
    return(-1) ;
  }
  if (fwrite((void *)b, sizeof(blockRecT), 1, f) != 1) {
    (void) fprintf(stderr, "Unable to write block %d\n", p) ;
    return(-1) ;
  }
  return(0) ;
}

int readBlock(FILE *f,			/* B+-tree file */
	      int p,			/* position for block */
	      blockRecT *b)		/* buffer for block */
				/* Returns
				 *    0, on success
 				 *    -1, on failure
				 */
{
  if (fseek(f, (long) (p*sizeof(blockRecT)), SEEK_SET)) {
    (void) fprintf(stderr, "Unable to seek to block %d\n", p) ;
    return(-1) ;
  }
  if (fread((void *)b, sizeof(blockRecT), 1, f) != 1) {
    (void) fprintf(stderr, "Unable to read block %d\n", p) ;
    return(-1) ;
  }
  return(0) ;
}
