/*
 * Command Line Options
 *
 * Author(s) : Joshua Shapiro
 *
 * File: getopt.cc
 * Created: Mon Aug 27 10:15:57 CDT 2001
 *
 */

#include <iostream>
#include <string>
#include <cstring>
#include <strstream>
using namespace std;

#include "getopt.hh"

char 
getOptions::getNextType() throw (optError)
{
  pos++;
  while (pos < argNumber) //make sure we are still in the argument list
    {
      if ((arguments[pos][0] == '-') && (arguments [pos][2] == 0)) //are we at a correct position?
	{
	  char c = arguments[pos][1];
	  /* step through control string to check if c is a member*/
	  for (int i = 0; i < control.length(); i++)
	    {
	      if (control[i] == c) //check that it is a member of the control
		return c;
	    }
	  string Error = "Unknown control character -";
	  throw optError (Error + c);
	}
      else pos++;//advance position to get to next argument if we were not at the correct position
    }
    // if we are out of the argument list, return false;
  return 0;
}



void 
getOptions::getNext (int& i) throw (optError)
{
  pos++;
  if (arguments[pos][0] == '-' && arguments[pos][2] == 0)
    {      
      pos--;
      throw optError("Expected an integer, found next control character");
    }
  else 
    {
      strstream test;
      test << atoi(arguments[pos]);
      if (! strcmp (test.str(), arguments[pos]) )
	i = atoi (arguments[pos]);
      else 
	throw optError("Expected an integer, found something else");
    }
  
}

void 
getOptions::getNext (double& d) throw (optError)
{
  pos++;
  if (arguments[pos][0] == '-' && arguments[pos][2] == 0)
    {
      pos--;	
      throw optError("Expected a float, found next control character");
    }    
  else 
    {
      strstream test;
      test << atof(arguments[pos]);
      if (! strcmp (test.str(), arguments[pos]) )
	d = atof(arguments[pos]);
      else 
	throw optError("Expected a float, found something else");
    }
}
void 
getOptions::getNext (string& s) throw (optError)
{
  pos++;
  if (arguments[pos][0] == '-' && arguments[pos][2] == 0)
    {
      pos--;
      throw optError("Expected a string, found next control character");
    }    
  else 
    s = arguments[pos];
}



getOptions& 
operator >> (getOptions& opt, int& i) throw (optError)
{ 
  opt.getNext(i); 
  return opt;
}


getOptions& 
operator >> (getOptions& opt, double& d) throw (optError)
{
  opt.getNext(d); 
  return opt;
}

getOptions& 
operator >> (getOptions& opt, string& s) throw (optError)
{
  opt.getNext(s); 
  return opt;
}
