#include "disk_tools.h"
#include "d_map.h"
#include "d_ref.h"
#include <map>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <ctime>

using namespace std;
using namespace disk_tools;

int
main(int argc, char ** argv)
{
   bool init = false;
 
   for(int i = 0; i < argc; i++) {
      if(strcmp(argv[i], "-init") == 0) {
         init = true;
      }
   }

   try {
      d_env env;

      p_d_env = & env;

      if(init) {
         create_database("int");
         d_database * db = open_database("int");
         {
            d_map< unsigned int, unsigned int > btree("btree");
         }
         close_database(db);
         exit(0);
      }

      int n = 25000;
      d_database * db = open_database("int");

      {
         d_map< unsigned int, unsigned int > btree("btree");
         vector< unsigned int > vec;

         unsigned int temp, temp2;
         srand(time(NULL));
         int n = 0;
         unsigned int count = 0U;
         //for(unsigned int i = 25000; i > 0; i--) {
         for(unsigned int i = 0; i < 25000; i++) {
            cout << i << endl;
            temp2 = (unsigned int)(rand() * 65000000);
            temp = i;
            temp2 = i;
            if(!btree.get(temp2, temp)) {
               btree.insert(temp2, temp);
               vec.push_back(temp2);
            }
            else {
               n++;
               i--;
            }
            //btree.insert(i, i);
            //vec.push_back(i);
         }

         //btree.balance();

         cout << "-------------------------" << endl;

         btree.print_tree(cout);

         cout << "-------------------------" << endl;
         cout << "VEC_SIZE=" << vec.size() << endl;
         cin.get();cin.get();

         count = 0U;
         for(unsigned int i = 0; i < vec.size(); i++) {
            temp = 0;
            if(btree.get(vec[i], temp)) {
               cout <<  vec[i] << " -> " << temp << endl;
               count++;
            }
         }
         cout << "count == " << count << endl;
         cin.get();cin.get();

         cout << "-------------------------" << endl;
         count = 0U;
         for(d_map< unsigned int, unsigned int >::iterator ptr = btree.begin(); ptr != btree.end(); ptr++) {
            cout << ptr->first << " -> " << ptr->second << endl;
            count++;
         }
         cout << "-------------------------" << endl;
         cout << "count == " << count << endl;
      }

      close_database(db);
   }
   catch(const char * message) {
      cerr << message << endl;
   }
   catch(...) {
      cerr << "unknown exception..." << endl;
   }

   return 0;
}
