//   (c) J. Dean Brock, 1998, 1999, 2002
//   Written for UNCA CSCI 343
//   Main user-level routine for creating huge B+-tree
//   Call as
//        bfill [-n size] btree-file


#include <unistd.h>
#include <strings.h>
#include <errno.h>

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <strstream>
using namespace std ;

#include "btree.hxx"

#define DEFAULTSIZE 1000000
#define MAXSIZE   100000000
#define DOTPRINT       2000

main(int argc, char *argv[])
 {
  int rc, numrec ;
  int errflg = 0 ;
  char *filArg = NULL ;
  char *numArg = NULL ;
  int   numRes ;
  char usage[]
        = "Usage:  bfill [-n size] btree-file" ;
  char *atoiHack = NULL ;
  bTree bigBT ;
  int value ;
  char name[KEYSIZE] ;

  optarg = NULL ;
  while ((rc = getopt(argc, argv, "n:")) != -1)
    switch (rc) {
    case 'n':
      numArg = optarg ;
      break ;
    default:
      errflg = 1 ;
    }
  if (optind == argc) {
    cerr << usage << endl ;
    exit(1) ;
  }
  else if (optind == argc-1)
    filArg = argv[optind] ;
  else
    errflg = 1 ;

  errno = 0 ;
  if (numArg == NULL)
    numRes = DEFAULTSIZE ;
  else {
    istrstream inbuff(numArg) ;
    if (! (inbuff >> numRes && inbuff.eof())) {
      cerr << "Bad option for -n: " << numArg << endl ;
      errflg = 1 ;
      errno = 0 ;
    }
  }

  if (errflg) {
    cerr << usage << endl ;
    exit(1) ;
  }

  if (numRes < 0 || numRes > MAXSIZE) {
    cerr << "Unable to create file with " << numRes << " records" << endl ;
    exit(1) ;
  }

  cout << "Writing " << numRes << " records to " << filArg << endl ;

  bigBT.create(filArg) ;

  if (! bigBT.io_ok()) {
    cerr << "Unable to open " << filArg << endl ;
    exit(1) ;
  }

  ostrstream outbuff ;
  outbuff.fill('0') ;
  numrec = 0 ;
  srandom(1997) ;
  while (numrec < numRes) {
    value = random() % 1000000000 ;
    outbuff << "RC" ;
    outbuff << setw(9) << value ;
    bigBT.update(outbuff.str(), value) ;
    outbuff.seekp(0, ios::beg) ;
    if (bigBT.io_ok()) {
      ++numrec ;
      if (numrec % DOTPRINT == 0) {
	cout << '.' ;
	if (numrec % (50*DOTPRINT) == 0)
	  cout << endl ;
	cout << flush ;
      }
    }
  }
 }
