/*
   Tamot --- Task Modelling Editor
   Copyright (C) 2000 Commonwealth Scientific and Industrial Research Organisation
   (CSIRO), Australia. All rights reserved. 

   The Software, owned by CSIRO Australia, has been developed by the CSIRO 
   Intelligent Interactive Technology group. 
   For more information, please see http://www.cmis.csiro.au/iit/.

   The Software is a beta-test version for internal research and evaluation purposes 
   by the Licensee. The Software is still at a development stage. 
   It has not undergone complete testing and may have inherent errors,
   bugs or deficiencies that can affect the operation of the Software. 

   We encourage your feedback and suggestions. Any bugs / suggestions found please email to
   Shijian.Lu@cmis.csiro.au and Thomas.Lo@cmis.csiro.au. 

   After you have signed the Beta-Test Software License Agreement with the CSIRO,
   CSIRO grants you a non-exclusive, non-transferable license to use it only for your 
   personal, non-commercial and lawful end use. Implied licenses are negated. 

   Warranty Disclaimer : 

   CSIRO supplies the Software on an "as is" basis and makes no warranties that use of
   the Software by the Licensee will not infringe any third party’s 
   Intellectual Property Rights nor that the Software will be of merchantable quality,
   or suitable for a particular purpose. CSIRO excludes all terms, conditions and
   warranties implied by custom, the general law or statute in relation to the
   Software.
*/

package domainModel;

import java.io.*;
import java.util.*;
import org.apache.xerces.dom.*;

import org.w3c.dom.*;
import com.ibm.xml.parsers.*;

import java.awt.*;
import taskModellingTool.Manager;

/** 
* XManager.java
* for manage XML parsing, printing, and  content 
* movement between the DOM tree and object collection.
*/
public class XManager
{
	private String doctypeName = "Tamot";
	private String TamotVersion = "3.0";
	private String doctypeID = "tmDm.dtd"; 	//"NewDTDFile3.dtd";
	private String taskCom="Task_Model_Components";
							//element tag for task model component
	private String taskDecomposition="Task_Model_Decomposition";
							// element tag for task decomposition
	private static String XMLHeader=
					"<?xml version=\"1.0\" encoding =\"UTF-8\" ?>";
	
	public static final String _XML_YES	 = "Yes";	//shijian 2001-1-15
	public static final String _XML_NO	 = "No";
	
	private Document doc = null;
	private DocumentType doctype = null;
	
	//20-2-2002
	//only initialise domain manager if domain menu is turned on
	private static DmManager dM = DmManager.getInstance();;
	/*static {
		
		if (Manager.getSysOption().getDomainF())
			dM= DmManager.getInstance();
	}
	*/
	public XManager(){
		this(new DocumentImpl());
		createNewDoc(); 
	}
	public XManager(Document aDoc){
		doc = aDoc;	
	}
	
	/** 
	* parse(), parses a XML document, if successful,
	* it'll procude a DOM document
	* @PARAM: uri, the file name of a XML doc to be parsed
	* @return the DOM document 
	*/
	public static Document parse(String uri)
  	{
  		Document docu = null;
   	try
    	{
	      DOMParser parser = new DOMParser();
	      parser.parse(uri);
	      docu = parser.getDocument();
    		return docu;
    	}
	   catch (Exception e)
	   {
	      System.err.println("Sorry, an error occurred: " + e);
	   }
    	return docu;

  	} //parse()

  		/** 
	* parse(), parses a XML document, if successful,
	* it'll procude a DOM document
	* @PARAM: f, the File object refers to a XML doc
	* @return void
	*/
	public void parse(File f)
  	{
  		String temp = f.getAbsolutePath(); //getName(); 	
  		
  		//System.out.println("path and name " + temp);

  		if (temp != null) {
  			
  		 	setDoc(parse(temp));
	    	//set document type name and ID
	    	DocumentType tp= getDoc().getDoctype();
          if (tp!= null && 
          		tp.getSystemId() != null &&
          			tp.getName() != null){
          				
          		setDtName(tp.getName());
          		setDtId(tp.getSystemId());
          }
	    	
	 /*   	
  			System.out.println("the largest ID " + DmClass.getLargestID());
  		 	
  	   	printDOMTree(getDoc());
  	   	
  	   	setDoc(null);	// set document to null
	*/
  		}


  	} //parse()
  	
  	
  	/** 
	* open(), parses a XML file, if successful,
	* it transfer all domain elements into object store.
	* then set the DOM doc to null
	* @PARAM: f, the File object refers to a XML doc
	* @return void
	*/
	public void open(File f)
  	{
  	  	createNewDoc();	// clear document content
  		parse( f);
  		removeTM(); // remove task model elements if any
  		 	
  		// trasfer all element to object store
  	 	allEleToStore();
  	 	
  	 	setDMColors();
	    
  	 	//13-7-2001
  	 	setStyleParameters();
  		 	
  	   	return;

  	} //open()
  	
  	/** 
	* updateDoc(), create a new DOC and then populate 
	* with content from object store
	* @return void
	*/
	public void updateDoc()
  	{
      	//System.out.println("now update doc ");
		createNewDoc(); // remove task model elements if any
  		// trasfer all domain objects into DOM elements
  	 	allObjToDOM();
	    	    	
  	} //updateDoc()
  	
  	
  	/** 
	* allEleToStore(), transfers all domain elements into object store.
	* @return void
	*/
	public void allEleToStore()
  	{
  		// trasfer all element to object store
  	 	allConEleToStore();
	  	allEnEleToStore();
	  	allActEleToStore();
  	 	allEngNounEleToStore();
	  	allReguVerbEleToStore();
	  	allIrreVerbEleToStore();
  	} //allEleToStore()
  	
  	/** 
	* allObjToDOM(), transfers all domain objects into DOM element.
	* @return void
	*/
	public void allObjToDOM()
  	{
  		// trasfer all element to object store
  	 	allConObjToDoc();
	  	allEnObjToDoc();
	  	allActObjToDoc();
	  	allEnglishNounObjToDoc();
	  	allEnglishVerbObjToDoc();
  	} //allObjToDOM()
  	
  	/** 
	* removeTM(), romoves task model elements from
	* the DOM tree
	*/
	public void removeTM()
  	{
  		Document docu = getDoc();
  		if (docu == null) return;
  		try{
	  		//remove task component 
			NodeList children = docu.getElementsByTagName(taskCom);
	      if (children != null && children.getLength() >= 1)
	      {
	      	Node node1 = children.item(0);
	      	Node nodeP = node1.getParentNode();
	         Node temp =nodeP.removeChild(node1);
	       }
	       
	       //remove task decomposition 
			NodeList	children2 = docu.getElementsByTagName(taskDecomposition);
	      if (children2 != null && children2.getLength() >= 1)
	      {
	      	Node node = children2.item(0);
	         (node.getParentNode()).removeChild(node);
	       }
  		}
	   catch (Exception e)
	   {
	      System.err.println("Sorry, an error occurred: " + e);
	   }
  	} //removeTM()


  /**
  * Prints the specified node, recursively. 
  */
  public static void printDOMTree(Node node) 
  {
    int type = node.getNodeType();
    switch (type)
    {
      // print the document element
      case Node.DOCUMENT_NODE: 
        {
          System.out.println(XMLHeader);
          
          //print doctype infor
          DocumentType tp= ((Document)node).getDoctype();
          if (tp!= null && 
          		tp.getSystemId() != null &&
          			tp.getName() != null){
          				
          		System.out.println("<!DOCTYPE " + 
          			tp.getName()+ " SYSTEM \""+
          			tp.getSystemId() + "\">");
          }

          printDOMTree(((Document)node).getDocumentElement());
          break;
        }

        // print element with attributes
      case Node.ELEMENT_NODE: 
        {
        	 
          System.out.print("<");
          System.out.print(node.getNodeName());
          NamedNodeMap attrs = node.getAttributes();
          for (int i = 0; i < attrs.getLength(); i++)
          {
            Node attr = attrs.item(i);
            System.out.print(" " + attr.getNodeName() + 
                             "=\"" + attr.getNodeValue() + 
                             "\"");
          }
          System.out.print(">");

          NodeList children = node.getChildNodes();
          if (children != null)
          {
            int len = children.getLength();
            for (int i = 0; i < len; i++)
              printDOMTree(children.item(i));
          }

          break;
        }

        // handle entity reference nodes
      case Node.ENTITY_REFERENCE_NODE: 
        {
          System.out.print("&");
          System.out.print(node.getNodeName());
          System.out.print(";");
          break;
        }

        // print cdata sections
      case Node.CDATA_SECTION_NODE: 
        {
          System.out.print("<![CDATA[");
          System.out.print(node.getNodeValue());
          System.out.print("]]>");
          break;
        }

        // print text
      case Node.TEXT_NODE: 
        {
          System.out.print(node.getNodeValue());
          break;
        }

        // print processing instruction
      case Node.PROCESSING_INSTRUCTION_NODE: 
        {
          System.out.print("<?");
          System.out.print(node.getNodeName());
          String data = node.getNodeValue();
          {
            System.out.print(" ");
            System.out.print(data);
          }
          System.out.print("?>");
          break;
        }
    }

    if (type == Node.ELEMENT_NODE)
    {
      System.out.print("</");
      System.out.print(node.getNodeName());
      System.out.print('>');
      System.out.println();

    }
  } // printDOMTree(Node)


  /**
  * Prints the specified node, recursively
  * onto the PrintStream out. 
  */
  public static void printDOMTree(Node node, Element root, PrintStream out) 
  {
  	
  	
    int type = node.getNodeType();
    
    //Element root= null;
    switch (type)
    {
      // print the document element
      case Node.DOCUMENT_NODE: 
        {
        	/*
          out.println("<?xml version=\"1.0\" encording =\"UTF-8\" ?>");
          
          //print doctype infor
          DocumentType tp= ((Document)node).getDoctype();
          if (tp!= null && 
          		tp.getSystemId() != null &&
          			tp.getName() != null){
          				
          		out.println("<!DOCTYPE " + 
          			tp.getName()+ " SYSTEM \""+
          			tp.getSystemId() + "\">");
          }
			*/
			 root = ((Document)node).getDocumentElement();
			 //System.out.println("tag name: " + root.getTagName());


          printDOMTree(((Document)node).getDocumentElement(),root,out);
          break;
        }

        // print element with attributes
      case Node.ELEMENT_NODE: 
        {
        	 //System.out.println("node name: " + node.getNodeName());
        	 //System.out.println("tag name: " + root.getTagName());
			 if (!(node.getNodeName().equals(root.getTagName()))){ 
			 			// don't print root element
 
	        	 out.print("<");
	          out.print(node.getNodeName());
	          NamedNodeMap attrs = node.getAttributes();
	          for (int i = 0; i < attrs.getLength(); i++)
	          {
	            Node attr = attrs.item(i);
	            out.print(" " + attr.getNodeName() + 
	                             "=\"" + attr.getNodeValue() + 
	                             "\"");
	          }
	          out.print(">");
	               
			 }

          NodeList children = node.getChildNodes();
          if (children != null)
          {
            int len = children.getLength();
            for (int i = 0; i < len; i++)
              printDOMTree(children.item(i),root,out);
          }

          break;
        }

        // handle entity reference nodes
      case Node.ENTITY_REFERENCE_NODE: 
        {
          out.print("&");
          out.print(node.getNodeName());
          out.print(";");
          break;
        }

        // print cdata sections
      case Node.CDATA_SECTION_NODE: 
        {
          out.print("<![CDATA[");
          out.print(node.getNodeValue());
          out.print("]]>");
          break;
        }

        // print text
      case Node.TEXT_NODE: 
        {
          out.print(node.getNodeValue());
          break;
        }

        // print processing instruction
      case Node.PROCESSING_INSTRUCTION_NODE: 
        {
          out.print("<?");
          out.print(node.getNodeName());
          String data = node.getNodeValue();
          {
            out.print(" ");
            out.print(data);
          }
          out.print("?>");
          break;
        }
    }

    if (type == Node.ELEMENT_NODE)
    {
    	if (!(node.getNodeName().equals(root.getTagName()))) {
        	 		//do not print the root element
        	 	
	      out.print("</");
	      out.print(node.getNodeName());
	      out.print('>');
	      out.println();
    	}
    }
  } // printDOMTree(Node node, PrintStream out)

    /**
  * Prints XML doc header upto Root element
  * onto the PrintStream out. 
  */
  public static void printXMLRootHead( Node node, PrintStream out) 
  {
      out.println(XMLHeader);
       
       //print doctype infor
       DocumentType tp= ((Document)node).getDoctype();
       if (tp!= null && 
       		tp.getSystemId() != null &&
       			tp.getName() != null){
       				
       		out.println("<!DOCTYPE " + 
       			tp.getName()+ " SYSTEM \""+
       			tp.getSystemId() + "\">");
       }
       
       //print root element only
       Element root = ((Document)node).getDocumentElement();
       Node node1= (Node)root;
       out.print("<");
       out.print(node1.getNodeName());
       NamedNodeMap attrs = node1.getAttributes();
       for (int i = 0; i < attrs.getLength(); i++)
       {
         Node attr = attrs.item(i);
         out.print(" " + attr.getNodeName() + 
                          "=\"" + attr.getNodeValue() + 
                          "\"");
       }
       out.println(">");

       

    }//printXMLRoot( PrintStream out)
    

    /**
  * Prints XML doc footer upto Root element
  * onto the PrintStream out. 
  */
  public static void printXMLFooter( Node node, PrintStream out) 
  {
       
       //print root element only
       Element root = ((Document)node).getDocumentElement();
       Node node1= (Node)root;

	    out.print("</");
       out.print(node1.getNodeName());
	    out.print('>');
	    out.println();
       

    }//printXMLRoot( PrintStream out)
    
  /** 
  	* insertBEntity(), 
  	* insert the ele element before the first 
  	* DmEntity element.If there is no DmEntity in the document, the 
  	*  element will not be added
  	*/
  	public static boolean insertBEntity(Document docu,Element ele){
		if (docu == null || ele == null) return false;
		//if (hasElement( docu, ele)) return false;
		try {
	      //get all DmEntity elements.
	      NodeList cons = docu.getElementsByTagName(XDmTag.getEntityT());
	    	if (cons != null && cons.getLength() >0)
	    	{	
	         cons.item(0).getParentNode().insertBefore(ele,cons.item(0));
	         return true;
	    	}
		}
		catch (Exception e)
		{
			System.err.println(e);
		}
		return false;
  		
  	}//insertBEntity()
  	
  	/** 
  	* insertBAction(), 
  	* insert the ele element before the first    
  	* DmAction element. If there is no DmAction in the document, the 
  	* element will not be added
  	*/
  	public static boolean insertBAction(Document docu,Element ele){
		if (docu == null || ele == null) return false;
	//	if (hasElement( docu, ele)) return false;
		try {
	      //get all DmAction elements.
	      NodeList cons = docu.getElementsByTagName(XDmTag.getActionT());
	    	if (cons != null&& cons.getLength() >0)
	    	{	
	         cons.item(0).getParentNode().insertBefore(ele,cons.item(0));
	         return true;
	    	}
		}
		catch (Exception e)
		{
			System.err.println(e);
		}
		return false;
  		
  	}//insertBAction()
  	
  	/** 
  	* append(),  insert 
  	* the ele element at the end of Domain_model's chidren 
  	* list. If the Domain_Model element is not defined in the DOM doc,the 
  	*  element will not be added
  	*/
  	public static boolean append(Document docu,Element ele){
		if (docu == null || ele == null) return false;
		//if (hasElement( docu, ele)) {
	//		return false;
	//}
		try {
	      //get the Domain_model element.
	      NodeList cons = docu.getElementsByTagName(XDmTag.getDmRootT());
	    	if (cons != null && cons.getLength() >0)
	    	{	
	         cons.item(0).appendChild(ele);
	         return true;
	    	}
		}
		catch (Exception e)
		{
			System.err.println(e);
		}
		return false;
  		
  	}//append()
  	
  	/** 
  	* remove(), remove an element from Domain_model's chidren 
  	* list if it exists. 
  	*/
  	public static void remove(Document docu,String iD){
		if (docu == null || iD == null) return;
		try {
	      //get the Domain_model element.
	      Element theE = docu.getElementById(iD);
	    	if (theE != null)
	    	{	
	    		Node parent = theE.getParentNode();
	    		Element temp = (Element )parent.removeChild(theE);
	    	}
		}
		catch (Exception e)
		{
			System.err.println(e);
		}
  		
  	}//remove()
  	
  	 	
  	/** 
  	* hasElement(), returns true if Document docu has an
  	* element whose id is the same as the element id of
  	* ele. it returns false, otherwise.
  	*
  	* Caution: Somehow after an element has been removed, this method 
  	* still returns true. even though that element is no long in
  	* the document printout. Idealy, it'd only return if find 
  	* the same element ID, not the same reference ID.
  	*/
	public static boolean hasElement(Document docu,Element ele){
		
		if (docu == null || ele == null) return false;
		try {
			String eleId= ele.getAttribute(XDmTag.getDmIdT());
			if (eleId == null || eleId == "") {
				System.out.println("no ID");
				return false;
			}
			if (docu.getElementById(eleId) != null) {
				String actName= docu.getElementById(eleId).getAttribute(XDmTag.getDmNameT());

				//System.out.println("********element " + actName + " exsits: ID: " + eleId);	
				
				return true;
			}
			
		}
		catch (Exception e)
		{
			System.err.println(e);
		}
		return false;

  	}//hasElement()
  	
	/** 
	*  setDoc(),
	* @PARAM: aDoc, the DOM doc 
	* @return void
	*/
	public void setDoc(Document aDoc)
  	{
		doc = aDoc;

  	} //setDoc()
	
	/**  
	* getDoc(),
	* @return Document
	*/
	public Document getDoc()
  	{
		return doc;

  	} //getDoc()

	/** 
	* setDtName(), 
	* @PARAM: aName, documenttype name
	* @return void
	*/
	public void setDtName(String aName)
  	{
		doctypeName = aName;

  	} //setDtName()

	/** 
	* setTamotVersion(), 
	* @PARAM: aName, TamotVersion
	* @return void
	*/
	public void setTamotVersion(String aName)
  	{
		TamotVersion = aName;

  	} //setTamotVersion()
	
	/** 
	* getDtName(), 
	* @return documenttype name
	*/
	public String getDtName()
  	{
		return doctypeName;

  	} //getDtName()
  	
	/** 
	* etTamotVersion(), 
	* @return Tamot version
	*/
	public String getTamotVersion()
  	{
		return TamotVersion;

  	} //getTamotVersion()
 
	/** 
	* setDtId(), getTamotVersion
	* @PARAM: aDoc, documenttype system ID
	* @return void
	*/
	public void setDtId(String aId)
  	{
		doctypeID = aId;

  	} //setDtId()
	
	/** 
	* getDtId(), 
	* @return Documenttype system ID
	*/
	public String getDtId()
  	{
		return doctypeID;

  	} //creatNewDoc()

	/**  
	* setDtId(),
	* @PARAM: aM, DmManager
	* @return void
	*/
	public void setDmManager(DmManager aM)
  	{
		dM = aM;

  	} //setDtId()
	
	/**  
	* getDmManager(),
	* @return domain model manager
	*/
	public static DmManager getDmManager()
  	{
		return dM;

  	} //getDmManager()
  	
	/** 
	* setXMLHeader(), set XMLHeader to String aH.
	*/
	public void setXMLHeader(String aH)
  	{
		XMLHeader = aH;

  	} //setXMLHeader()

  	
  		/**  
	* getXMLHeader(),
	* @return domain model manager
	*/
	public String getXMLHeader()
  	{
		return XMLHeader;

  	} //getXMLHeader()
  	
/** 
	* creatNewDoc(), create a DOM doc using the doctypeName and 
	* doctypeID information
	* @return Document
	*/
	public Document createNewDoc()
  	{
  		//System.out.println("create new doc");
  		DocumentImpl imp = null;

  		if (getDtName() != null && getDtId() != null){
  			
	  		DocumentTypeImpl tImp = new DocumentTypeImpl(new DocumentImpl(), 
	  			getDtName(), null, getDtId());
	  		imp = new DocumentImpl(tImp);
	  		
  		}
  		else 	imp = new DocumentImpl();
  		
  		Document docu = (Document)imp;
    	//System.out.println("now create  root ele");
      	Element root = docu.createElement(XDmTag.getRootT());
      	root.setAttribute(XDmTag.getVersionT(), getTamotVersion());
      	
    	//System.out.println("now create dm root ele");
      	Element dm = docu.createElement(XDmTag.getDmRootT());
      	root.appendChild(dm);
    	//System.out.println("now save color");
      
      	colorsToEle(dm, docu);
      	
      	//13-7-2001
      	styleToEle(dm, docu);

      	docu.appendChild(root);
  		setDoc(docu);

		return getDoc();

  	} //creatNewDoc()
  	
   	/** 
  	* colorToEle, write to XML elements
  	* if DM colors (Action-instance, Entity-instance
  	* concept) are not default colors
  	*/
	public  void colorsToEle(Element parent,Document doc){
		if (!(dM.getActColor().equals(DmManager.ACTION_COLOR)))
			saveActColor(parent,doc);
		if (!(dM.getEnColor().equals(DmManager.ENTITY_COLOR)))
			saveEnColor(parent,doc);
		if (!(dM.getConColor().equals(DmManager.CONCEPT_COLOR)))
			saveConColor(parent,doc);
	
		return ;
  	}//colorsToEle()
  	
  	
	public  void saveActColor(Element parent,Document doc){
		if (parent == null) return;
		Element elem = null;		

		try {
			String actColorTag= XDmTag.getAIColorT(); 
	  		elem = doc.createElement(actColorTag);
	  		
	  		String colorTag= XDmTag.getColorT(); 
			Element elemColor = doc.createElement(colorTag);
			
			int red = dM.getActColor().getRed();
			int green = dM.getActColor().getGreen();
			int blue = dM.getActColor().getBlue();

		    elemColor.setAttribute(XDmTag.getRedT(), Integer.toString(red));	//aCon.getName());
		    elemColor.setAttribute(XDmTag.getGreenT(), Integer.toString(green));	//aCon.getName());
		    elemColor.setAttribute(XDmTag.getBlueT(), Integer.toString(blue));	//aCon.getName());
			
		    //add color to act-colour
	      	elem.appendChild(elemColor);
	      	
		    //add act-color to domain-root
	      	parent.appendChild(elem);

	      
		}
		catch (Exception e)
		{
			System.err.println("Error occured when writing Action Color: " +e);
		}
		return ;
  	}//saveActColor()
  	
	public  void saveEnColor(Element parent,Document doc){
		if (parent == null) return;
		Element elem = null;		

		try {
			String enColorTag= XDmTag.getEIColorT(); 
	  		elem = doc.createElement(enColorTag);
	  		
	  		String colorTag= XDmTag.getColorT(); 
			Element elemColor = doc.createElement(colorTag);
			
			int red = dM.getEnColor().getRed();
			int green = dM.getEnColor().getGreen();
			int blue = dM.getEnColor().getBlue();

		    elemColor.setAttribute(XDmTag.getRedT(), Integer.toString(red));	//aCon.getName());
		    elemColor.setAttribute(XDmTag.getGreenT(), Integer.toString(green));	//aCon.getName());
		    elemColor.setAttribute(XDmTag.getBlueT(), Integer.toString(blue));	//aCon.getName());
			
		    //add color to Entity-colour
	      	elem.appendChild(elemColor);
	      	
		    //add Entity-color to domain-root
	      	parent.appendChild(elem);

	      
		}
		catch (Exception e)
		{
			System.err.println("Error occured when writing Entity Color: " +e);
		}
		return ;
  	}//saveEnColor()
  	
	public  void saveConColor(Element parent,Document doc){
		if (parent == null) return;
		Element elem = null;		

		try {
			String conColorTag= XDmTag.getConColorT(); 
	  		elem = doc.createElement(conColorTag);
	  		
	  		String colorTag= XDmTag.getColorT(); 
			Element elemColor = doc.createElement(colorTag);
			
			int red = dM.getConColor().getRed();
			int green = dM.getConColor().getGreen();
			int blue = dM.getConColor().getBlue();

		    elemColor.setAttribute(XDmTag.getRedT(), Integer.toString(red));	//aCon.getName());
		    elemColor.setAttribute(XDmTag.getGreenT(), Integer.toString(green));	//aCon.getName());
		    elemColor.setAttribute(XDmTag.getBlueT(), Integer.toString(blue));	//aCon.getName());
			
		    //add color to concept-colour
	      	elem.appendChild(elemColor);
	      	
		    //add concept-color to domain-root
	      	parent.appendChild(elem);

	      
		}
		catch (Exception e)
		{
			System.err.println("Error occured when writing Concept Color: " +e);
		}
		return ;
  	}//saveConColor()
 	 	
	/** 
	* allConEleToStore(), it add all DmConcept elements from
	* doc to the DmManager's DmConcept object collection 
	*/
	public void allConEleToStore()
  	{
  		if (getDoc() == null) return;
  		DmManager dMa = getDmManager();
  		XConcept xC= new XConcept(getDoc());
		NodeList allConEle = getDoc().getElementsByTagName(XDmTag.getConceptT());
      if (allConEle != null && allConEle.getLength() >0 ) {
			//System.out.println("DmConcept tag: \""+
			//		((Element)allConEle.item(0)).getTagName() + "\"");
			//System.out.println("DmConcept number: \""+allConEle.getLength());
      	for(int i = 0; i<allConEle.getLength(); i++) {      		
				Element aRel = (Element)allConEle.item(i); 
			/*	
				if (aRel != null)
					System.out.println("concept element name: \""+
						aRel.getAttribute(XDmTag.getDmNameT()));
					
				else
					System.out.println("element is null: \"");
			*/
				DmConcept con = xC.eleToCon(aRel);
		/*		if (con != null)
					System.out.println("concept name: \""+con.getName());
					
				else
					System.out.println("concept is null: \"");
		*/		
				dMa.addConcept(con);
				
				//ystem.out.println("concept name: \""+con.getName());
				
				//track the largest DM element ID
				long l =con.getIdDigits() ;
				if ( l > DmClass.getLargestID())
					DmClass.setNewId(l);				

      	}
      }
	         
  	} //allConEleToStore()
  	 	
	/** 
	* allConObjToDoc(), it add all DmConcept elements from
	* doc to the DmManager's DmConcept object collection 
	*/
	public void allConObjToDoc()
  	{
  		if (getDoc() == null) createNewDoc();
  		
  		DmManager dMa = getDmManager();
  		
		Collection allCon = dMa.getConceptAll();
		Iterator it = allCon.iterator();
		DmConcept aConcept ;
  		XConcept xC= new XConcept(getDoc());
		
		while (it.hasNext()) {
			aConcept= (DmConcept)it.next();
			xC.add(xC.conToEle(aConcept));	
		}
	
  	} //allConObjToDoc()
  	 	
	/** 
	* allEnEleToStore(), it add all DmEntity elements from
	* doc to the DmManager's EntityInstance object collection 
	*/
	public void allEnEleToStore()
  	{
  		if (getDoc() == null) return;
  		//DmManager dMa = getDmManager();
  		XEntity xE= new XEntity(getDoc());
		NodeList allEnEle = getDoc().getElementsByTagName(XDmTag.getEntityT());
      if (allEnEle != null && allEnEle.getLength() >0 ) {
      	for(int i = 0; i<allEnEle.getLength(); i++) {      		
			Element aRel = (Element)allEnEle.item(i);
			EntityInstance en = xE.eleToEn(aRel);
			
			//2001-8-20
			//check if the entity instance is already in store
			addToStore(en);
      	}
      }
	         
  	} //allEnEleToStore()
  	 	
	/** 
	* allEnObjToDoc(), it add all DmConcept elements from
	* doc to the DmManager's DmConcept object collection 
	*/
	public void allEnObjToDoc()
  	{
  		if (getDoc() == null) createNewDoc();
  		
  		DmManager dMa = getDmManager();
  		
		Collection allEn = dMa.getEInstanceAll();
		Iterator it = allEn.iterator();
		EntityInstance anEntity ;
  		XEntity xE= new XEntity(getDoc());
		
		while (it.hasNext()) {
			anEntity= (EntityInstance)it.next();
			xE.add(xE.enToEle(anEntity));	
		}
	
  	} //allEnObjToDoc()
  	 	
	/** 
	* allActEleToStore(), it add all DmAction elements from
	* doc to the DmManager's ActionInstance object collection 
	*/
	public void allActEleToStore()
  	{
  		if (getDoc() == null) return;
  		DmManager dMa = getDmManager();
  		XAction xA= new XAction(getDoc());
		NodeList allActEle = getDoc().getElementsByTagName(XDmTag.getActionT());
      if (allActEle != null && allActEle.getLength() >0 ) {
		//	System.out.println("partOf tag: \""+((Element)allActEle.item(0)).getTagName() + "\"");
      	for(int i = 0; i<allActEle.getLength(); i++) {      		
				Element aRel = (Element)allActEle.item(i); 
				ActionInstance act = xA.eleToAct(aRel);
				dMa.addAInstance(act);
				
				//track the largest DM element ID
				long l =act.getIdDigits() ;
				if ( l > DmClass.getLargestID())
					DmClass.setNewId(l);
				
      	}
      }
	         
  	} //allActEleToStore()
  	 	
	/** 
	* allActObjToDoc(), it add all the DmManager's ActionInstance objects 
	* to the doc tree   
	*/
	public void allActObjToDoc()
  	{
  		if (getDoc() == null) createNewDoc();
  		
  		DmManager dMa = getDmManager();
  		
		Collection allAct = dMa.getAInstanceAll();
		Iterator it = allAct.iterator();
		ActionInstance anAction ;
  		XAction xA= new XAction(getDoc());
		
		while (it.hasNext()) {
			anAction= (ActionInstance)it.next();
			xA.add(xA.actToEle(anAction));	
		}
	
  	} //allActObjToDoc()
  	
	/** 
	* allEnglishNounObjToDoc(), it add all EnglishNoun objects  from
	* the DmManager's DmConcept object collection to the doc 
	*/
	public void allEnglishNounObjToDoc()
  	{
  		if (getDoc() == null) createNewDoc();
  		
  		//DmManager dMa = getDmManager();
  	/*	
		Collection allCon = dM.getEnglishNounAll();
		Iterator it = allCon.iterator();
		EnglishNoun aConcept ;
  		XEnglishNoun xC= new XEnglishNoun(getDoc());
		
		while (it.hasNext()) {
			aConcept= (EnglishNoun)it.next();
			xC.add(xC.englishNounToEle(aConcept));	
		}
		*/
		
		Collection conE = dM.getObjectCons();
			//getConceptSome(ConceptType.getDefaultEntityType());
		Collection conU = dM.getConceptSome(ConceptType.getDefaultUserType());
		Collection conS = dM.getConceptSome(ConceptType.getDefaultSystemType());
		Collection conI = dM.getInterfaceCons();
		//getConceptSome(ConceptType.getInterfaceType());
		
		HashSet ts = new HashSet(conE);
		ts.addAll(conU);	//
 		ts.addAll(conS);	//
   		ts.addAll(conI);	//

   		Iterator i = ts.iterator();
		DmConcept c;
		EnglishNoun aNoun ;
		XEnglishNoun xC= new XEnglishNoun(getDoc());

		while (i.hasNext()) {
	    	c=(DmConcept)i.next();
	    	aNoun = (EnglishNoun)c.getCard(DmConcept._ENGLISH);
	    	xC.add(xC.englishNounToEle(aNoun)); 
		}
		
		
		
		
		
		
	
  	} //allEnglishNounObjToDoc()
  	
	/** 
	* allEnglishVerbObjToDoc(), it add all EnglishVerb objects,
	* regualr and irregular, from
	* the DmManager's  object collection to the doc 
	*/
	public void allEnglishVerbObjToDoc()
  	{
  		if (getDoc() == null) createNewDoc();
  		/*	
  		DmManager dMa = getDmManager();
  		
  		//add all regular verbs
		Collection allReg = dMa.getRegularVerbAll();
		Iterator it = allReg.iterator();
		EnglishVerb aVerb ;
  		XEnglishVerb xC= new XEnglishVerb(getDoc());
		
		while (it.hasNext()) {
			aVerb= (EnglishVerb)it.next();
			xC.add(xC.englishVerbToEle(aVerb));	
		}
		
		//add all irregular verbs
		Collection allIrr = dMa.getIrregularVerbAll();
		Iterator itt = allIrr.iterator();
		IrregularVerb verb ;
  		XIrregularVerb xI= new XIrregularVerb(getDoc());
		
		while (itt.hasNext()) {
			verb= (IrregularVerb)itt.next();
			xI.add(xI.irregularVerbToEle(verb));	
		}
		*/
		
		Collection conA = dM.getActionCons();
			//getConceptSome(ConceptType.getDefaultActionType());
		Iterator i = conA.iterator();
		DmConcept c;
		EnglishVerb aVerb ;
  		XEnglishVerb xC= new XEnglishVerb(getDoc());
		IrregularVerb IrVerb ;
  		XIrregularVerb xI= new XIrregularVerb(getDoc());
		
  		while (i.hasNext()) {
	    	 c=(DmConcept)i.next();
	    	aVerb = (EnglishVerb)c.getCard(DmConcept._ENGLISH);
	    	if (aVerb instanceof IrregularVerb){
	    		IrVerb = (IrregularVerb)aVerb;
	    		xI.add(xI.irregularVerbToEle(IrVerb));
	    	} else {
	    		xC.add(xC.englishVerbToEle(aVerb));	
	    	}
  		}
		
	
  	} //allEnglishVerbObjToDoc()
  	 	
	/** 
	* allEngNounEleToStore(), it add all EnglishNoun elements from
	* doc to the DmManager's EnglishNoun object collection 
	*/
	public void allEngNounEleToStore()
  	{
  		if (getDoc() == null) return;
  		DmManager dMa = getDmManager();
  		XEnglishNoun xC= new XEnglishNoun(getDoc());
		NodeList allConEle = getDoc().getElementsByTagName(XDmTag.getEnglishNounT());
      if (allConEle != null && allConEle.getLength() >0 ) {
			//System.out.println("partOf tag: \""+((Element)allConEle.item(0)).getTagName() + "\"");
      	for(int i = 0; i<allConEle.getLength(); i++) {      		
				Element aRel = (Element)allConEle.item(i); 
				EnglishNoun con = xC.eleToEnglishNoun(aRel);
				dMa.addEnglishN(con);
				
				//track the largest DM element ID
				long l =con.getIdDigits() ;
				if ( l > DmClass.getLargestID())
					DmClass.setNewId(l);				

      	}
      }
	         
  	} //allEngNounEleToStore()
  	 	
	/** 
	* allReguVerbEleToStore(), it add all  regular EnglishVerb elements from
	* doc to the DmManager's EnglishVerb object collection 
	*/
	public void allReguVerbEleToStore()
  	{
  		if (getDoc() == null) return;
  		DmManager dMa = getDmManager();
  		XEnglishVerb xC= new XEnglishVerb(getDoc());
		NodeList allConEle = getDoc().getElementsByTagName(XDmTag.getEnglishVerbT());
      if (allConEle != null && allConEle.getLength() >0 ) {
			//System.out.println("partOf tag: \""+((Element)allConEle.item(0)).getTagName() + "\"");
      	for(int i = 0; i<allConEle.getLength(); i++) {      		
				Element aRel = (Element)allConEle.item(i); 
				EnglishVerb con = xC.eleToEnglishVerb(aRel);
				dMa.addEnglishV(con);
				
				//track the largest DM element ID
				long l =con.getIdDigits() ;
				if ( l > DmClass.getLargestID())
					DmClass.setNewId(l);				

      	}
      }
	         
  	} //allReguVerbEleToStore()
  	 	
	/** 
	* allIrreVerbEleToStore(), it add all  Irrelar EnglishVerb elements from
	* doc to the DmManager's EnglishVerb object collection 
	*/
	public void allIrreVerbEleToStore()
  	{
  		if (getDoc() == null) return;
  		DmManager dMa = getDmManager();
  		XIrregularVerb xC= new XIrregularVerb(getDoc());
		NodeList allConEle = getDoc().getElementsByTagName(XDmTag.getIrregularVerbT());
      if (allConEle != null && allConEle.getLength() >0 ) {
			//System.out.println("partOf tag: \""+((Element)allConEle.item(0)).getTagName() + "\"");
      	for(int i = 0; i<allConEle.getLength(); i++) {      		
				Element aRel = (Element)allConEle.item(i); 
				IrregularVerb con = xC.eleToIrregularVerb(aRel);
				dMa.addEnglishV(con);
				
				//track the largest DM element ID
				long l =con.getIdDigits() ;
				if ( l > DmClass.getLargestID())
					DmClass.setNewId(l);				

      	}
      }
	         
  	} //allIrreVerbEleToStore()
  	
	public  Color readActColor(){
		
  		if (getDoc() == null) return null;
		try{
			NodeList allActColor = getDoc().
				getElementsByTagName(XDmTag.getAIColorT());
				
	      	if (allActColor != null && allActColor.getLength() >0 ) {
				Element actColorEle = (Element)allActColor.item(0); 
					
					return readColor(actColorEle);
			}
		}
		catch (Exception e)
		{
			//System.err.println("Exception In XManager.readActColor() "+ e);
			return null;
		}
		return null;
	}//readActColor()
  	
	public  Color readEnColor(){
		
  		if (getDoc() == null) return null;
		try{
			NodeList allEnColor = getDoc().
				getElementsByTagName(XDmTag.getEIColorT());
				
	      	if (allEnColor != null && allEnColor.getLength() >0 ) {
				Element enColorEle = (Element)allEnColor.item(0); 
					
				return readColor(enColorEle);
			}
		}
		catch (Exception e)
		{
			//System.err.println("Exception In XManager.readActColor() "+ e);
			return null;
		}
		return null;
	}//readEnColor()
  	
	public  Color readConColor(){
		
  		if (getDoc() == null) return null;
		try{
			NodeList allConColor = getDoc().
				getElementsByTagName(XDmTag.getConColorT());
				
	      	if (allConColor != null && allConColor.getLength() >0 ) {
				Element conColorEle = (Element)allConColor.item(0); 
					
				return readColor(conColorEle);
			}
		}
		catch (Exception e)
		{
			//System.err.println("Exception In XManager.readActColor() "+ e);
			return null;
		}
		return null;
	}//readConColor()
	
	public  Color readColor(Element ele){
		if (ele == null) return null;
		
		try{
			NodeList allColor = ele.
				getElementsByTagName(XDmTag.getColorT());
				
	      	if (allColor != null && allColor.getLength() >0 ) {
				Element colorEle = (Element)allColor.item(0);
				
	         	String redS= colorEle.getAttribute(XDmTag.getRedT());
				String greenS= colorEle.getAttribute(XDmTag.getGreenT());
				String blueS= colorEle.getAttribute(XDmTag.getBlueT());
				
				int red = Integer.parseInt(redS);
				int green = Integer.parseInt(greenS);
				int blue = Integer.parseInt(blueS);
				
				return (new Color(red, green, blue));
			}	 	         
		}
		catch (Exception e)
		{
			//System.err.println("Exception In XManager.readActColor() "+ e);
			return null;
		}
		
		return null;
	}//readColor()
	
	public void setDMColors(){
		Color actColor = readActColor();
		if (actColor != null)
			dM.setActColor(actColor);
			
		Color enColor = readEnColor();
		if (enColor != null)
			dM.setEnColor(enColor);
			
		Color conColor = readConColor();
		if (conColor != null)
			dM.setConColor(conColor);
	}
  	
   	/** 
  	* styleToEle, write to XML elements
  	* if document style parameters (how, step-by-step) 
  	* are not default values 13-7-2001
  	*/
	public  void styleToEle(Element parent,Document doc){
		if (dM.isConjunction() != DmManager.CONJUNCTION)
			saveStyleConjunction(parent,doc);
		if (dM.isStyleHow() != DmManager.STYLE_HOW)
			saveStyleHow(parent,doc);
		if (dM.isModalityCan() != DmManager.MODALITY_CAN)
			saveStyleModalityCan(parent,doc);
		if (dM.isPurposeFirst() != DmManager.PURPOSE_FIRST)
			saveStylePurposeFirst(parent,doc);
		if (dM.isStepByStep() != DmManager.STYLE_STEP_BY_STEP)
			saveStepByStep(parent,doc);
			
		return ;
  	}//styleToEle()
  	
  	//25-7-2001 
	public  void saveStyleConjunction(Element parent,Document doc){
		if (parent == null) return;

		try {
			if (dM.isConjunction())
		    	parent.setAttribute(XDmTag.getConjunctionT(), _XML_YES);
		   	else
		    	parent.setAttribute(XDmTag.getConjunctionT(), _XML_NO);
	      
		}
		catch (Exception e)
		{
			System.err.println("Error occured when writing style parameter conjunction: " +e);
		}
		return ;
  	}//saveStyleConjunction()
  	
   
  	//13-7-2001
	public  void saveStyleHow(Element parent,Document doc){
		if (parent == null) return;

		try {
			if (dM.isStyleHow())
		    	parent.setAttribute(XDmTag.getStyleHowT(), _XML_YES);
		   	else
		    	parent.setAttribute(XDmTag.getStyleHowT(), _XML_NO);
	      
		}
		catch (Exception e)
		{
			System.err.println("Error occured when writing style parameter how: " +e);
		}
		return ;
  	}//saveStyleHow()
  	
  	//25-7-2001
	public  void saveStyleModalityCan(Element parent,Document doc){
		if (parent == null) return;

		try {
			if (dM.isModalityCan())
		    	parent.setAttribute(XDmTag.getModalityCanT(), _XML_YES);
		   	else
		    	parent.setAttribute(XDmTag.getModalityCanT(), _XML_NO);
	      
		}
		catch (Exception e)
		{
			System.err.println("Error occured when writing style parameter modality-can: " +e);
		}
		return ;
  	}//saveStyleModalityCan()
  	
  	//25-7-2001
	public  void saveStylePurposeFirst(Element parent,Document doc){
		if (parent == null) return;

		try {
			if (dM.isPurposeFirst())
		    	parent.setAttribute(XDmTag.getPurposeFirstT(), _XML_YES);
		   	else
		    	parent.setAttribute(XDmTag.getPurposeFirstT(), _XML_NO);
	      
		}
		catch (Exception e)
		{
			System.err.println("Error occured when writing style parameter purpose-first: " +e);
		}
		return ;
  	}//saveStylePurposeFirst()
  	
  	//13-7-2001
	public  void saveStepByStep(Element parent,Document doc){
		if (parent == null) return;

		try {
			if (dM.isStepByStep())
		    	parent.setAttribute(XDmTag.getStepByStepT(), _XML_YES);
		   	else
		    	parent.setAttribute(XDmTag.getStepByStepT(), _XML_NO);
	      
		}
		catch (Exception e)
		{
			System.err.println("Error occured when writing style parameter step-by-step: " +e);
		}
		return ;
  	}//saveStepByStep()
	
  	//set style parameters, 13-7-2001
	public void setStyleParameters(){
		boolean conjunction = readConjunction();
		dM.setConjunction(conjunction);
		DmManager.setConjunctionMi(conjunction);
		
		boolean styleHow = readStyleHow();
		dM.setStyleHow(styleHow);
		DmManager.setHowMi(styleHow);
		
		boolean modalityCan = readModalityCan();
		dM.setModalityCan(modalityCan);
		//System.out.println("modality style = " + modalityCan);
		DmManager.setModalityCanMi(modalityCan);
		
		boolean purposeFirst = readPurposeFirst();
		dM.setPurposeFirst(purposeFirst);
		//System.out.println("how style = " + styleHow);
		DmManager.setPurposeFirstMi(purposeFirst);
		
		boolean stepValue = readStepByStep();
		dM.setStepByStep(stepValue);
		DmManager.setStepByStepMi(stepValue);

	}
	
	//25-7-2001
	public  boolean readConjunction(){
  		if (getDoc() == null) return false;
		try{
		
			NodeList dmNode = getDoc().
				getElementsByTagName(XDmTag.getDmRootT());
				
	      	if (dmNode != null && dmNode.getLength() >0 ) {
				Element dmEle = (Element)dmNode.item(0);	
	         	String value= dmEle.getAttribute(XDmTag.getConjunctionT());
				if (value.equals(_XML_YES))
					return true;
				else return false;
	      	}	 	         
		}
		catch (Exception e)
		{
			//System.err.println("Exception In XManager.readActColor() "+ e);
			return false;
		}
		
		return false;
	}//readConjunction()
	
	//13-7-2001
	public  boolean readStyleHow(){
  		if (getDoc() == null) return false;
		try{
		
			NodeList dmNode = getDoc().
				getElementsByTagName(XDmTag.getDmRootT());
				
	      	if (dmNode != null && dmNode.getLength() >0 ) {
				Element dmEle = (Element)dmNode.item(0);	
	         	String value= dmEle.getAttribute(XDmTag.getStyleHowT());
				if (value.equals(_XML_YES))
					return true;
				else return false;
	      	}	 	         
		}
		catch (Exception e)
		{
			//System.err.println("Exception In XManager.readActColor() "+ e);
			return false;
		}
		
		return false;
	}//readStyleHow()
	
	//25-7-2001
	public  boolean readModalityCan(){
  		if (getDoc() == null) return false;
		try{
		
			NodeList dmNode = getDoc().
				getElementsByTagName(XDmTag.getDmRootT());
				
	      	if (dmNode != null && dmNode.getLength() >0 ) {
				Element dmEle = (Element)dmNode.item(0);	
	         	String value= dmEle.getAttribute(XDmTag.getModalityCanT());
				if (value.equals(_XML_YES))
					return true;
				else return false;
	      	}	 	         
		}
		catch (Exception e)
		{
			//System.err.println("Exception In XManager.readActColor() "+ e);
			return false;
		}
		
		return false;
	}//readModalityFirst()
	
	//25-7-2001
	public  boolean readPurposeFirst(){
  		if (getDoc() == null) return false;
		try{
		
			NodeList dmNode = getDoc().
				getElementsByTagName(XDmTag.getDmRootT());
				
	      	if (dmNode != null && dmNode.getLength() >0 ) {
				Element dmEle = (Element)dmNode.item(0);	
	         	String value= dmEle.getAttribute(XDmTag.getPurposeFirstT());
				if (value.equals(_XML_YES))
					return true;
				else return false;
	      	}	 	         
		}
		catch (Exception e)
		{
			//System.err.println("Exception In XManager.readActColor() "+ e);
			return false;
		}
		
		return false;
	}//readPurposeFirst()
	
	//13-7-2001
	public  boolean readStepByStep(){
  		if (getDoc() == null) return true;	//true is the default value
		try{
		
			NodeList dmNode = getDoc().
				getElementsByTagName(XDmTag.getDmRootT());
				
	      	if (dmNode != null && dmNode.getLength() >0 ) {
				Element dmEle = (Element)dmNode.item(0);	
	         	String value= dmEle.getAttribute(XDmTag.getStepByStepT());
				if (value.equals(_XML_NO))
					return false;
				else return true;
	      	}	 	         
		}
		catch (Exception e)
		{
			//System.err.println("Exception In XManager.readActColor() "+ e);
			return true;
		}
		
		return true;
	}//readStepByStep()
	
	//2001-8-20 
	public static void addToStore(EntityInstance en){
		//check if the entity instance is already in store
		if (en != null){
			EntityInstance tempEn =dM.getEInstance(en.getID());
			if (tempEn == null){
				dM.addEInstance(en);
				//track the largest DM element ID
				long l =en.getIdDigits() ;
				if ( l > DmClass.getLargestID())
					DmClass.setNewId(l);
			}
		}
		return;
	}
	
  	/**
  	* Main program entry point. 
  	*/
  public static void main(String argv[]) 
  {
    if (argv.length == 0)
    {
      System.out.println("Usage:  java XAction uri");
      System.out.println("   where uri is the URI of the XML document you want to print.");
      System.out.println("   Sample:  java XAction dmTest3.xml");
      System.exit(1);
    }
   
		//testing xConcept
    	XManager xM = new XManager(XManager.parse(argv[0]));
    		xM.getDmManager().printAInstance(xM.getDmManager().getAInstanceAll());

    	xM.allConEleToStore();
    	xM.allEnEleToStore();
    	xM.allActEleToStore();
    	xM.getDmManager().printEInstance(xM.getDmManager().getEInstanceAll());
    /*	xM.createNewDoc();
    	xM.allConObjToDoc();
    	xM.allEnObjToDoc();
    	xM.allActObjToDoc();
   */
   //	XManager xM = new XManager();
   //	xM.setDoc(xM.createNewDoc());
    	printDOMTree(xM.getDoc());
    	
  }// main()
  	
}//class XManager static final long serialVersionUID = 7699304788206024258L;