// argcArgvInFunc.cc
// P. Conrad for CISC181, Spring 2005

#include <iostream>
#include <fstream>
using namespace std;

// if you want to access argc and argv from anywhere in the program,
// you have to declare them as parameters to main.  But then, you can
// pass them through as arguments to any other function you like,
// and use them there.

// function prototypes

void aNiceFunction(int argc, char*argv[]);
int secondArgAsAnInt(int argc, char*argv[]);
void readFromTheFile(int argc, char*argv[]);

// Note: to test this program, pass in a.out filename number

int main(int argc, char *argv[]) 

{
  // pass in argc and argv as parameters to the function
  // where you want to access them

  aNiceFunction(argc,argv);

  int x;
  x = secondArgAsAnInt(argc,argv);

  cout << "The integer you put in was " << x << endl;

  readFromTheFile(argc,argv);


  return 0;


}

void aNiceFunction(int argc, char *argv[])
{
  // now I'm inside another function, but I have access to 
  // the command line arguments

  if (argc != 3)
    {
      cerr << "You silly person. I need two things on the command line" 
	   << endl
	   << "Please put " << argv[0] 
	   << " followed by a filename followed by an integer" << endl;
      exit(1);
    }
  
  cout << "Your filename is " << argv[1] << endl;


}


int secondArgAsAnInt(int argc, char*argv[])
{
  if (argc >= 3)
    return atoi(argv[2]);
  else
    return 0;
}


void readFromTheFile(int argc, char*argv[])
{
  if (argc < 2)
    {
      cerr << "I don't have a filename to open" << endl;
      exit(1);  
    }

  ifstream myInputFile(argv[1],ios::in);      

  if (!myInputFile)
    {
      cerr << "Could not open " << argv[1] << endl;
      exit(2);
    }

  char someText[LINE_MAX];

  myInputFile.getline(someText,LINE_MAX);

  cout << "I read this from the input file: " << endl
       << someText << endl;

}



