import java.io.*;


/**
 * This class reads in Lsystem files
 * (called by: Lsystem.java)
 *
 * @author Scott Teresi, April 1999, www.teresi.us
 */



public class LsystemsReader {

  LineNumberReader reader;
  String file;
  char commentChar = ';';
  boolean done = false;


  public LsystemsReader (String f) throws IOException {

    file = f;

    reader = new LineNumberReader(new FileReader(file));
  }



  public int read() {

    int r = -1;

    try {
      r = reader.read();
    } catch (IOException ioEx) {
      System.out.println("Error in file " + file + ", line #" +
			 reader.getLineNumber());
    }

    return r;
  }



  public String readLine() {

    String line = null;
    boolean keepTrying = true;

    while (keepTrying) {

      try {
	line = reader.readLine();
      } catch (IOException ex) {
	System.out.println("Error in file " + file + ", line #" +
			   reader.getLineNumber());
	keepTrying = false;
      }

      if (line == null) {
	keepTrying = false;
      } else {
	if (line.length() != 0) {
          line = cleanUp(line);
	  keepTrying = false;
	}
      }

    }

    return line;
  }



  public int getLineNumber() {

    return reader.getLineNumber();
  }



  // reached the end of the L-system yet?

  public boolean done() {
    return done;
  }



  // read until a space is reached

  public String parseWord (String line) {

    for (int i = 0; i < line.length(); i ++) {
      if (line.charAt(i) == ' ') {
	line = line.substring(0, i);
	break;
      }
    }

    return line;
  }



  // Get rid of leading and trailing spaces and comments

  String cleanUp(String l) {

    StringBuffer line;

    // remove leading and trailing spaces

    line = new StringBuffer(l.trim());

    // remove comment string

    StringBuffer temp = new StringBuffer();
    for (int i = 0; i < line.length(); i ++) {
      if (line.charAt(i) == commentChar) {
	break;
      } else {
	temp.append(line.charAt(i));
      }
    }
    line = temp;

    // check for } brace

    done = false;
    for (int i = 0; i < line.length(); i ++) {
      if (line.charAt(i) == '}') {
	done = true;
      }
    }

    return line.toString();
  }

}
