//
// (c) J. Dean Brock, 1999, 2002
//

#include <fstream>
using namespace std ;

#include "btree.hxx"

bTree::bTree() {
  btState = 0 ;
}

bTree::~bTree() {
  if (btState)
    btFile.close() ;
  btState = 0 ;
}

void bTree::create(char *name) {
  if (btState) {
    btFile.close() ;
    btState = 0 ;
  }
  btFile.open(name, ios::in | ios::out | ios::trunc ) ;
  if (btFile.fail()) {
    return ;
  }

  // Create btree with a single empty leaf node
  setUsedRecords(&btRoot, 0) ;
  setLeaf(&btRoot) ;
  btRoot.recs[METAPNTR].value = -1 ;
  btFile.write((char *)&btRoot, sizeof(blockRecT)) ;

  if (btFile.fail())
    btState = 0 ;
  else
    btState = 1 ;
}

void bTree::open(char *name) {
  if (btState) {
    btFile.close() ;
    btState = 0 ;
  }
  btFile.open(name, ios::in | ios::out | ios::nocreate) ;
  if (btFile.fail()) {
    return ;
  }

  // read in the root
  btFile.seekg(0, ios::beg) ;
  btFile.read((char *)&btRoot, sizeof(blockRecT)) ;

  // Ought to add some sanity checks in here ...
  if (btFile.fail())
    btState = 0 ;
  else
    btState = 1 ;
}

int bTree::io_ok() const {
  return btState ;
}
