import java.io.*;  // neccessary for file handling
import java.util.*; // neccessary for container classes
import org.jdom.*;
import org.jdom.input.SAXBuilder;

public class Theatre2
{
  public static Document getDocument(String filename) 
  {
    try {
      SAXBuilder builder = new SAXBuilder(true);
      return builder.build(new File(filename)); // return the parsed document
    }
    catch (JDOMException e) { 
      System.out.println(e);
      System.exit(1);
    }
    return null; // is never reached
  }
  
  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 Theatre2 <Play> <Figure>");
      System.exit(1);
    }

    // create the jdom -  document
    Document doc = getDocument(argv[0]);
    
    // get access to the root element
    Element root = doc.getRootElement();
 
    // create a list with all acts and loop through all items
    List acts = root.getChildren("ACT");
    for (int i=0; i<acts.size(); ++i) { 
      Element curAct = (Element) acts.get(i);     
      
      // create a list of all the scenes in this acts and loop through
      List scenes = curAct.getChildren("SCENE");
      for (int j=0; j<scenes.size(); ++j) {
        Element curScene = (Element) scenes.get(j);

        // create a list of all speeches
        List speeches = curScene.getChildren("SPEECH");
        for (int k=0; k<speeches.size(); ++k) {
        
          // Sorry! Only if the specified speaker is the first in this list, he will be found.
          // For a correct handling another list would be neccessary
          Element firstSpeaker = ((Element) speeches.get(k)).getChild("SPEAKER");          
          if ( firstSpeaker.getText().equals(argv[1]) ) {
            System.out.println(curAct.getChild("TITLE").getText() + "  -  " + curScene.getChild("TITLE").getText()); 
            break;
          }          
        } // for speeches            
      } // for scenes
    } // for acts
    
  }  // main     
 
}

