/*
 * Lexical Parser
 *
 * Author(s) : Catalin Dumitrescu (catalind@acm.org)
 *
 * File: token.cc
 * Created: Mon Aug 27 10:15:57 CDT 2001
 *
 */

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

#include "token.hh"

token::token ()
{
  back_count = 0;
  in = &cin;
}

token::token (const char* cstr)
{
  back_count = 0;
  in = new ifstream (cstr);
}

token::~token ()
{
  ifstream *inf = dynamic_cast<ifstream*> (in);
  if (inf)
    inf->close ();
}

void
token::setSpaces (string s)
{
  spaces = s;
}

string 
token::getNext () throw (schemeException)
{
  char c;
  string str_tmp;
  istream *in_t = in;

  if (back_count > 0)
    {
      back_count = 0;
      str_tmp = back;
      back = "";
      return str_tmp;
    }

  do {
    in_t->get (c);  
  } while (!in_t->eof () && isspace (c));

  if (in_t->eof ())
    { throw tokenException ("end of file"); }
  else if (c == '(')
    { str_tmp += c; }
  else if (c == ')')
    { str_tmp += c; }
  else
    {
      while (!in_t->eof () && !isspace (c) && (c != ')'))
	{       
	  str_tmp += c;
	  in_t->get (c);
	}
      if (c == ')')
	putBack (c);
    }    

  return str_tmp;
}

string 
token::getNext (string) throw (schemeException)
{
  throw tokenException ("not implemented");
}

void 
token::putBack (string s) throw (schemeException)
{
  back += s;
  back_count += s.size();
}

void 
token::putBack (char c) throw (schemeException)
{
  back += c;
  ++back_count;
}

