// makeRandomFile.cc   main program to generate n random integers in a file
// P. Conrad for CISC220, 06J

#include <iostream>
#include <cstdlib>
#include <ctime> // for initialization of srand from time(0)
#include <cassert>

using std::cout;
using std::cerr;
using std::endl;

int scale(int randInt, int min, int max)
{
  int range = max - min + 1;
  int returnValue = (randInt % range) + min;

  // double check our math
  assert(returnValue >= min && returnValue <= max);

  // then return the value
  return returnValue;

}

int main(int argc, char *argv[])
{
  // check command line arguments, and assign value to count

  if (argc!=2 && argc!=4)
    {
      cerr << "Usage: " << argv[0] << " count \n" 
	   << " or  : " << argv[0] << " count min max\n" 
	   << "Both forms return a file of length count on standard output\n"
	   << "The first form returns numbers between 0 and " <<RAND_MAX<<"\n"
	   << "The second form returns numbers between min and max" << endl;
      exit(1);
    }

  int count = atoi(argv[1]);
  
  if (count < 0)
    {
      cerr << "Error: count must be positive" << endl;
      exit(2);
    }

  // assign "scaled" flag.  if scaled, then assign values to min and max
  // and check validity of those values

  int min, max;
  bool scaled = (argc==4);

  if (scaled)
    {
      min = atoi(argv[2]);
      max = atoi(argv[3]);
      

      if (min > max)
	{
	  cerr << "Error: min must be <= max" << endl;
	  exit(3);
	}

      // The range of values returned is 0 to RAND_MAX, so the size of that
      // range is (RAND_MAX + 1).  

      int range = (max - min + 1);
      if (range > (RAND_MAX + 1))
	{
	  cerr << "Error: the range between min and max (inclusive) \n"
	       << " must be <= " << (RAND_MAX+1) << endl;
	  exit(4);
	}

    }
  
  srand(time(0)); // initialize srand from time of day

  for (int i=0; i<count; i++)
    {
      int x = rand();
      if (scaled)
	x = scale(x,min,max);
      cout << x << endl;
    }

  return 0;

}

