import java.io.*;
import org.xml.sax.*;
import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.helpers.DefaultHandler;


class Theatre3 extends DefaultHandler
{
  static String searchedSpeaker;
  boolean getSpeakerName = false;
  boolean getSceneName = false;
  boolean getActName = false;
  boolean getTitle = false;
  String lastScene = "";
  String lastAct = "";
  boolean sceneFound = false;

  // every time a new element is found, this callback is activated
  public void startElement(java.lang.String uri,
                           java.lang.String localName,
                           java.lang.String qName,
                           Attributes attributes) throws SAXException
  {
    if (localName.equals("SPEAKER")) getSpeakerName = true;
    if (localName.equals("SCENE")) getSceneName = true;
    if (localName.equals("TITLE")) getTitle = true;
    if (localName.equals("ACT")) getActName = true;
  }
   
  // every time a closing tag was found this method is called
  public void endElement(java.lang.String namespaceURI, java.lang.String localName, java.lang.String qName)
  {
    getSpeakerName = false;
    getSceneName = false;
    getActName = false;
    getTitle = false;
  }

  // for handling of element content
  public void characters(char[] ch, int start, int length) 
  {
    // remember the scene names
    if (getSceneName && getTitle) {
      lastScene = new String(ch, start, length);
      sceneFound = false;
    }
    
    // remember the act names
    if (getActName && getTitle) lastAct = new String(ch, start, length);

    // is the speaker found, the same as the one searched
    if (getSpeakerName) {
      String speakerName = new String (ch, start, length);
      if (!sceneFound && speakerName.equals(searchedSpeaker)) {
        // print out the current scene / act
        System.out.println(lastAct + "  -  " + lastScene);
        sceneFound = true;
      }
    }
  }         
  
  public static void main(String args[]) {
    // command line ok ? 
    if (args.length != 2) {
      System.out.println("This program returns a list of all the scenes in which a specified Figure participates.");
      System.out.println("Usage: java Theatre3 <Play> <Figure>");
      System.exit(1);
    }
    searchedSpeaker = args[1];
    
    // get the Xerces-SaxParser, set the content handler and parse the document
    XMLReader parser = new SAXParser();
    parser.setContentHandler(new Theatre3());
    try {
      parser.parse(args[0]);
    }    
    catch (Exception e) {
      System.out.println("An error occurred.");
      System.exit(1);
    }
  }
  
  
}


