import java.io.*;  // necessary for file ops
import org.w3c.dom.*; // contains W3C-Interfaces
import org.xml.sax.SAXException;
import org.apache.xerces.parsers.DOMParser;  


public class Theatre1
{
  public static Document getDocument(String filename) 
  {
    try {  // get a validating parser 
      DOMParser p = new DOMParser();      
      p.setFeature("http://xml.org/sax/features/validation", true);
      p.parse(filename);  // parse the document and return it
      return p.getDocument();
    }
    catch (IOException io) {
      System.out.println(io);
      System.exit(1);
    }
    catch (SAXException s) {
      System.out.println("Error occured during parsing.");
      System.exit(1);
    }
    return null; // dummy
  }
  
  public static void main (String argv[])
  {
    // command line ok ?
    if (argv.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 Theatre1 <Play> <Figure>");
      System.exit(1);
    }
 
    // get the document object of the specified xml-document
    Document doc = getDocument(argv[0]);

    // get the root element
    Element root = doc.getDocumentElement();
    
    // create a list of all speakers of the play
    // this becomes possible because the dom with this method provides
    // a means to get a list of all children (not only the direct ones)
    // of any node
    // this is not possible in jdom
    NodeList speakers = root.getElementsByTagName("SPEAKER");
    Node lastScene = null;
    
    // loop through all speakers and print out the distinct list of scenes in
    // which the speaker occurs
    for (int i=0; i<speakers.getLength(); ++i) {
      if (argv[1].equals(speakers.item(i).getFirstChild().getNodeValue())) {
        Node scene = speakers.item(i).getParentNode().getParentNode();

        if (scene == lastScene) continue; // the speaker again in the same scene

        lastScene = scene;

        Node act = scene.getParentNode();

        String sceneTitle = scene.getFirstChild().getFirstChild().getNodeValue();
        String actTitle = act.getFirstChild().getFirstChild().getNodeValue();
        
        System.out.println(actTitle + "  -  " + sceneTitle);
      }          
    }  // for all speakers
  }
}

  

