// ------------------------------- //
// -------- Start of File -------- //
// ------------------------------- //
// ----------------------------------------------------------- // 
// C++ Source Code File Name: ix_debug.cpp 
// Compiler Used: MSVC40, DJGPP 2.7.2.1, GCC 2.7.2.1, HP CPP 10.24
// Produced By: Doug Gaer   
// File Creation Date: 02/12/1997 
// Date Last Modified: 10/22/1998
// Copyright (c) 1997 Douglas M. Gaer
// ----------------------------------------------------------- // 
// ------------- Program Description and Details ------------- // 
// ----------------------------------------------------------- // 
/*
The VBD C++ classes are copyright (c) 1997, by Douglas M. Gaer.
All those who put this code or its derivatives in a commercial
product MUST mention this copyright in their documentation for
users of the products in which this code or its derivative
classes are used. Otherwise, you have the freedom to redistribute
verbatim copies of this source code, adapt it to your specific
needs, or improve the code and release your improvements to the
public provided that the modified files carry prominent notices
stating that you changed the files and the date of any change.

THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
THE ENTIRE RISK OF THE QUALITY AND PERFORMANCE OF THIS SOFTWARE
IS WITH YOU. SHOULD ANY ELEMENT OF THIS SOFTWARE PROVE DEFECTIVE,
YOU WILL ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR
CORRECTION.

This program is used to debug B-tree index files created with
the VBD file manager.
*/
// ----------------------------------------------------------- // 
#include <iostream.h>
#include "btree.hpp"
#include "btreeprt.hpp"
#include "btwalk.hpp"
#include "rbtree.hpp"
#include "twalk.hpp"
#include "vbdstats.hpp"

// Program name and version number
const char *VersionNumber = "1027.101";
const char *ProgramName = "ix_debug";

// Global Red Black memory base tree pointer used to sort
// the disk based btree nodes
static RBTree<InMemCopy> *rbtree; 

// Default cache size for the disk based btree
int cache_size = 1024;

void PrintKeys(RBTree<InMemCopy> *rbt)
{
  int num = 1;
  int count = 0;
  BNodeBase *nxt; // BSTree base node pointer

  // Using iterator object to walk throught the rbtree
  TreeWalkerb tw(rbt->GetRoot(), INORDER);

  // Walk through the rbtree using an iterator object
  while((nxt = tw.Next()) != 0) {
    RBNode<InMemCopy> *ptr = (RBNode<InMemCopy> *)nxt;
    cout << "(" << num << ") " << ptr->Data.key << endl;
    num++; count++;
    if(count > 10) {
      count = 0;
      cout << "Press enter to continue..." << endl;
      cin.get();
    }
  }
}

void DumpKeys(RBTree<InMemCopy> *rbt)
{
  int num = 1;
  BNodeBase *nxt; // BSTree base node pointer

  // Using iterator object to walk throught the rbtree
  TreeWalkerb tw(rbt->GetRoot(), INORDER);

  // Walk through the rbtree using an iterator object
  while((nxt = tw.Next()) != 0) {
    RBNode<InMemCopy> *ptr = (RBNode<InMemCopy> *)nxt;
    cout << "(" << num << ") " << ptr->Data.key << " ";
    num++; 
  }
  cout << endl;
}

void Version()
{
  cout << endl;
  cout << ProgramName << " version number: " << VersionNumber << endl;
  cout << endl;
}

void pause()
{
  cout << endl;
  cout << "Press enter to continue..." << endl;
  cin.get();
}

char *InputData()
{
  char buf[255];
  cout << "Enter Key Name: ";
  cin.getline(buf, sizeof(buf));
  unsigned len = 0;
  for(unsigned i = 0; buf[i] != '\0'; i++) len++;
  char *s = new char[len];
  s[len] = '\0';
  memmove(s, buf, len);
  cout << endl;
  return s;
}

void StoreKey(CachePointer n)
// Visit function used to load the btree nodes into memory
{
  int i = 0;

  while (i < n->cnt) {
    InMemCopy buf(n->entry[i].key,
		  n->entry[i].object_address,
		  n->entry[i].class_id);

      rbtree->Add(buf);
    i++;
  }
}

void SkipToEol(istream &s)
// Used to clear istream
{
  char c;
  s.clear();
  while(s.get(c) && c != '\n') { ; }
}

int Quit()
{
  cout << "Exiting..." << endl;
  return 0;
}

void FindKey(Btree &t)
// Searchs the btree for a specified entry key
{
  char *buf = InputData();
  int rv;

  if(!buf) {
    cout << "Invalid input." << endl;
    cout << endl;
    return;
  }
  
  EntryKey e = buf;
  rv = t.Search(e);
  
  if(!rv) {
    cout << "Could not find: " << buf << endl;
    cout << endl;
    return;
  }
  
  cout << "Found: " << buf << endl;
  cout << "Entry Key Name:             " << e.key << endl;
  cout << "Object's data file address: " << e.object_address << endl;
  cout << "Object's class ID:          " << e.class_id << endl;
  cout << endl;
}

void Menu(void)
{
  cout << "(D)   Dump the B-tree index" << endl;
  cout << "(F)   Find a key in the B-tree index file" << endl;
  cout << "(L)   List the contents of the B-tree index file" << endl;
  cout << "(H)   Help (prints this menu)" << endl;
  cout << "(P)   Print the B-tree node by node" << endl;
  cout << "(Q)   Quit" << endl;
  cout << "(S)   Display VBD file stats" << endl;
  cout << "(T)   Display B-tree stats" << endl;
  cout << "(V)   Display this program's version number" << endl;
  cout << endl;
}

int main(int argc, char **argv)
{
  // Display the program version information and exit the program
  if(argc >= 2) {
    if(strcmp(argv[1], "version") == 0) {
      Version();
      return 0;
    }
  }

  if(argc < 2) {
    cerr << endl;
    cerr << "B-tree index file debug utility version "
	 << VersionNumber << endl;
    cerr << "Usage: " << ProgramName << " infile.btx" << endl;
    cerr << endl;
    return 1;
  }

  VBDFilePtr f(new VBDFile);
  const char *FName = argv[1];
  if(!VBDFile::Exists(FName)) 
    Error->SignalException(EHandler::NoFileExists);
  else
    f->Open(FName, VBDFile::READONLY);

  FileHeader fh;
  VBHeader vb;
  
  // Analyze the VBD file header to determine if the file has
  // a pre-allocated static area
  __LWORD__ static_area;
  f->Read(&fh, sizeof(FileHeader), 0);

  // Check the HeapStart value 
  f->Read(&vb, sizeof(VBHeader), fh.HeapStart);
  if (vb.CkWord != CheckWord) {
    cout << "Bad HeapStart value." << endl;
    cout << "This VBD file is damaged." << endl;
    cout << "Exiting..." << endl;
    cout << endl;
    return 0;
  }
  else    
    // If no errors, calculate the the size of the static area
    static_area = fh.HeapStart - sizeof(FileHeader);

  if(static_area == 0) {
    cout << "No static area was alloacted in this file." << endl;
    cout << "Cannot connect B-tree header." << endl;
    cout << "Exiting..." << endl;
    cout << endl;
    return 0;
  }

  FAU StaticEOF = f->FileSize(f->VBDFileName());
  FAU addr = f->VBSearch(0); // Search the entire file
  
  if(addr == 0) {
    cout << endl;
    cout << "No variable blocks found in file: "
	 << f->VBDFileName() << endl;
    cout << "Exiting..." << endl;
    cout << endl;
    return 0;
  }

  Btree t(cache_size);
  t.Connect(f, 0);
  rbtree = new RBTree<InMemCopy>; // Initialize memory based rbtree pointer
  
  // Main menu
  char key;
  Menu();
  int rv = 1;
  
  while(rv) {
    if (!cin) { // Input is in fail state
       SkipToEol(cin); // Go to end of line
       if (!cin) {  // Can't fix
          cout << "Input stream is broken" << endl;
          return 0;
       }
    }
    cout << '>';
    cin >> key;
    if (!cin) continue; // Fix at top of loop
    switch(key) {
      case 'f' : case 'F' : SkipToEol(cin); FindKey(t); break;	
      case 'd' : case 'D' :
	SkipToEol(cin);
	BtreeWalk(t.GetRoot(), StoreKey, &t);
	DumpKeys(rbtree);
	break;
      case 'l' : case 'L' :
	SkipToEol(cin);
	BtreeWalk(t.GetRoot(), StoreKey, &t);
	PrintKeys(rbtree);
	break;
      case 'h' : case 'H' : Menu(); break;
      case '?' : Menu(); break;
      case 'p' : case 'P' :
	SkipToEol(cin);
	BtreeWalk(t.GetRoot(), PrintNode, &t);
	break;
      case 'q' : case 'Q' : rv = Quit(); break;
      case 't' : case 'T' : SkipToEol(cin); BTreeStats(t); break;	
      case 's' : case 'S' : SkipToEol(cin); VBDStats(f); break;
      case 'v' : case 'V' : SkipToEol(cin); Version(); break;
	
      default:
        cout << "Unrecognized command" << endl;
    }
  }
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
//
