/*******************************
 * CS211 Spring/Fall 2002      *
 * CS211In.java                *
 *******************************/

import java.io.*;

// Tokenizer
public class FileIn {
    
    int NUMBER = -1, WORD = -2, OPERATOR = -3, EOF = -4;

    // Instance variable declarations:    
    String Name;
    InputStream in;
    boolean reading_file = false;
    StreamTokenizer tokens;
    boolean errorp = false; //To avoid multiple error messages
    
    // Open a file for input:
    public FileIn (String FileName) 
	{
		try 
		{ 
		    Name = FileName;
		    in = new FileInputStream(FileName);
		    reading_file = true;
		    Reader r = new BufferedReader(new InputStreamReader(in));
		    tokens = new StreamTokenizer(r);
		    tokens.wordChars(':',':');
		} 
		catch (Exception e) 
		{ 
			// Do not report any exceptions
		    System.out.println("ERROR: Unable to open file " + FileName + " for input\n");
		    errorp = true;
		}
    }
    
	
    // Get an number from file:
    public double getNum () 
	{
		try 
		{
	    	if (tokens.nextToken() == tokens.TT_NUMBER)
			return tokens.nval;
	    	else
			throw new Exception();
		} 
		catch (Exception e) 
		{
	    	if (! errorp)
				System.out.println("ERROR: Attempt to read a non-number value as an number");
	    	errorp = true;
	    	return 0;
		}
    }
    
    // Peek at the next token and return its "kind":
    public int peekAtKind () 
	{ // look at kind of next token w/o eating it
		try 
		{
	    	int kind = tokens.nextToken();
		    switch (kind) 
			{
			    case StreamTokenizer.TT_EOF:    tokens.pushBack(); return EOF;
			    case StreamTokenizer.TT_NUMBER: tokens.pushBack(); return NUMBER;
			    case StreamTokenizer.TT_WORD:   tokens.pushBack(); return WORD;
			    default: tokens.pushBack(); return OPERATOR; //character found
		    }
		} 
		catch (Exception e) 
		{
	    	if (! errorp) 
			System.out.println("ERROR: Unable to peek into file " + Name);
		    errorp = true;
		    return 0;
		}
    }

    // Close file:
    public void close () 
	{
		if (reading_file)
		    try 
			{ 
				in.close(); 
			}
		    catch (Exception e) 
			{
				if (! errorp)
				    System.out.println("Error: Unable to close file " + Name);
				errorp = true;
		    }
    }
}
