/*---------------------------------------------------------------------------
File:         			FileRead.java
Package:                        JFLAP Version 3.0
Author:				Magda & Octavian Procopiuc V1.0 07/15/96
                                Eric Gramond V3.0 08/14/98
Description of Contents:	Contains class FileRead.
				
--------------------------------------------------------------------------*/

/* 
 * Susan H. Rodger, Magda Procopiuc, Octavian Procopiuc, Eric Gramond
 * Computer Science Department
 * Duke University
 * June 1998
 * Supported by National Science Foundation DUE-9596002 and DUE-9555084.
 *
 * Copyright (c) 1998
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that the above copyright notice and this paragraph are
 * duplicated in all such forms and that any documentation,
 * advertising materials, and other materials related to such
 * distribution and use acknowledge that the software was developed
 * by the author.  The name of the author may not be used to
 * endorse or promote products derived from this software without
 * specific prior written permission.
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

package flap;

import java.io.*;
import java.util.*;

/**
 * This class is used to read and parse the data from a given
 * file, and to construct a grammar using this data.
 *
 * @author	Eric Gramond
 * @version	3.0 15 July 1998
 */

public class GrammarFileRead {
  
  
  protected BufferedReader dis = null;
  
 /**
  * Tries to read a grammar from the given file.
  * @exception BadInputException if the input is badly formatted
  * @exception IOException if the file can't be read
  * @exception EOFException if the file ends unexpectedly 
  * @exception FileNotFoundException if the file can't be found
  */
  public Grammar read(String fileName) throws FileNotFoundException, IOException, EOFException , BadInputException {
    
    dis =  new BufferedReader(new FileReader(fileName));

    Grammar g= new Grammar();
    Rule r;
    Variable var;
    int i;

    String total = "";
    String line;

    line = dis.readLine();
    while(line != null) {
      if(line.length() > 0 && line.charAt(0) != '#') {
        
        if(line.length() >= 5 && !line.substring(1, 5).equals(" -> "))
        {
            throw new BadInputException(
               "\n\nUnrestricted grammars are not\nallowed in JFLAP.");
        }

          //strip the " -> " in the middle
        if(line.length() > 5)
          line = ((char) line.charAt(0)) + line.substring(5);
        else
          line = "" + ((char) line.charAt(0));
        total += line + "\n";
      }
      line = dis.readLine();
    }
    
    g.readString(total);
    return g;
  }
}
