#include <iostream.h>
#include <sys/time.h>
#include <stdlib.h>
#include <vector>
#include <list>


int processCmdLine(char *argv[],int argc);
void seed();

// Flags set by command line
bool dolist = false;  // l
bool dovector = false; // v
bool printList = false; // p
bool printInserts = false; // i


template<template C> C<int>::iterator findInsertionPos(C<int>& values, int newval)
{
  C<int>::iterator pos;

  for (pos=values.begin(); pos!=values.end(); pos++)
    if (*pos > newval) break;

  return pos;
}


template<C> void doIt(int size)
{
  typedef C<int> cont;
  typedef cont::iterator iter;

  cont values;

  for (int i=0; i<size; i++) {
    iter pos;
    int newval;

    newval = rand() % size;
    pos = findInsertionPos<C>(values,newval);

    if (printInserts) {
      cout << endl << "Inserting " << newval;
      if (pos != values.end()) 
	cout << " before " << *pos;
    }
    values.insert(pos, newval);
  }

  if (printList) {
    cout << endl << endl << "Final Order: ";
    for (iter i=values.begin(); i!=values.end(); i++)
      cout << *i << " ";
    cout << endl;
  }
}


main(int argc, char *argv[])
{
  int size = processCmdLine(argv,argc);
  seed();

  if(dolist) 
    doIt<list>(size);
  else if (dovector) 
    doIt<vector>(size);

}  
	       
void seed()
{
  timeval tp;

  /* put these two lines at the beginning of your program, like
     the first two lines of your main.  You can put it in a constructor
     but there is no need for this to be called more than once 
     (the constructor is called every time you create an instance of
     the class). */
  gettimeofday(&tp, NULL );
  srand(tp.tv_sec);
}

int processCmdLine(char *argv[],int argc)
{
  if (argc < 3) exit();
  else if (argv[1][0] = '-')
    for (int i=1; argv[1][i]; i++) 
      switch (argv[1][i]) {
      case 'l' : dolist = true; break;
      case 'v' : dovector = true; break;
      case 'p' : printList = true; break;
      case 'i' : printInserts = true; break;
      }
  else exit();

  return(atoi(argv[2]));
}


