/*
   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.
*/

//Source file: C:/Data/Isolde/Tamot2/Current/domainModel/DmManager.java

package domainModel;

import java.awt.*;
import java.util.*;
import utility.*;
import taskModellingTool.*;
import parser.FSParser.*;
import parser.slider.*;
import domainModel.gui.*;

/**
 * DmManager, maintains collections of Dmconcept and DmInstance 
 * objects. concept objects with indentical "name" and "type"
 * are considered to be equal. For instance objects, "name" and 
 * "conceptOf" can be used to uniquely identify an object.
 * @author 
 */
public class DmManager extends Object
{
	private HashMap conceptAll= new HashMap(); 	// DmConcept concept collection,
	private HashMap eInstanceAll= new HashMap();	//entity instance clollection
	private HashMap aInstanceAll= new HashMap();	//action instance clollection 
	private HashMap _englishNoun= new HashMap();	//English noun clollection
	private HashMap _englishVerb= new HashMap();	//English verb clollection 
	
	private HashMap _predefinedInterfaceConcepts= new HashMap(); 
			// concept collection, populated by addInterfaceConcepts()
	private HashMap _predefinedInterfaceCards= new HashMap(); 
			// english cards corresponding to concept collection, 
			//populated by addInterfaceConcepts()
	private final String _idPrefix = "def_";	 // used to differeciate predefined 

	private static DmManager dmInstance	
      = new DmManager();
  	private static Parser _defaultParser=new Parser(dmInstance,"action.grammar");  //"simple.grammar");  // for 3-word expressions
  	private static Parser _complexParser=new Parser(dmInstance,"action.grammar");  // for 3-word expressions

  	public static final Color CONCEPT_COLOR = Color.red.darker(); 	//DEFAUT CONCEPT COLOR
  	public static final Color ENTITY_COLOR = (new Color(200, 140, 80)).darker(); 	//DEFAUT ENTITY INSTANCE COLOR
  	public static final Color ACTION_COLOR = Color.blue.darker(); 	//DEFAUT action instance COLOR
  	
  	private static Color _currentConColor = 
  				CONCEPT_COLOR; 	//current CONCEPT COLOR
  	private static Color _currentEnColor = 
  				ENTITY_COLOR; 	//current entity instance COLOR
	private static Color _currentActColor = 
				ACTION_COLOR; 	//current action instance COLOR
				  	
  	private static Parser defaultParser; // for 3-word expressions
    private static Parser actionParser;  // for general action expressions
    private static ParseFrame  slider ;           // the parser interface
    
    //online help documents style parameters
  	public static final boolean  STYLE_STEP_BY_STEP  = true; 	//DEFAUT _stepByStep value
  	public static final boolean STYLE_HOW = false; 	//DEFAUT _how value
  	public static final boolean  MODALITY_CAN  = false; 	//DEFAUT _modalityCan value
  	public static final boolean PURPOSE_FIRST = false; 	//DEFAUT _purposeFirst value
  	public static final boolean  CONJUNCTION  = false; 	//DEFAUT _conjuction value
  	private static boolean _stepByStep = STYLE_STEP_BY_STEP;
  	private static boolean _how = STYLE_HOW;
  	private static boolean _modalityCan = MODALITY_CAN;
  	private static boolean _purposeFirst = PURPOSE_FIRST;
  	private static boolean _conjunction = CONJUNCTION;
  
  	/**
     * This private constructor is defined so the compiler won't
     * generate a default public constructor.
     */
    private DmManager() { 
    	// populate the container with predefined concepts
    	DmConcept defEnt=DmConcept.getDefaultEntityConcept();
    	DmConcept defAct=DmConcept.getDefaultActionConcept();
    	DmConcept defUser=DmConcept.getDefaultUserConcept();
    	DmConcept defSys=DmConcept.getDefaultSystemConcept();
    	DmConcept defInterface=DmConcept.getInterfaceConcept();
    	
    	conceptAll.put(defEnt.getID(),defEnt);
    	conceptAll.put(defAct.getID(),defAct);
    	conceptAll.put(defUser.getID(),defUser);
    	conceptAll.put(defSys.getID(),defSys);
    	conceptAll.put(defInterface.getID(),defInterface);
 /*   	conceptAll.put(DmConcept.getDefaultActionConcept().getID(),
    		DmConcept.getDefaultActionConcept());
    	conceptAll.put(DmConcept.getDefaultUserConcept().getID(),
    		DmConcept.getDefaultUserConcept());
    	conceptAll.put(DmConcept.getDefaultSystemConcept().getID(),
    		DmConcept.getDefaultSystemConcept());
    */	
    	//add language card into cards collection
    	addEnglishN((EnglishNoun)defEnt.getCard(DmConcept._ENGLISH));	
    	addEnglishV((EnglishVerb)defAct.getCard(DmConcept._ENGLISH));	
    	addEnglishN((EnglishNoun)defUser.getCard(DmConcept._ENGLISH));	
    	addEnglishN((EnglishNoun)defSys.getCard(DmConcept._ENGLISH));	
     	addEnglishN((EnglishNoun)defInterface.getCard(DmConcept._ENGLISH));	
   	
    	// populate the container with predefined Instances
    	eInstanceAll.put(EntityInstance.getDefaultUserInstance().getID(),
    		EntityInstance.getDefaultUserInstance());
    	eInstanceAll.put(EntityInstance.getDefaultSystemInstance().getID(),
    		EntityInstance.getDefaultSystemInstance());
    		
       	//this method is only for test purpose
    		testDM();
 		
    	//create predefined interface concepts
    	addInterfaceConcepts();
    	
    		
    	//2001-2-13
    	//_defaultParser = new Parser(this,"simple.grammar");
    }
    
    /**
     * Return a reference to the only instance of this class.
     */
    public static DmManager getInstance() {
        return dmInstance;
    } // getInstance()

    /**
	 * getConceptAll, return a sorted read-only version of the concept
	 * object collection
	 */
	public Collection getConceptAll() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		Collection v =conceptAll.values();
		sv.addAll(v);
		sv.sort();

		return Collections.synchronizedCollection(sv);
	}
	
    /**
	 * getConceptSome, return a sorted sub-set of read-only version of the concept
	 * object collection. the sub-set is defined by the "type" parameter.
	 * @param type, the concept to add 
	 */
	public Collection getConceptSome(String type) {
		if (type == null) return null;
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		Collection v = conceptAll.values();
		Iterator it = v.iterator();
		DmConcept aConcept ;
		while (it.hasNext()) {
			aConcept= (DmConcept)it.next();
    	//	System.out.println(" concepts: " + aConcept.getName()
    	//		+ "type: \"" +aConcept.getType()+ "\"");
				
			if (aConcept.getType().equals(type)) {
				sv.add(aConcept);
			}
		}
		
		sv.sort(); // sort concept in alphebatical order 
					// according to "name"

		return Collections.synchronizedCollection(sv);
	}//getConceptSome()
	

	/**
	 * addConcept, is the method to add a concept object into
	 * the concept collection. if a concept with the same "name"
	 * and "type" exists in the collection, a refernce to that 
	 * object is returned
	 * @exception 
	 * @author 
	* @param aConcept, the concept to add
	 */
	public DmConcept addConcept(DmConcept aConcept) {
		
		if (aConcept == null) return null;
		
		//CombinedKey key = 
		//	new CombinedKey(aConcept.getName(), aConcept.getType());
			
		String key = aConcept.getID(); // use ID as key

		if (!conceptAll.containsKey(key)){
		//	System.out.println("add DmConcept: \""+aConcept.getName());
			conceptAll.put(key,aConcept);
			return aConcept;
		} else {
			return (DmConcept)conceptAll.get(key); // return a reference to the 
													// existing concept object
		}
	
	}//addConcept()

	/**
	 * removeConcept, is the method to remove a concept object from
	 * the concept collection. 
	* @param aConcept, the concept to be removed 
	 */
	public DmConcept removeConcept(DmConcept aConcept) {
		
		if (aConcept == null) return null;
		
		if (aConcept.equals(DmConcept.getDefaultEntityConcept()) ||
			aConcept.equals(DmConcept.getDefaultUserConcept()) ||
			aConcept.equals(DmConcept.getDefaultSystemConcept()) ||
			aConcept.equals(DmConcept.getDefaultActionConcept()) ||
			aConcept.equals(DmConcept.getInterfaceConcept()) ||
			_predefinedInterfaceConcepts.containsValue(aConcept)) 
			return null;
		
		//CombinedKey key = 
		//	new CombinedKey(aConcept.getName(), aConcept.getType());
			
		String key = aConcept.getID(); // use ID as key
		if (aConcept.numberOfInstances() > 0){
			System.err.println("There are instances of concept "+
				aConcept.getName()+". please remove all of its instances "+
				"\n before remove the concept!!");
				return null;
			
		}
			
		if (conceptAll.containsKey(key)){
			conceptAll.remove(key);
			return aConcept;
		} else {
			return null;
		}
	
	}//removeConcept()

    /**
	 * getEInstanceAll, return a sorted read-only version of the entity
	 * instance object collection
	 */
	public Collection getEInstanceAll() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		Collection v =eInstanceAll.values();
		sv.addAll(v);
		sv.sort();

		return Collections.unmodifiableCollection(sv);

	}

	/**
	 * getAInstanceAll, return a sorted read-only version of the action
	 * instance object collection
	 */
	public Collection getAInstanceAll() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		Collection v =aInstanceAll.values();
		sv.addAll(v);
		sv.sort();

		return Collections.unmodifiableCollection(sv);
	}

	/**
	 * addEInstance, is the method to add a entity-instance object into
	 * the instance collection. if a instance with the same "name"
	 * and "conceptOf" exists in the collection, a refernce to that 
	 * object is returned
	 * @exception 
	 * @author 
	* @param eInstance, the entity instance to add
	 */
	public EntityInstance addEInstance(EntityInstance eInstance) {
		
		if (eInstance == null) return null;
		
		//CombinedKey key = 
		//	new CombinedKey(eInstance.getName(), eInstance.getConceptOf().getName());
		String key = eInstance.getID(); // use ID as key
		if (!eInstanceAll.containsKey(key)){
			eInstanceAll.put(key,eInstance);
			return eInstance;
		} else {
			return (EntityInstance)eInstanceAll.get(key); // return a reference to the 
													// existing entity-instance object
		}
	
	}//addEInstance()

	/**
	 * addAInstance, is the method to add a action-instance object into
	 * the action-instance collection. if a instance with the same "name"
	 * and "conceptOf" exists in the collection, a refernce to that 
	 * object is returned
	* @param aInstance, the action-instance to add
	 */
	public ActionInstance addAInstance(ActionInstance aInstance) {
		
		if (aInstance == null) return null;
		
	//	CombinedKey key = 
	//		new CombinedKey(aInstance.getName(), aInstance.getConceptOf().getName());
		String key = aInstance.getID(); // use ID as key
		
		if (!aInstanceAll.containsKey(key)){
			aInstanceAll.put(key,aInstance);
			return aInstance;
		} else {
			return (ActionInstance)aInstanceAll.get(key); // return a reference to the 
													// existing action-instance object
		}
	
	}//addAInstance()
	
	/**
	 * getAInstance, is the method to get an action-instance object from
	 * the action-instance collection. It first uses the param "str" as ID,
	 * if not found, then search for action-instance with name of "str"  
	 * @param id, the str of the action-instance to fetch
	 */
	public ActionInstance getAInstance(String str) {
		
		if (str == null) return null;
		ActionInstance temp = (ActionInstance)aInstanceAll.get(str);
		 
		if ( temp != null)  return temp;
		else {
		
			Collection v = aInstanceAll.values();
			Iterator it = v.iterator();
			ActionInstance aIns, theIns = null;
			while (it.hasNext()) {
				aIns= (ActionInstance)it.next();
					
				if (aIns.getName() == str) {
					theIns =aIns;
					break;
				}
			}
			return theIns;
		}
		

		
	
	}//getAInstance()
	
	/**
	 * getEInstance, is the method to get an entity-instance object from
	 * the entity-instance collection. 
	 * @param id, the ID of the entity-instance to fetch
	 */
	public EntityInstance getEInstance(String id) {
		
		if (id == null) return null;
		return (EntityInstance)eInstanceAll.get(id); 
		
	
	}//getEInstance()
	
	/**
	 * getConcept, is the method to get a action-instance object from
	 * the action-instance collection. 
	 * @param id, the ID of the action-instance to fetch
	 */
	public DmConcept getConcept(String id) {
		
		if (id == null) return null;
		
		return (DmConcept)conceptAll.get(id); 
		
	
	}//getConcept()

	/**
	 * removeEInstance, is the method to remove a concept object from
	 * the concept collection. 
	* @param eInstance, the instnace to be removed 
	 */
	public EntityInstance removeEInstance(EntityInstance eInstance) {
		
		if (eInstance == null) return null;
		if (eInstance.equals(EntityInstance.getDefaultUserInstance()) ||
			eInstance.equals(EntityInstance.getDefaultSystemInstance()) ) 
			return null;
	//	CombinedKey key = 
	//		new CombinedKey(eInstance.getName(), eInstance.getConceptOf().getName());
		String key = eInstance.getID(); // use ID as key
		if (eInstanceAll.containsKey(key)){
			eInstanceAll.remove(key);
						
			//remove it from its concept-instances
			eInstance.setConceptOf(null);
			
			return eInstance;
		} else {
			return null;
		}
	
	}//removeEInstance()

	/**
	 * removeAInstance, is the method to remove a action-instance object from
	 * the action instance collection. 
	* @param aConcept, the action-instance to be removed 
	 */
	public ActionInstance removeAInstance(ActionInstance aInstance) {
		
		if (aInstance == null) return null;
		//remove semantics from relevant tasks
		Manager.removeSemantics(findTaskAIns(aInstance));
		
		//CombinedKey key = 
		//	new CombinedKey(aInstance.getName(), aInstance.getConceptOf().getName());
		String key = aInstance.getID(); // use ID as key
		if (aInstanceAll.containsKey(key)){
			aInstanceAll.remove(key); // remove from the action instance collection
			
			//remove it from its concept-instances
			aInstance.setConceptOf(null);
			
			
			return aInstance;
		} else {
			return null;
		}
	
	}//removeAInstance()


	/**
	 * printConcept, print concept's name, type and number of instances 
	 * to the standard output
	 */
	public void printConcept(Collection con) {
		
		Iterator it = con.iterator();
		DmConcept aConcept ;
		System.out.println("Name                Type          No. of instnaces     ID");
		while (it.hasNext()) {
			aConcept= (DmConcept)it.next();
				
			System.out.println(aConcept.getName()+"          "+ 
				aConcept.getType()+"         "+
				aConcept.numberOfInstances()+ "       "+ aConcept.getID()  );
		}
	
	}//printConcept()
    

	/**
	 * printAInstance, print action instances's name, conceptOf 
	 * and relations 
	 * to the standard output
	 */
	public void printAInstance(Collection con) {
		
		Iterator it = con.iterator();
		ActionInstance aInstance ;
		DmRelation relM = DmRelation.getInstance();

		System.out.println("Name                ConceptOf          ");
		while (it.hasNext()) {
			aInstance= (ActionInstance)it.next();
				
			System.out.println(aInstance.getName()+"          "+ 
				aInstance.getConceptOf().getName() );
				
    		String allActRle[] = relM.getAllActionRelations();
			TreeMap reActInstances = aInstance.getActionRelations();    
			for (int j = 0; j < allActRle.length; j++) {
				if (reActInstances.get(allActRle[j]) != null){
    				System.out.println("     "+allActRle[j]+" Instance: " 
    					+((DmInstance) reActInstances.get(allActRle[j])).getName());				
				}
       		}  
		}
	
	}//printAInstance()
    	

	/**
	 * printEInstance, print entity instances's name, conceptOf, cardinality,
	 * and relations 
	 * to the standard output
	 */
	public void printEInstance(Collection con) {
		
		Iterator it = con.iterator();
		EntityInstance eInstance ;
		DmRelation relM = DmRelation.getInstance();

		System.out.println("Name                ConceptOf          Cardinality         Concept  ID");
		while (it.hasNext()) {
			eInstance= (EntityInstance)it.next();
				
			System.out.println(eInstance.getName()+"         "+ 
				eInstance.getConceptOf().getName()+"         "+ 
				eInstance.getCardinality()+"        "+eInstance.getConceptOf().getID() );
				
    		String allActRle[] = relM.getAllEntityRelations();
			TreeMap reActInstances = eInstance.getEntityRelations();    
			for (int j = 0; j < allActRle.length; j++) {
				if (reActInstances.get(allActRle[j]) != null){
    				System.out.println("     "+allActRle[j]+" Instance: " 
    					+((DmInstance) reActInstances.get(allActRle[j])).getName());				
				}
       		}  
		}
	
	}//printEInstance()
    	
	/**
	 * isConcept(String st), retruns true if there is concept whose name is 
	 * as specified in st (case ignored). it returns false otherwise
	 */
	public boolean isConcept(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		
		Iterator it = conceptAll.values().iterator();
		DmConcept concept ;

		while (it.hasNext()) {
			concept= (DmConcept)it.next();
				
			//System.out.println(concept.getName());
				
			if (temp.equals(concept.getName())) return true;
		}
		
		return false;
	
	}//isConcept()

    	
	/**
	 * isEInstance(String st), retruns true if there is concept whose name is 
	 * as specified in st (case ignored). it returns false otherwise
	 */
	public boolean isEInstance(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		
		Iterator it = eInstanceAll.values().iterator();
		EntityInstance eInstance ;

		while (it.hasNext()) {
			eInstance= (EntityInstance)it.next();
				
			//	System.out.println(eInstance.getName());
				
			if (temp.equals(eInstance.getName())) return true;
		}
		
		return false;
	
	}//isEInstance()
    	
	/**
	 * isAInstance(String st), retruns true if there is concept whose name is 
	 * as specified in st (case ignored). it returns false otherwise
	 */
	public boolean isAInstance(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		
		Iterator it = aInstanceAll.values().iterator();
		ActionInstance aInstance ;

		while (it.hasNext()) {
			aInstance= (ActionInstance)it.next();
				
			//	System.out.println(eInstance.getName());
				
			if (temp.equals(aInstance.getName())) return true;
		}
		
		return false;
	
	}//isAInstance()
    	
	/**
	 * getEConcept(String st), retruns a reference to the 
	 * entity concept if there is such concept whose name is 
	 * as specified in st (case ignored). it returns null otherwise
	 */
	public DmConcept getEConcept(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		Collection con = getConceptSome(ConceptType.getDefaultEntityType());
		
		Iterator it = con.iterator();
		DmConcept concept ;

		while (it.hasNext()) {
			concept= (DmConcept)it.next();
				
			//System.out.println(concept.getName());
				
			if (temp.equals(concept.getName())) return concept;
		}
		
		return null;
	
	}//getEConcept()
    	
	/**
	 * getUserConcept(String st), retruns a reference to the 
	 * User concept if there is such concept whose name is 
	 * as specified in st (case ignored). it returns null otherwise
	 */
	public DmConcept getUserConcept(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		Collection con = getConceptSome(ConceptType.getDefaultUserType());
		
		Iterator it = con.iterator();
		DmConcept concept ;

		while (it.hasNext()) {
			concept= (DmConcept)it.next();
				
			//System.out.println(concept.getName());
				
			if (temp.equals(concept.getName())) return concept;
		}
		
		return null;
	
	}//getUserConcept()

    	
	/**
	 * getSystemConcept(String st), retruns a reference to the 
	 * System concept if there is such concept whose name is 
	 * as specified in st (case ignored). it returns null otherwise
	 */
	public DmConcept getSystemConcept(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		Collection con = getConceptSome(ConceptType.getDefaultSystemType());
		
		Iterator it = con.iterator();
		DmConcept concept ;

		while (it.hasNext()) {
			concept= (DmConcept)it.next();
				
			//System.out.println(concept.getName());
				
			if (temp.equals(concept.getName())) return concept;
		}
		
		return null;
	
	}//getSystemConcept()

	/**
	 * getAConcept(String st), retruns a reference to the 
	 * action concept if there is such concept whose name is 
	 * as specified in st (case ignored). it returns null otherwise
	 */
	public DmConcept getAConcept(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
		if (st == null) return null;
		
		//leading and trailling spaces
		Collection con = getActionCons();
			//getConceptSome(ConceptType.getDefaultActionType());
		
		Iterator it = con.iterator();
		DmConcept concept ;

		while (it.hasNext()) {
			concept= (DmConcept)it.next();
				
			//System.out.println(concept.getName());
				
			if (temp.equals(concept.getName()) ||
				temp.equals(concept.getID())) return concept;
		}
		
		return null;
	
	}//getAConcept()
    	
	/**
	 * getInterfaceConcept(String st), retruns a reference to the 
	 * interface concept if there is such concept whose name is 
	 * as specified in st (case ignored). it returns null otherwise
	 */
	public DmConcept getInterfaceConcept(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		Collection con = getConceptSome(ConceptType.getInterfaceType());
		
		Iterator it = con.iterator();
		DmConcept concept ;

		while (it.hasNext()) {
			concept= (DmConcept)it.next();
			if (temp.equals(concept.getName())) return concept;
		}
		
		return null;
	
	}//getInterfaceConcept()

    	    	
	/**
	 * getEInstanceByName(String st), retruns a reference to the 
	 * entityInstance if there is such instance whose name is 
	 * as specified in st (case ignored). it returns null otherwise
	 */
	public EntityInstance getEInstanceByName(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		
		Iterator it = eInstanceAll.values().iterator();
		EntityInstance eInstance ;

		while (it.hasNext()) {
			eInstance= (EntityInstance)it.next();
				
			//	System.out.println(eInstance.getName());
				
			if (temp.equals(eInstance.getName())) return eInstance;
		}
		
		return null;
	
	}//getEInstanceByName()
    	
	/**
	 * getAInstanceByName(String st), retruns a reference to the 
	 * action Instance if there is such instance whose name is 
	 * as specified in st (case ignored). it returns null otherwise
	 */
	public ActionInstance getAInstanceByName(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		
		Iterator it = aInstanceAll.values().iterator();
		ActionInstance aInstance ;

		while (it.hasNext()) {
			aInstance= (ActionInstance)it.next();
				
			//	System.out.println(eInstance.getName());
				
			if (temp.equals(aInstance.getName())) return aInstance;
		}
		
		return null;
	
	}//getAInstanceByName()

	/**
	 * addEnglishN, is the method to add a EnglishNoun object into
	 * the _engliahNoun collection. if a instance with the same "name"
	 * exists in the collection, it will refer to that instance
	 * @param eng, the EnglishNoun object to add
	 */
	public boolean addEnglishN(EnglishNoun eng) {
		
		if (eng == null) return false;
		//String name = eng.getName();
		//EnglishNoun existN = getEnglishN(name);
		
		//if (existN == null)
			_englishNoun.put(eng.getID(),eng);

		return true;
	
	}//addEnglishN()

	/**
	 * addEnglishV, is the method to add a EnglishVerb object into
	 * the _engliahVerb collection. if a instance with the same "name"
	 * exists in the collection, it will be overwritten
	 * @param eng, the EnglishVerb object to add
	 */
	public boolean addEnglishV(EnglishVerb eng) {
		
		if (eng == null) return false;
		_englishVerb.put(eng.getID(),eng);
		return true;
	
	}//addEnglishV()
    	
	/**
	 * getEnglishN(String st), retruns a reference to the 
	 * EnglishNoun object if there is such instance whose name is 
	 * as specified in st (case ignored). it returns null otherwise
	 */
	public EnglishNoun getEnglishN(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		
		if (_englishNoun.containsKey(temp))
			return (EnglishNoun)_englishNoun.get(temp);
		else {
			Collection con = _englishNoun.values();
			
			Iterator it = con.iterator();
			EnglishNoun en ;
	
			while (it.hasNext()) {
				en= (EnglishNoun)it.next();
				//System.out.println(concept.getName());
				if (temp.equals(en.getName())) return en;
			}
		}
		
		
		return null;
	
	}//getEnglishN()
    	
	/**
	 * getEnglishV(String st), retruns a reference to the 
	 * EnglishVerb object if there is such instance whose name is 
	 * as specified in st (case ignored). it returns null otherwise
	 */
	public EnglishVerb getEnglishV(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		
		if (_englishVerb.containsKey(temp))
			return (EnglishVerb)_englishVerb.get(temp);
		
		return null;
	
	}//getEnglishV()
	
	
	//testDM() called in the constructor
	private void testDM(){
		
/*		//create some dmconcepts
		DmConcept dc1= new DmConcept("menu");
		dc1.setType(ConceptType.getDefaultEntityType());	
		addConcept(dc1);
    	addEnglishN((EnglishNoun)dc1.getCard(DmConcept._ENGLISH));	

    	DmConcept dc2= new DmConcept("menuitem");
		dc2.setType(ConceptType.getDefaultEntityType());
		addConcept(dc2);
    	addEnglishN((EnglishNoun)dc2.getCard(DmConcept._ENGLISH));	
*/
    	DmConcept dc3= new DmConcept("medium");
		dc3.setType(ConceptType.getDefaultEntityType());
		IrregularNoun med = new IrregularNoun("medium");
		med.setPlural("media");
		addEnglishN(med);

		dc3.setCard(DmConcept._ENGLISH,med);
		addConcept(dc3);
		
		DmConcept dc4= new DmConcept("do");
		dc4.setType(ConceptType.getDefaultActionType());
		IrregularVerb d = new IrregularVerb("do");
		d.set3rdP("does");
		d.setPast("did");
		d.setPp("done");
		addEnglishV(d);

		dc4.setCard(DmConcept._ENGLISH,d);
		addConcept(dc4);
/*
		//create some dmconcepts
		EntityInstance ei1= new EntityInstance ("file");
		ei1.setConceptOf(dc1);	
		addEInstance(ei1);
		
		EntityInstance ei2= new EntityInstance ("medium");
		ei2.setConceptOf(dc2);
		ei2.setEntityRelation("part of",ei1);
		addEInstance(ei2);
	*/	
	}

    /**
	 * getEnglishNounAll, return a sorted read-only version of the getEnglishNoun
	 * object collection
	 */
	public Collection getEnglishNounAll() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		Collection v =_englishNoun.values();
		sv.addAll(v);
		sv.sort();

		return Collections.unmodifiableCollection(sv);
	}

    /**
	 * getEnglishVerbAll, return a sorted read-only version of the getEnglishVerb
	 * object collection
	 */
	public Collection getEnglishVerbAll() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		Collection v =_englishVerb.values();
		sv.addAll(v);
		sv.sort();

		return Collections.unmodifiableCollection(sv);
	}//getEnglishVerbAll()
	
    /**
	 * getRegularVerb, return a sorted sub-set of read-only version of the RegularVerb
	 * object collection. .
	 */
	public Collection getRegularVerbAll() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		Collection v = _englishVerb.values();
		Iterator it = v.iterator();
		EnglishVerb aVerb ;
		while (it.hasNext()) {
			aVerb= (EnglishVerb)it.next();
				
			if (!(aVerb instanceof IrregularVerb )) {
				sv.add(aVerb);
			}
		}
		
		sv.sort(); // sort EnglishVerb in alphebatical order 
					// according to "name"

		return Collections.unmodifiableCollection(sv);
	}//getRegularVerb()
	
    /**
	 * getIrregularVerb, return a sorted sub-set of read-only version of the getIrregularVerb
	 * object collection. .
	 */
	public Collection getIrregularVerbAll() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		Collection v = _englishVerb.values();
		Iterator it = v.iterator();
		EnglishVerb aVerb ;
		while (it.hasNext()) {
			aVerb= (EnglishVerb)it.next();
				
			if (aVerb instanceof IrregularVerb ) {
				sv.add(aVerb);
			}
		}
		
		sv.sort(); // sort EnglishVerb in alphebatical order 
					// according to "name"
		System.out.println("************** irregular v num: "+ sv.size());
		
		return Collections.unmodifiableCollection(sv);
	}//getIrregularVerb()
	
    /**
	 * getEConceptAll, return a sorted sub-set of read-only version of the getIrregularVerb
	 * object collection. .
	 */
	public Collection getEConceptAll() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		Collection conE = getConceptSome(ConceptType.getDefaultEntityType());
 		Collection conU = getConceptSome(ConceptType.getDefaultUserType());
 		Collection conS = getConceptSome(ConceptType.getDefaultSystemType());
 		Collection conI = getConceptSome(ConceptType.getInterfaceType());
 		
 		HashSet ts = new HashSet(conE);
 		ts.addAll(conU);	//add ts to conE
  		ts.addAll(conS);	//add ts to conE as well
		ts.addAll(conI);	//add ts to conE as well
		//return Collections.unmodifiableCollection((Collection)ts);
			
		sv.addAll((Collection)ts);
		sv.sort();

		return Collections.unmodifiableCollection(sv);


	}
	
    	
	/**
	 * getEConcept(String st), retruns a reference to the 
	 * entity concept of type Entity, user or system. if there is such concept whose name is 
	 * as specified in st (case ignored). it returns null otherwise
	 */
	public DmConcept getEConceptAny(String st) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		Collection con = getEConceptAll();
		
		Iterator it = con.iterator();
		DmConcept concept ;

		while (it.hasNext()) {
			concept= (DmConcept)it.next();
				
			//System.out.println(concept.getName());
				
			if (temp.equals(concept.getName())) return concept;
		}
		
		return null;
	
	}//getEConcept()
	
	//Shijian
	//2001-2-12
    public static void newECon(){
    	//System.out.println("Create new thing concept ");
    	try{
    		DMNameNew newEC = new DMNameNew(MainFrame.getMainFrame(),
    			DMNameNew.NEW_ENTITY_CONCEPT);
    	}catch( UnknownDMClassException e ) {
         System.err.println( "Unrecognized domain class! " + e );
      	}
    }
    
    public static void newSCon(){
    	//System.out.println("Create new system concept ");
    	try{
    		DMNameNew newEC = new DMNameNew(MainFrame.getMainFrame(),
    			DMNameNew.NEW_SYSTEM_CONCEPT);
    	}catch( UnknownDMClassException e ) {
         System.err.println( "Unrecognized domain class! " + e );
      	}
    }
    
    public static void newUCon(){
    	//System.out.println("Create new user concept ");
    	try{
    		DMNameNew newEC = new DMNameNew(MainFrame.getMainFrame(),
    			DMNameNew.NEW_USER_CONCEPT);
    	}catch( UnknownDMClassException e ) {
         System.err.println( "Unrecognized domain class! " + e );
      	}
    }
    
    
    public static void newICon(){
    	//System.out.println("Create new user concept "); 
    	try{
    		DMNameNew newEC = new DMNameNew(MainFrame.getMainFrame(),
    			DMNameNew.NEW_INTERFACE_CONCEPT);
    	}catch( UnknownDMClassException e ) {
         System.err.println( "Unrecognized domain class! " + e );
      	}
    }
    
  	//Shijian 2001-2-12
    public static void newACon(){
    	//System.out.println("Create new action concept ");  
    	try{
    		DMNameNew newEC = new DMNameNew(MainFrame.getMainFrame(),
				DMNameNew.NEW_ACTION_CONCEPT);
    	}catch( UnknownDMClassException e ) {
         System.err.println( "Unrecognized domain class! " + e );
      	}
    }
    
  	//Shijian 2001-2-12
    public static void newEIns(){
    	NewEInstance newEC = new NewEInstance(MainFrame.getMainFrame(), 
    		"", 
    			"Create new Object Instance",
    				ConceptType.getDefaultEntityType());
    /*
    	System.out.println("Create new thing Instance ");  
    	try{
    		DMNameNew newEC = new DMNameNew(MainFrame.getMainFrame(),
				DMNameNew.NEW_ENTITY_INSTANCE);
    	}catch( UnknownDMClassException e ) {
         System.err.println( "Unrecognized domain class! " + e );
      	}
      */
    }
    
    public static void newSIns(){
    	NewEInstance newEC = new NewEInstance(MainFrame.getMainFrame(), 
    		"", 
    			"Create new System Instance",
    				ConceptType.getDefaultSystemType());
    	
    	/*
    	System.out.println("Create new system Instance ");  
    	try{
    		DMNameNew newEC = new DMNameNew(MainFrame.getMainFrame(),
				DMNameNew.NEW_SYSTEM_INSTANCE);
    	}catch( UnknownDMClassException e ) {
         System.err.println( "Unrecognized domain class! " + e );
      	}
      	
      	*/
    }
    
    public static void newUIns(){
    	NewEInstance newEC = new NewEInstance(MainFrame.getMainFrame(), 
    		"", 
    			"Create new User Instance",
    				ConceptType.getDefaultUserType());
    	
    /*	
    	System.out.println("Create new system Instance ");  
    	try{
    		DMNameNew newEC = new DMNameNew(MainFrame.getMainFrame(),
				DMNameNew.NEW_USER_INSTANCE);
    	}catch( UnknownDMClassException e ) {
         System.err.println( "Unrecognized domain class! " + e );
      	}
      */
    }
    
    public static void newIIns(){
    	NewEInstance newEC = new NewEInstance(MainFrame.getMainFrame(), 
    		"", 
    			"Create new Interface Instance",
    				ConceptType.getInterfaceType());
    	
    }
    
  	//Shijian 2001-2-12
    public static void newAIns(){
    	System.out.println("Create new action instance ");  
     	try{
    		DMNameNew newEC = new DMNameNew(MainFrame.getMainFrame(),
				DMNameNew.NEW_ACTION_INSTANCE);
    	}catch( UnknownDMClassException e ) {
         System.err.println( "Unrecognized domain class! " + e );
      	}
   }
    
  	//Shijian 2001-2-12
    public static void newERels(){
    	System.out.println("Create new entity Relation ");  
     	try{
    		DMNameNew newEC = new DMNameNew(MainFrame.getMainFrame(),
				DMNameNew.NEW_ENTITY_RELATION);
    	}catch( UnknownDMClassException e ) {
         System.err.println( "Unrecognized domain class! " + e );
      	}
   }
    
  	//Shijian 2001-2-12
    public static void newARels(){
    	System.out.println("Create new action Relation ");  
    	try{
    		DMNameNew newEC = new DMNameNew(MainFrame.getMainFrame(),
				DMNameNew.NEW_ACTION_RELATION);
    	}catch( UnknownDMClassException e ) {
         System.err.println( "Unrecognized domain class! " + e );
      	}
    }
    
  	//Shijian 2001-2-12
    public static void editDM(){
    	//System.out.println("dislay DM edit dialog ");  
		DmEdit	de= new DmEdit(MainFrame.getMainFrame(),"Edit Domain Model");	
    }
    
  	//Shijian 2001-2-12
    public static void createDMAll(){
    	//first delete all DM elements if there is any
    	clearDMAll();
    /*	
    	//create AI for semantics, precondition, and \
    	// feedback for all tasks
		createDMAllTask();
		
    	//create AI for precondition, for all links
		createDMAllLink();
		
		*/
		//System.out.println("starting parsing"); 

		ArrayList sv = new ArrayList();
		
		Manager.computeOrderedComs(sv);

		Collection v = Collections.unmodifiableCollection(sv);
		Iterator it = v.iterator();
		GenericComponent gc ;
		Task t;
		while (it.hasNext()) {
			gc= (GenericComponent)it.next();
				
			if (gc instanceof Task ) {
				t = (Task)gc;
				//System.out.println("task = "+t.getName()); 

				createDMTask(t);
			} 
			//else if (gc instanceof Link)
			//	createDMLink((Link)gc);
		}
    	
		
    }
    
  	//Shijian 2001-2-12
    public static void createDMIfNil(){

    	/*
    	createDMAllTaskIfNil();
    	createDMAllLinkIfNil();
    	return;
    	*/
    	
		ArrayList sv = new ArrayList();
		
		Manager.computeOrderedComs(sv);

		Collection v = Collections.unmodifiableCollection(sv);
		Iterator it = v.iterator();
		GenericComponent gc ;
		while (it.hasNext()) {
			gc= (GenericComponent)it.next();
				
			if (gc instanceof Task ) {
				createDMTaskIfNil((Task)gc);
				//System.out.println("task = "+gc.getName()); 

			} 
			//else if (gc instanceof Link)
			//	createDMLink((Link)gc);
		}

    	trackingInstnaces();
    }
    
  	//Shijian 2001-2-12
    public static void markDirty(){
    	markDirtySome(Manager.getAllTask());
    }
    
  	//Shijian 2001-2-14
    // ta is a collection of tasks
    public static void markDirtySome(Collection ta){
    	
		Iterator it = ta.iterator();
		Task t;
		while (it.hasNext()) {
			t= (Task)it.next();
			t.setDirty(true);	
		}
    }
    
  	//Shijian 2001-2-12
    public static void markClean(){
		markCleanSome(Manager.getAllTask());	
    }
    
  	//Shijian 2001-2-14
    // ta is acollection of tasks
    public static void markCleanSome(Collection ta){
    	//System.out.println("mark all tasks clean"); 
		
		//Iterator it = Manager.getAllTask().iterator();
		Iterator it = ta.iterator();
		Task t;
		while (it.hasNext()) {
			t= (Task)it.next();
			t.setDirty(false);	
		}
	
    }
    
  	//Shijian 2001-2-12
    public static void clearDMAll(){
    	//System.out.println("clear all domain model elements");  
    	getInstance().removeAll();
    	
    	//13-7-2001
    	//reset document style menuitem state to default
    	setStepByStepMi(STYLE_STEP_BY_STEP);
    	setHowMi(STYLE_HOW);
    	setConjunctionMi(CONJUNCTION);
    	setModalityCanMi(MODALITY_CAN);
    	setPurposeFirstMi(PURPOSE_FIRST);
    }
    
	/**
	 * printTask, print Task's name,  
	 * to the standard output
	 */
	public static void printTask(Collection ta) {
		
		Iterator it = ta.iterator();
		Task t;
		while (it.hasNext()) {
			t= (Task)it.next();
				
			System.out.println("task name: "+t.getName());
		}
	
	}//printConcept()
	
	//2001-2-13
	//remove english noun from obj store
	public EnglishNoun removeENoun(EnglishNoun en) {
		
		if (en == null) return null;
		if (en.equals((EnglishNoun)DmConcept.getDefaultEntityConcept().
			getCard(DmConcept._ENGLISH)) ||
			en.equals((EnglishNoun)DmConcept.getDefaultUserConcept().
			getCard(DmConcept._ENGLISH)) ||
			en.equals((EnglishNoun)DmConcept.getDefaultSystemConcept().
			getCard(DmConcept._ENGLISH))   ||
			en.equals((EnglishNoun)DmConcept.getInterfaceConcept().
			getCard(DmConcept._ENGLISH)) ||
			_predefinedInterfaceCards.containsValue(en)) 
			return null;
		
		String key = en.getID(); // use ID as key
		if (_englishNoun.containsKey(key)){
			_englishNoun.remove(key);
			return en;
		} else {
			return null;
		}
	
	}//removeENoun()
	
	//2001-2-13
	//remove english verb from obj store
	public EnglishVerb removeEVerb(EnglishVerb en) {
		
		if (en == null) return null;
		if (en.equals((EnglishVerb)DmConcept.getDefaultActionConcept().
			getCard(DmConcept._ENGLISH)) ) 
			return null;
		
		String key = en.getID(); // use ID as key
		if (_englishVerb.containsKey(key)){
			_englishVerb.remove(key);
			return en;
		} else {
			return null;
		}
	
	}//removeEVerb()
	
	//2001-2-13
	//remove all english verbs from obj store
	public void removeENounAll() {
		Iterator it = getEnglishNounAll().iterator();
		while (it.hasNext()) {
			removeENoun((EnglishNoun)it.next());
		}
	
	}//removeENounAll()
	
	//2001-2-13
	//remove all english verbs from obj store
	public void removeEVerbAll() {
		Iterator it = getEnglishVerbAll().iterator();
		while (it.hasNext()) {
			removeEVerb((EnglishVerb)it.next());
		}
	
	}//removeEVerbAll()
	
	//2001-2-13
	//remove all dmConcepts from obj store
	public void removeConAll() {
		Iterator it = getConceptAll().iterator();
		while (it.hasNext()) {
			removeConcept((DmConcept)it.next());
		}
	
	}//removeConAll()
	
	//2001-2-13
	//remove all EntityInstances from obj store
	public void removeEInsAll() {
		Iterator it = getEInstanceAll().iterator();
		while (it.hasNext()) {
			removeEInstance((EntityInstance)it.next());
		}
	
	}//removeEInsAll()
	
	//2001-2-13
	//remove all ActionInstances from obj store
	public void removeAInsAll() {
		
		//first remove AI reference from tasks and links
		Manager.removeTaskDomain(Manager.getAllTask());
		Manager.removeLinkDomain(Manager.getAllLink());
		
		Iterator it = getAInstanceAll().iterator();
		while (it.hasNext()) {
			removeAInstance((ActionInstance)it.next());
		}
		
	
	}//removeAInsAll()
	
	//2001-2-13
	//remove all DM elements from obj store
	// except defualt ones
	public void removeAll() {
		removeENounAll();
		removeEVerbAll();
		removeAInsAll();
		removeEInsAll();
		removeConAll();
	}//removeAll()
	
	//2001-2-14
	//find all ActionInstances which are related to
	// EntityInstance ei
	public Collection findAInsRel(EntityInstance ei) {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		
		Iterator it = getAInstanceAll().iterator();
		Iterator it2;
		ActionInstance ai;
		EntityInstance eiTemp;
		TreeMap tm;
		while (it.hasNext()) {
			ai= (ActionInstance)it.next();
			tm = ai.getActionRelations();
			it2 = tm.values().iterator();
			while (it2.hasNext()){
				eiTemp = (EntityInstance)it2.next();
				if (eiTemp != null){
					if (eiTemp.equals(ei)) {
						sv.add(ai);
						break;
					}
				}
			}
    		//System.out.println(" concepts: " + aConcept.getName()
    		//	+ "type: \"" +aConcept.getType()+ "\"");
				
		}
		
		sv.sort();

		return Collections.unmodifiableCollection(sv);

	}//findAInsRel()
	
	//find all ActionInstances which are related to
	// EntityInstance ei
	public Collection findAInsRel(Collection eiCol) {
		if (eiCol == null) return null;
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		Iterator it = eiCol.iterator();
		EntityInstance ei ;
		while (it.hasNext()) {
			ei= (EntityInstance)it.next();
			
			sv.addAll(findAInsRel(ei));
		}
		
		sv.sort(); // sort concept in alphebatical order 
					// according to "name"

		return Collections.unmodifiableCollection(sv);

	}//findAInsRel()
	
	//2001-2-14
	//find all ActionInstances which are related to
	// DmConcept(action Concept) con
	public Collection findAInsACon(DmConcept con) {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		
		Iterator it = getAInstanceAll().iterator();
		ActionInstance ai;
		while (it.hasNext()) {
			ai= (ActionInstance)it.next();
			if (ai.getConceptOf() != null)
				if (ai.getConceptOf().equals(con)) 
						sv.add(ai);
				
		}
		
		sv.sort();

		return Collections.unmodifiableCollection(sv);

		
	}//findAInsACon()
	
	//2001-2-14
	//find all EntityInstances which are related to
	// DmConcept(Entity Concept) con
	public Collection findEInsECon(DmConcept con) {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		
		Iterator it = getEInstanceAll().iterator();
		EntityInstance ei;
		while (it.hasNext()) {
			ei= (EntityInstance)it.next();
			if (ei.getConceptOf() != null)
				if ((ei.getConceptOf()).equals(con)) 
						sv.add(ei);
		}
		
		sv.sort();

		return sv; 	//Collections.unmodifiableCollection(sv);

		
	}//findEInsECon()
	
	//2001-2-14
	//find all tasks which are related to
	// ActionInstance ai
	public Collection findTaskAIns(ActionInstance ai) {
		SortArrayList sv = new SortArrayList (new GCCompare());
		
		Iterator it = Manager.getAllTask().iterator();
		Task t;
		while (it.hasNext()) {
			t= (Task)it.next();
			if (t.getSemantics() != null)
				if (t.getSemantics().equals(ai.getID())){
					sv.add(t);
					continue;
				}
			
			if (t.getPreconDM() != null)
				if (t.getPreconDM().equals(ai.getID())){
					sv.add(t);
					continue;
				}
			if (t.getFeedbackDM() != null)
				if (t.getFeedbackDM().equals(ai.getID())){
					sv.add(t);
				}
 
		}
		
		sv.sort();

		return Collections.unmodifiableCollection(sv);

		
	}//findTaskAIns()
	
	//find all task  which are related to
	// any actioninstances in col
	public Collection findTaskAICol(Collection aiCol) {
		if (aiCol == null) return null;
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		Iterator it = aiCol.iterator();
		ActionInstance ai ;
		while (it.hasNext()) {
			ai= (ActionInstance)it.next();
			
			sv.addAll(findTaskAIns(ai));
		}
		
		sv.sort(); // sort concept in alphebatical order 
					// according to "name"

		return Collections.unmodifiableCollection(sv);

	}//findAInsRel()
	
	//2001-2-14
	//find all tasks which are related to
	// EntityInstance ei and mark them dirty
	public void markTaskDirty(EntityInstance ei) {
		//first find all related ActionInstances
		Iterator it = findAInsRel(ei).iterator();
		ActionInstance aiTemp;

		//then find all related tasks
		while (it.hasNext()) {
			aiTemp= (ActionInstance)it.next();
			markTaskDirty(aiTemp);
		}
	}//markTaskDirty()
	
	//2001-2-14
	//find all tasks which are related to
	// ActionInstance ai and mark them dirty
	public void markTaskDirty(ActionInstance ai) {
		markDirtySome( findTaskAIns(ai));		
	}//markTaskDirty()
	
	//2001-2-14
	//find all tasks which are related to
	// DmConcept(action Concept) aCon and mark them dirty
	public void markTaskDirtyACon(DmConcept aCon) {
		//first find all related ActionInstances
		Iterator it = findAInsACon(aCon).iterator();
		ActionInstance aiTemp;

		//then find all related tasks
		while (it.hasNext()) {
			aiTemp= (ActionInstance)it.next();
			markTaskDirty(aiTemp);
		}
		
	}//markTaskDirtyACon()
	
	//2001-2-14
	//find all tasks which are related to
	// DmConcept(entity Concept) eCon and mark them dirty
	public void markTaskDirtyECon(DmConcept eCon) {
		//first find all related EntityInstances
		Iterator it = findEInsECon(eCon).iterator();
		EntityInstance eiTemp;

		//then find all related tasks
		while (it.hasNext()) {
			eiTemp= (EntityInstance)it.next();
			markTaskDirty(eiTemp);
		}

	}//markTaskDirtyECon()
	
	//2001-2-21
	//create a new entity instance, if no instance with
	// the same name exists, otherwise return a reference 
	// of the existing instance, if name consists more than 
	// one word, the last one will be chosen as the head
	// ei, a concept will be created from it.
	public EntityInstance makeEiIfNil(String name, String type) {
		Sentence sen = new Sentence(name);
		
		String head=sen.getLastWord();
	
		//now create the entity instance
		
		EntityInstance ei = getEInstanceByName(name);
		if ((ei != null) && 
			    ei.getConceptOf().getName().equals(head))
			return ei;
		else {
		/*	
			ei = new EntityInstance(name);
			addEInstance(ei);
			
			//create a concept of the head
			DmConcept dc ;
			if (type.equals(ConceptType.getDefaultUserType())){
				dc = getUserConcept(head);
			} else if (type.equals(ConceptType.getDefaultSystemType())){
				dc = getSystemConcept(head);
			} else {
				dc = getEConcept(head);
			}
			
			if (dc == null) {
				dc = new DmConcept(head, type);
				addEnglishN((EnglishNoun)dc.getCard(DmConcept._ENGLISH));
				addConcept(dc);
			}

			ei.setConceptOf(dc);
		*/
		
			ei=createNewEI(head,name,type);
		}
		if (sen.getWordCount() > 1) {
			String premod=sen.getAllWordsButLast();
			//if (premod != null && !(premod.equals(""))){
			ei.setPreModifier(premod);
		}
			
	    	//System.out.println(" ***********new E instance name " + name +
	    	//			" new head: "+ head+ " premodifier: " +premod);
		return ei;
	}//makeEiIfNil()
	
		
    /**
	 * getEiSome, return a sorted sub-set of read-only version of the entity
	 * instance collection. the sub-set is defined by the "type" parameter.
	 * @param type, the concept to add 
	 */
	public Collection getEiSome(String type) {
		if (type == null) return null;
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		Iterator it = getConceptSome(type).iterator();
		DmConcept aCon ;
		while (it.hasNext()) {
			aCon= (DmConcept)it.next();
    	//	System.out.println(" concepts: " + aConcept.getName()
    	//		+ "type: \"" +aConcept.getType()+ "\"");
				
			sv.addAll(findEInsECon(aCon));
		}
		
		sv.sort(); // sort concept in alphebatical order 
					// according to "name"

		return Collections.unmodifiableCollection(sv);
	}//getEiSome()
		
    /**
	 * getEiSome, return a sorted sub-set of read-only version of the entity
	 * instance collection. the sub-set is defined by the "type" parameter.
	 * @param type, the concept to add 
	 */
	public Collection getEiSome(String type,Collection col) {
		if (type == null || col == null) return null;
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		Iterator it = col.iterator();
		//DmConcept aCon ;
		EntityInstance ei;
		while (it.hasNext()) {
			ei= (EntityInstance)it.next();
			if (type.equals(ei.getConceptOf().getType()))
				sv.add(ei);
		}
		
		sv.sort(); // sort concept in alphebatical order 
					// according to "name"

		return sv; 	//Collections.unmodifiableCollection(sv);
	}//getEiSome()
	
		
    /**
	 * getEiCol, return ALL entity instance named "name" of type "type" .
	 */
	public Collection getEiCol(String name, String type) {
		if (name == null || type == null) return null;
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		Iterator it = getEiSome(type,getEInstanceAll()).iterator();
		EntityInstance ei ;
		while (it.hasNext()) {
			ei= (EntityInstance)it.next();
			if (ei.getName().equals(name))
					sv.add(ei);
		}
		
		sv.sort(); // sort concept in alphebatical order 
		return Collections.synchronizedCollection(sv);
	}//getEiCol()
	
    /**
	 * getEi, return a entity instance named "name" of type "type" .
	 */
	public EntityInstance getEi(String name, String type) {
		if (name == null || type == null) return null;
		Iterator it = getEiSome(type,getEInstanceAll()).iterator();
		EntityInstance ei ;
		while (it.hasNext()) {
			ei= (EntityInstance)it.next();
			if (ei.getName().equals(name))
				return ei;
		}
		
		return null;
	}//getEi()
	
	/**
	 * getEConcept(String st), retruns a reference to the 
	 * entity concept if there is such concept whose name is 
	 * as specified in st (case ignored). it returns null otherwise
	 */
	public DmConcept getEConcept(String st, String type) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		Collection con = getConceptSome(type);
		
		Iterator it = con.iterator();
		DmConcept concept ;

		while (it.hasNext()) {
			concept= (DmConcept)it.next();
				
			//System.out.println(concept.getName());
				
			if (temp.equals(concept.getName())) return concept;
		}
		
		return null;
	
	}//getEConcept()
    	
	
	//return a collection which only contains 1 element "obj"
	public Collection getCollection1(Object obj) {
		if (obj == null) return null;
		ArrayList sv = new ArrayList ();
		sv.add(obj);
		return Collections.synchronizedCollection(sv);
	}//getCollection1()
	
	//return a concept collection from an instnace collection
	public Collection getConFromIns(Collection col) {
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		Iterator it = col.iterator();
		EntityInstance ei;
		while (it.hasNext()) {
			ei= (EntityInstance)it.next();
			sv.add(ei.getConceptOf());
		}
		
		sv.sort(); // sort concept in alphebatical order 
					// according to "name"

		return Collections.synchronizedCollection(sv);
	}//getCollection1()
	
	public static void setConColor(Color co){
		_currentConColor = co;		
		
	}
	
	public static void setEnColor(Color co){
		_currentEnColor = co;		
		
	}
	
	public static void setActColor(Color co){
		_currentActColor = co;		
		
	}
	
	public static Color getConColor(){
		return	_currentConColor;		
		
	}
	
	public static Color getEnColor(){
		return	_currentEnColor;		
		
	}
	
	public static Color getActColor(){
		return	_currentActColor;		
		
	}
    
  	// 2001-3-23
    public static void editSemantics(Task t){
    	if (actionParser == null)
    		actionParser = new Parser(dmInstance,"action.grammar");  // for general action expressions
    	if (slider == null)
    		slider = new ParseFrame(MainFrame.getMainFrame());   
    		// the parser interface
    		
 		String title = "Edit Action Instance for Semanitcs";
	    boolean returnCode ;

	    String seman= t.getSemantics();
     	ActionInstance aiTemp;
     	
      	if (seman == null || seman.equals("")){
			seman= t.getDefaultSemantics();
			returnCode = actionParser.parse(seman);
      	}else {
      		if (dmInstance.getAInstance(seman) != null){
      			aiTemp = dmInstance.getAInstance(seman);
   		 		seman= aiTemp.getName();
   		 		
   		 		//31-10-2001
	    		if( !actionParser.parse(aiTemp)){
				  	if (seman == null || seman.equals(""))
						seman= t.getDefaultSemantics();
					
			    	returnCode = actionParser.parse(seman);
	    		}
      			
      		}
   		}	
   		
   		slider.run(actionParser, dmInstance,title, t); 	//EditionDialog.this);
	    if (slider.isOK())
			t.setSemantics(slider.getAI().getID());

   		/*
      	if (seman == null || seman.equals(""))
 		 	seman= t.getDefaultSemantics();
  		
 		//String title = "Edit Action Instance for Semanitcs";
	    returnCode = actionParser.parse(seman);
	    slider.run(actionParser, dmInstance,title, t); 	//EditionDialog.this);
	    if (slider.isOK())
			t.setSemantics(slider.getAI().getID());
		*/
    	return;
    }
    
  	// 2001-3-23
    public static void editPrecon(Task t){
    	if (actionParser == null)
    		actionParser = new Parser(dmInstance,"action.grammar");  // for general action expressions
    	if (slider == null)
    		slider = new ParseFrame(MainFrame.getMainFrame());           // the parser interface
 
     	String precon= t.getPreconDM();
     	ActionInstance aiTemp;
      	if (!(precon == null || precon.equals(""))){
      		if (dmInstance.getAInstance(precon) != null){
      			aiTemp = dmInstance.getAInstance(precon);
   		 		precon= aiTemp.getName();
      		}
   		}	
      	if (precon == null || precon.equals(""))
 		 	precon= t.getPrecon();
  		
 		String title = "Edit Action Instance for Precondition";
	    boolean returnCode = actionParser.parse(precon);
	    slider.run(actionParser, dmInstance,title,t); 	//EditionDialog.this);
	    if (slider.isOK()){
			t.setPrecon(slider.getAI().getName());
			t.setPreconDM(slider.getAI().getID());
	    }

		return;
    }
       
  	// 2001-3-23
    public static void editFeedback(Task t){
    	if (actionParser == null)
    		actionParser = new Parser(dmInstance,"action.grammar");  // for general action expressions
    	if (slider == null)
    		slider = new ParseFrame(MainFrame.getMainFrame());           // the parser interface
 
     	String feedback= t.getFeedbackDM();
     	ActionInstance aiTemp;
      	if (!(feedback == null || feedback.equals(""))){
      		if (dmInstance.getAInstance(feedback) != null){
      			aiTemp = dmInstance.getAInstance(feedback);
   		 		feedback= aiTemp.getName();
      		}
   		}	
      	if (feedback == null || feedback.equals(""))
 		 	feedback= t.getFeedback();
  		
 		String title = "Edit Action Instance for Feedback";
	    boolean returnCode = actionParser.parse(feedback);
	    slider.run(actionParser, dmInstance,title,t); 	//EditionDialog.this);
	    if (slider.isOK()){
			t.setFeedback(slider.getAI().getName());
			t.setFeedbackDM(slider.getAI().getID());
	    }
    	return;
    }
    
  	// 2001-3-23
    public static void editLinkCon(Link l){
    	if (actionParser == null)
    		actionParser = new Parser(dmInstance,"action.grammar");  // for general action expressions
    	if (slider == null)
    		slider = new ParseFrame(MainFrame.getMainFrame());           // the parser interface
 
     	String linCon= l.getPreconDM();
     	ActionInstance aiTemp;
      	if (!(linCon == null || linCon.equals(""))){
      		if (dmInstance.getAInstance(linCon) != null){
      			aiTemp = dmInstance.getAInstance(linCon);
   		 		linCon= aiTemp.getName();
      		}
   		}	
      	if (linCon == null || linCon.equals(""))
 		 	linCon= l.getPrecondition();
  		
 		String title = "Edit Action Instance for Link condition";
	    boolean returnCode = actionParser.parse(linCon);
	    slider.run(actionParser, dmInstance,title,l); 	//EditionDialog.this);
	    if (slider.isOK()){
			l.setPrecondition(slider.getAI().getName());
			l.setPreconDM(slider.getAI().getID());
	    }
    	//System.out.println("link condiction iD: " + slider.getAI().getID());		

    	return;
    }
    
  	//Shijian 2001-3-28
    public static void createDMAllTask(){
		Iterator it = Manager.getAllTask().iterator();
		boolean returnCode;
		ActionInstance ai;
		Task t;
		while (it.hasNext()) {
			t= (Task)it.next();
			
			//create AI for semantics
			returnCode = _defaultParser.parse(
						t.getDefaultSemantics().toLowerCase());
		   	ai=_defaultParser.createDM(t);
		   	if (ai != null)
		   		t.setSemantics(ai.getID());
		   	else 
		   		System.err.println("AI for semantics for TASK " +
		   			t.getName()+ " is not created!!");
		   			
		   	//create AI for preconditon
		   	String st = t.getPrecon().toLowerCase();
			Sentence sen = new Sentence(st);
		   	if (st.trim().length() >0 && sen.getWordCount() > 2 ){
				returnCode = _defaultParser.parse(st);
			   	ai=_defaultParser.createDM(t);
			   	if (ai != null)
			   		t.setPreconDM(ai.getID());
			   	else 
			   		System.err.println("AI for Precondtion for TASK " +
			   			t.getName()+ " is not created!!");
		   	}
		   			
		   	//create AI for feedback
		   	st = t.getFeedback().toLowerCase();
			sen = new Sentence(st);
		   	if (st.trim().length() >0 && sen.getWordCount() > 2 ){
	
				returnCode = _defaultParser.parse(st);
			   	ai=_defaultParser.createDM(t);
			   	if (ai != null)
			   		t.setFeedbackDM(ai.getID());
			   	else 
			   		System.err.println("AI for feedback for TASK " +
			   			t.getName()+ " is not created!!");
		   	}
		}
    }
    
  	//Shijian 2001-3-28
    public static void createDMAllLink(){
    	Iterator it = Manager.getAllLink().iterator();
		Link l;
		String precon;
		while (it.hasNext()) {
			l= (Link)it.next();
			precon= l.getPrecondition().toLowerCase();
			Sentence sen = new Sentence(precon);
			if (precon != null ){
				if (precon.trim().length() >0 && sen.getWordCount() > 2 ){
					boolean returnCode = _defaultParser.parse(
						l.getPrecondition());
				   	ActionInstance ai=_defaultParser.createDM(l);
				   	if (ai != null)
				   		l.setPreconDM(ai.getID());
				   	else 
				   		System.err.println("Ai for link precondition " +
				   			l.getName()+ " is not created!!");
				}
			}
		}
    }
    
  	//Shijian 2001-3-28
    public static void createDMAllTaskIfNil(){
		Iterator it = Manager.getAllTask().iterator();
		String seman, precon,preconID, feedback,feedbackID;
		boolean returnCode;
		ActionInstance ai;
		Task t;
		while (it.hasNext()) {
			t= (Task)it.next();
			
			//create AI for semantics
			seman= t.semantics;
			if (seman == null || seman.equals("")){
				seman =t.getDefaultSemantics().toLowerCase();

				returnCode = _defaultParser.parse(seman);
			   	ai=_defaultParser.createDM(t);
			   	if (ai != null)
			   		t.setSemantics(ai.getID());
			   	else 
			   		System.err.println("AI for semantics for TASK " +
		   				t.getName()+ " is not created!!");
			}
		   			
		   	//create AI for preconditon
			precon= t.getPrecon().toLowerCase();
			Sentence sen = new Sentence(precon);

			preconID= t.getPreconDM();
			if (precon != null && sen.getWordCount() > 2 ){
				if (precon.trim().length() >0 && 
					(preconID == null || preconID.equals(""))){
					returnCode = _defaultParser.parse(precon);
				   	ai=_defaultParser.createDM(t);
				   	if (ai != null)
				   		t.setPreconDM(ai.getID());
				   	else 
				   		System.err.println("AI for Precondtion for TASK " +
				   			t.getName()+ " is not created!!");
						
				}
			} else{
				t.setPreconDM("");				
			}
		   			
		   	//create AI for feedback
			feedback= t.getFeedback().toLowerCase();
			sen = new Sentence(feedback);
			feedbackID= t.getFeedbackDM();
			if (feedback != null  && sen.getWordCount() > 2 ){
				if (feedback.trim().length() >0 && 
					(feedbackID == null || feedbackID.equals(""))){
					returnCode = _defaultParser.parse(feedback);
				   	ai=_defaultParser.createDM(t);
				   	if (ai != null)
				   		t.setFeedbackDM(ai.getID());
				   	else 
				   		System.err.println("AI for feedback for TASK " +
				   			t.getName()+ " is not created!!");
				}
			} else{
				t.setFeedbackDM("");
			}
		}
    }
    
  	//Shijian 2001-3-28
    public static void createDMAllLinkIfNil(){
    	Iterator it = Manager.getAllLink().iterator();
		Link l;
		String precon, preconID;
		boolean returnCode;
		ActionInstance ai;
		while (it.hasNext()) {
			l= (Link)it.next();
			precon= l.getPrecondition().toLowerCase();
			Sentence sen = new Sentence(precon);

			preconID= l.getPreconDM();
			if (precon != null  && sen.getWordCount() > 2 ){
				if (precon.trim().length() >0 && 
					(preconID == null || preconID.equals(""))){
					returnCode = _defaultParser.parse(precon);
				   	ai=_defaultParser.createDM(l);
				   	if (ai != null)
				   		l.setPreconDM(ai.getID());
				   	else 
				   		System.err.println("Ai for link precondition " +
				   			l.getName()+ " is not created!!");
				}
			}else{
				l.setPreconDM("");
			}
		}
    }
	
	//2001-4-20
	//find all tasks which are related to
	// ActionInstance ai
	public Collection findLinksAIns(ActionInstance ai) {
		SortArrayList sv = new SortArrayList (new GCCompare());
		
		Iterator it = Manager.getAllLink().iterator();
		Link l;
		while (it.hasNext()) {
			l= (Link)it.next();
			if (l.getPreconDM() != null)
				if (l.getPreconDM().equals(ai.getID()) ) 
					sv.add(l);
				
		}
		
		sv.sort();

		return Collections.synchronizedCollection(sv);

		
	}//findTaskAIns()
	
	//find all tasks and Links  which are related to
	// any actioninstances in col
	public Collection findComAICol(Collection aiCol) {
		if (aiCol == null) return null;
		SortArrayList sv = new SortArrayList (new GCCompare());

		Iterator it = aiCol.iterator();
		ActionInstance ai ;
		while (it.hasNext()) {
			ai= (ActionInstance)it.next();
			
			sv.addAll(findTaskAIns(ai));
			sv.addAll(findLinksAIns(ai));

		}
		
		sv.sort(); // sort concept in alphebatical order 
					// according to "name"

		return Collections.synchronizedCollection(sv);

	}//findAInsRel()
  
  public EntityInstance createNewEI(String ConName, String InstanceName,String type ){
		
		// First, make sure a concept exists for the head.
		DmConcept dc = getEConcept(ConName, type);
		
		// check to see if there a interface concept
		if (dc == null && type.equals(ConceptType.getDefaultEntityType())){
			dc = getEConcept(ConName, ConceptType.getInterfaceType());
			if (dc != null){
				InterfaceInstance ei = new InterfaceInstance(InstanceName);
				ei.setConceptOf(dc);
				addEInstance(ei);

				return ei;
			}
			
		}

		if (dc == null) {
			dc = new DmConcept(ConName, type); //"entity type");
		 
		  	//add language card to DmManager collection
		  	addEnglishN((EnglishNoun)dc.
		  		getCard(DmConcept._ENGLISH));
		  
		  	dc.setParent(DmConcept.getDefaultEntityConcept());
		  	addConcept(dc);
		}	

		// Next, make the instance and connect it to the appropriate concept.
		
		EntityInstance ei;
		if (type.equals(ConceptType.getInterfaceType()))
			ei = new InterfaceInstance(InstanceName);
		else 
			ei = new EntityInstance(InstanceName);

		ei.setConceptOf(dc);
		addEInstance(ei);

		return ei;
		
  	
  }
  
  //2001-5-1
  // first check if entity-instance exists, if yes, then check whether it
  // is related to gc, if yes return that entity-instance, otherwise,
  //create a new entity-instance
  public EntityInstance getRelatedEInstance(GenericComponent gc,
  				String eInstName, String conName, String pro,
  					String post, String type){
  /*	
	EntityInstance ei =getEi(eInstName,type);
	//if ei is related to any task which happens to be 
	//either a predecessor or a successor of _gc, or ei is either 
	//default system or user instance, then return
	// ei
	if (ei != null) {
		Collection componentCol=findComAICol(findAInsRel(ei));
		if (ei.equals(EntityInstance.getDefaultUserInstance())||
			ei.equals(EntityInstance.getDefaultSystemInstance()) ||
				Manager.isRelated(gc, componentCol)){
			System.out.println( ei.getName() + "  is related to " +
				gc.getName());
			return ei;
		} else {
			System.out.println( ei.getName() + "  is NOT related"+gc.getName() );

		}
	}
	
*/
	EntityInstance ei = getRelatedEInstance1(gc, eInstName,type);
	if ( ei!= null) return ei; 
	
	// if either ei does not exist or ei is not related
	// create a new instance
	ei=createNewEI(conName,eInstName,type);
	
	// Finally, add pre/post modifiers if necessary.
	if (pro!= null)
		//if it is an InterfaceInstance set premodifier as 
		// label by default
		if (ei instanceof InterfaceInstance)
			((InterfaceInstance)ei).setLabel(pro);
		else ei.setPreModifier(pro);

	if (post != null)
	  	ei.setPostModifier(post);
	  	
	addEInstance(ei);
	return ei;
  	
  }
  
  //2001-7-16
  // first check if there are entity instances with name "sInstName", 
  // if yes, then check whether any of them 
  // is related to gc, if yes return that entity-instance, return null
  // if none is related to gc
  public EntityInstance getRelatedEInstance1(GenericComponent gc,
  				String eInstName, String type){
  	
	Collection eiCol =getEiCol(eInstName,type);
	
	if (eiCol == null) return null;
	else {
		Iterator it = eiCol.iterator();
		EntityInstance ei;
		Collection componentCol;
		while (it.hasNext()) {
			ei= (EntityInstance)it.next();
			componentCol=findComAICol(findAInsRel(ei));
			//if ei is related to any task which happens to be 
			//either a predecessor or a successor of _gc, or ei is either 
			//default system or user instance, then return ei
			if (ei.equals(EntityInstance.getDefaultUserInstance())||
				ei.equals(EntityInstance.getDefaultSystemInstance())||
					Manager.isRelated(gc, componentCol)){
				return ei;
			}
		}
		
		
	}
	
	return null;
  	
  }
  
    //2001-5-23
  // If (instance)"name" does not contain concept-name
  // 	return null
  // Else if there is a longest concept-name
  //	return the longest concept-name
  // if there are 2 or more longest,
  //	return the one appears last
  public DmConcept getHead(String instanceName){
  	String name = instanceName.toLowerCase();
  	int newFrom,from = -1;
  	int newLen,length = -1;
  	DmConcept head =null;
  	String conName;
  	
	Collection v = getEConceptAll();
	Iterator it = v.iterator();
	DmConcept aConcept ;
	while (it.hasNext()) {
		aConcept= (DmConcept)it.next();
		//System.out.println(" concepts: " + aConcept.getName()
		//	+ "type: \"" +aConcept.getType()+ "\"");
  		conName =aConcept.getName();
  		
		if (name.lastIndexOf(conName) != -1) {
			newLen = conName.length();
			newFrom = name.lastIndexOf(conName);
			if ((length <newLen) ||
				((length == newLen)&& (newFrom > from)) ){
					
				length = newLen;
				from = newFrom;
				
				head = aConcept;
			}
		}
	}
	
	return head;
	
	
  }
  
	
  //2001-6-18
  //add predefined interface concepts:
  // button, dialog, menu, menu item
  private void addInterfaceConcepts(){
    String interfaceConcepts[] = {"button",
				  "dialog box", "menu","menu item", 
				  //"console", "dial",
				  "confirmation dialog box",
				  "information dialog box",
				  "toolbar",
				  "icon",
				  "box"
    };
    
    DmConcept dc1;
    EnglishNoun en; 
    for (int i = 0; i < interfaceConcepts.length; i++){
			dc1= new DmConcept(interfaceConcepts[i]);
			
			//16-1-2002
			//remove interface sub-type from concepts
	    //if (interfaceConcepts[i].endsWith("box"))
	   	//	dc1.setType(ConceptType.getD3InterfaceType());
	    //else
	   		dc1.setType(ConceptType.getInterfaceType());
	    dc1.setID(getIdPrefix()+dc1.getID());
	
	    _predefinedInterfaceConcepts.put(dc1.getID(),dc1);
	    conceptAll.put(dc1.getID(),dc1);
		  		
	    en = (EnglishNoun)dc1.getCard(DmConcept._ENGLISH);
	    en.setID(getIdPrefix()+en.getID());
	
	    addEnglishN(en);	
	    _predefinedInterfaceCards.put(en.getID(), en);
      
 //19-10-2001
/*			
      if (en.getName().equals("menuitem"))
	en.setSpelling("menu item");
      if (en.getName().equals("dialog"))
	en.setSpelling("dialog box");
*/ 

    }
    return;

  }
  	
  	public String getIdPrefix(){
  		return _idPrefix	;
  	}
  	
  	/**
  	* check if the help document style is step-by-step
  	*/
  	public boolean isStepByStep(){
  		return _stepByStep	;
  	}
  
  	/**
  	* set help document style step-by-step value to b
  	*/
  	public void setStepByStep(boolean b){
  		_stepByStep = b;
  		return 	;
  	}
    	
  	/**
  	* check if the help document style is step-by-step
  	*/
  	public boolean isStyleHow(){
  		return _how	;
  	}
  
  	/**
  	* set help document style step-by-step value to b
  	*/
  	public void setStyleHow(boolean b){
  		_how = b;
  		return 	;
  	}
  
  	/**
  	* set help document style step-by-step menuItem state
  	*/
  	public static void setHowMi(boolean b){
	//	MainMenu.getHowMi().setSelected(b);
  		return 	;
  	}
  
  
  	/**
  	* set help document style step-by-step menuItem state
  	*/
  	public static void setStepByStepMi(boolean b){
//		MainMenu.getStepByStepMi().setSelected(b);
  		return 	;
  	}
  	
  	/**
  	* set help document style step-by-step menuItem state
  	*/
  	public static void setConjunctionMi(boolean b){
	//	MainMenu.getConjunctionMi().setSelected(b);
  		return 	;
  	}
  	
  
  	/**
  	* set help document style step-by-step menuItem state
  	*/
  	public static void setModalityCanMi(boolean b){
	//	MainMenu.getModalityCanMi().setSelected(b);
  		return 	;
  	}
  
  
  	/**
  	* set help document style step-by-step menuItem state
  	*/
  	public static void setPurposeFirstMi(boolean b){
	//	MainMenu.getPurposeFirstMi().setSelected(b);
  		return 	;
  	}
  	
  	/**
  	* check if the help document style is modality-can
  	*/
  	public boolean isModalityCan(){
  		return _modalityCan	;
  	}
  
  	/**
  	* set help document style modality-can value to b
  	*/
  	public void setModalityCan(boolean b){
  		_modalityCan = b;
  		return 	;
  	}
  	
  	/**
  	* check if the help document style is purpose-first
  	*/
  	public boolean isPurposeFirst(){
  		return _purposeFirst	;
  	}
  
  	/**
  	* set help document style _purposeFirst value to b
  	*/
  	public void setPurposeFirst(boolean b){
  		_purposeFirst = b;
  		return 	;
  	}
    	

  	
  	/**
  	* check if the help document style is conjuction
  	*/
  	public boolean isConjunction(){
  		return _conjunction	;
  	}
  
  	/**
  	* set help document style Conjunction value to b
  	*/
  	public void setConjunction(boolean b){
  		_conjunction = b;
  		return 	;
  	}
    	


  	//2001-7-16
  	public static void createDMTaskIfNil(Task t){

		//create AI for semantics
  		String precon,preconID,feedback,feedbackID;
		String seman= t.semantics;
		boolean returnCode;
		ActionInstance ai;
		if (seman == null || seman.equals("")){
			seman =t.getDefaultSemantics().toLowerCase();

			returnCode = _defaultParser.parse(seman);
		   	ai=_defaultParser.createDM(t);
		   	if (ai != null)
		   		t.setSemantics(ai.getID());
		   	else 
		   		System.err.println("AI for semantics for TASK " +
	   				t.getName()+ " is not created!!");
		}
	   			

	   	//create AI for preconditon
		precon= t.getPrecon().toLowerCase();
		Sentence sen = new Sentence(precon);

		preconID= t.getPreconDM();
		if (precon != null && sen.getWordCount() > 2 ){

			if (precon.trim().length() >0 && 
				(preconID == null || preconID.equals(""))){
				returnCode = _defaultParser.parse(precon);
			   	ai=_defaultParser.createDM(t);
			   	if (ai != null)
			   		t.setPreconDM(ai.getID());
			   	else 
			   		System.err.println("AI for Precondtion for TASK " +
			   			t.getName()+ " is not created!!");
					
			}
		} else{
			t.setPreconDM("");				
		}
	   			
	   	//create AI for feedback
		feedback= t.getFeedback().toLowerCase();
		sen = new Sentence(feedback);
		feedbackID= t.getFeedbackDM();
		if (feedback != null  && sen.getWordCount() > 2 ){
			if (feedback.trim().length() >0 && 
				(feedbackID == null || feedbackID.equals(""))){
				returnCode = _defaultParser.parse(feedback);
			   	ai=_defaultParser.createDM(t);
			   	if (ai != null)
			   		t.setFeedbackDM(ai.getID());
			   	else 
			   		System.err.println("AI for feedback for TASK " +
			   			t.getName()+ " is not created!!");
			}
		} else{
			t.setFeedbackDM("");
		}
  	}
  	
  	//Shijian 2001-7-16
    public static void createDMTask(Task t){
		boolean returnCode;
		ActionInstance ai;
			
		//create AI for semantics
		returnCode = _defaultParser.parse(
					t.getDefaultSemantics().toLowerCase());
	   	ai=_defaultParser.createDM(t);
	   	if (ai != null)
	   		t.setSemantics(ai.getID());
	   	else 
	   		System.err.println("AI for semantics for TASK " +
	   			t.getName()+ " is not created!!");
	   			
	   	//create AI for preconditon
	   	String st = t.getPrecon().toLowerCase();
		Sentence sen = new Sentence(st);
	   	if (st.trim().length() >0 && sen.getWordCount() > 2 ){
			returnCode = _defaultParser.parse(st);
		   	ai=_defaultParser.createDM(t);
		   	if (ai != null)
		   		t.setPreconDM(ai.getID());
		   	else 
		   		System.err.println("AI for Precondtion for TASK " +
		   			t.getName()+ " is not created!!");
	   	}
	   			
	   	//create AI for feedback
	   	st = t.getFeedback().toLowerCase();
		sen = new Sentence(st);
	   	if (st.trim().length() >0 && sen.getWordCount() > 2 ){

			returnCode = _defaultParser.parse(st);
		   	ai=_defaultParser.createDM(t);
		   	if (ai != null)
		   		t.setFeedbackDM(ai.getID());
		   	else 
		   		System.err.println("AI for feedback for TASK " +
		   			t.getName()+ " is not created!!");
	   	}
    }
  
  //2001-8-2
  // first check if there are action instances with name "aName", 
  // if yes, then check whether any of them 
  // is related to gc, if yes return that action-instance, return null
  // if none is related to gc
  public ActionInstance getRelatedAI(GenericComponent gc,
  				String aName){
  	
	Collection aiCol =getAiCol(aName);
	
	if (aiCol == null) return null;
	else {
		Iterator it = aiCol.iterator();
		ActionInstance ai;
		Collection componentCol;
		while (it.hasNext()) {
			ai= (ActionInstance)it.next();
			TreeSet col = new TreeSet();
			col.add(ai);
			componentCol=findComAICol(col);
			//if ai is related to any task which happens to be 
			//either a predecessor or a successor of _gc, then return ai
			if (Manager.isRelated(gc, componentCol)){
				return ai;
			}
		}
		
		
	}
	
	return null;
  	
  }
	
  	//2001-8-2
    /**
	 * getEiCol, return ALL action instances named "name" .
	 */
	public Collection getAiCol(String name) {
		if (name == null ) return null;
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		Iterator it = getAInstanceAll().iterator();
		ActionInstance ai ;
		while (it.hasNext()) {
			ai= (ActionInstance)it.next();
			if (ai.getName().equals(name))
					sv.add(ai);
		}
		
		sv.sort(); // sort concept in alphebatical order 
		return Collections.synchronizedCollection(sv);
	}//getAiCol()
	
	//2001-8-15
	public Collection getActionCons() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		
		String d3types[] = ConceptType.getDefinedActionTypes();
		for (int i = 0; i < d3types.length; i++) {
    		sv.addAll(getConceptSome(d3types[i]));				
       	}   
		sv.sort();

		return Collections.synchronizedCollection(sv);
	}
	
	//2001-8-15
	public Collection getObjectCons() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		
		String d3types[] = ConceptType.getDefinedObjectTypes();
		for (int i = 0; i < d3types.length; i++) {
    		sv.addAll(getConceptSome(d3types[i]));				
       	}   
		sv.sort();

		return Collections.synchronizedCollection(sv);
	}
	
	//2001-8-16
	public Collection getObjectIns() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		
		String d3types[] = ConceptType.getDefinedObjectTypes();
		for (int i = 0; i < d3types.length; i++) {
    		sv.addAll(getEiSome(d3types[i], getEInstanceAll()));				
       	}   
		sv.sort();

		return Collections.synchronizedCollection(sv);
	}
	/*
	//2001-8-17
	public Collection getObjectCons() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		
		Iterator it = getObjectIns().iterator();
		EntityInstance ei ;
		while (it.hasNext()) {
			ei= (EntityInstance)it.next();
			sv.add(ei.getConceptOf());
		}
		
		Iterator it2 = getObjectCons1().iterator();
		DmConcept con ;
		while (it2.hasNext()) {
			con= (DmConcept)it2.next();
			if ( !(sv.contains(con)))
				sv.add(con);
		}
		sv.sort();

		return Collections.synchronizedCollection(sv);
	}
	*/
	//2001-8-21
	public DmConcept getConcept(String st, String type) {
		
		String temp = st.toLowerCase().trim(); //turn to loser case and get-rid-off 
															//leading and trailling spaces
		Collection con = getConceptSome(type);
		
		Iterator it = con.iterator();
		DmConcept concept ;

		while (it.hasNext()) {
			concept= (DmConcept)it.next();
				
			//System.out.println(concept.getName());
				
			if (temp.equals(concept.getName())) return concept;
		}
		
		return null;
	
	}//getEConcept()
    
  	//Shijian 2001-10-2    
	public static void setDocStyle(){
    	StyleDialog test = new StyleDialog(MainFrame.getMainFrame(),
    		"Set Document Style");
    	
    }
    
	
	//2001-10-18
	public Collection getInterfaceCons() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		
		String d3types[] = ConceptType.getDefinedInterfaceTypes();
		for (int i = 0; i < d3types.length; i++) {
    		sv.addAll(getConceptSome(d3types[i]));				
       	}   
		sv.sort();

		return Collections.synchronizedCollection(sv);
	}
	
	//2001-10-18
	public Collection getInterfaceIns() {
		SortArrayList sv = new SortArrayList (new DmClassCompare());
		
		String d3types[] = ConceptType.getDefinedInterfaceTypes();
		for (int i = 0; i < d3types.length; i++) {
    		sv.addAll(getEiSome(d3types[i], getEInstanceAll()));				
       	}   
		sv.sort();

		return Collections.synchronizedCollection(sv);
	}
	
	//19-10-2001
		
    /**
	 * getEiSome, return a sorted sub-set of read-only version of the entity
	 * instance collection. the sub-set is defined by the "type" parameter.
	 * @param type, the concept to add 
	 */
	public Collection getEiSome(String type[],Collection col) {
		if (type.length == 0 || col == null) return null;
		
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		for (int i = 0; i < type.length; i++) {
			sv.addAll(getEiSome(type[i],col));
       	}   
       	
       	sv.sort(); // sort instances in alphebatical order 
					// according to "name"
		return Collections.unmodifiableCollection(sv);


	}//getEiSome()
	
	//30-10-2001
    /**
	 * delete action instance and all related entity-instances
	 * which are not related to other action-instances
	 */
	public void removeAiAndEi(ActionInstance ai) {
		if (ai == null) return;
		
		Collection eiCol = ai.getRelIns();
		//delete ai
		removeAInstance(ai);
		//remove related entity instances
		EntityInstance eiTemp;
		Collection aiCol;
		Iterator it = eiCol.iterator();
		while (it.hasNext()){
			eiTemp = (EntityInstance)it.next();
			aiCol = findAInsRel(eiTemp);
			if (aiCol != null && aiCol.size() >= 1);
			else removeEInstance(eiTemp);
				
		}
		

	}//removeAiAndEi()
	
	//31-10-2001
    /**
	 * delete ALL action and entity instances 
	 */
	public void clearDMAllIns() {
		removeAInsAll();
		removeEInsAll();
	}//removeAiAndEi()
	
    /**
	 * delete ALL un-referenced action and entity instances 
	 */
	public void clearDMAllUnIns() {
		clearDMAllUnActIns();	
		clearDMAllUnEnIns();
	}//clearDMAllUnIns()
	
    /**
	 * delete ALL unreferenced action instances 
	 */
	public void clearDMAllUnActIns() {
		ActionInstance ai;
		ArrayList taskColTemp= new ArrayList();
		Collection taskCol;
		ArrayList actDiscard = new ArrayList();
		
		Iterator it = aInstanceAll.values().iterator();
		while (it.hasNext()){
			ai = (ActionInstance)it.next();
		 	taskCol = findTaskAIns(ai);
		 	if (taskCol != null && taskCol.size() >= 1)
		 		taskColTemp.add(ai);		//do nothing if refereced by tasks
		 	else 
				actDiscard.add(ai);
		}
		
		//2002-1-21
		//get all act-act ai
		TreeMap acActAi = new TreeMap();
	for (int i = 0; i<taskColTemp.size(); i++){
		ai =(ActionInstance)taskColTemp.get(i);
	 	acActAi.putAll(ai.getActionActRelations());
	}

		//now deleting
		for (int i = 0; i<actDiscard.size(); i++){
			ai =(ActionInstance)actDiscard.get(i);
			if (!(acActAi.containsValue(ai))) //if ai is not an act-act relation
				removeAInstance((ActionInstance)actDiscard.get(i));
				
		}
	
	}//clearDMAllUnActIns()
	
    /**
	 * delete ALL unreferenced entity instances 
	 * modify on June 5, to keep entity-instances referred by an relevant
	 * EI
	 */
	public void clearDMAllUnEnIns() {
		EntityInstance ei,ei2;
		Collection actCol;
		ArrayList eiRetain = new ArrayList();
	ArrayList eiDiscard = new ArrayList();

	//System.out.println("comes to clearDMAllUnEnIns"); 

		Iterator it = eInstanceAll.values().iterator();
		
		//first find EI instances referred by an action instance
		while (it.hasNext()){
		ei = (EntityInstance)it.next();
		actCol = findAInsRel(ei);
		if (actCol != null && actCol.size() >= 1)//add to eiRetain if refereced by tasks
		{
			eiRetain.add(ei);
			//now add all EIs related to ei
			eiRetain.addAll(findEInsRel(ei));

		}
		else 
			eiDiscard.add(ei);
	}
	
	//now  remove all EIs from eiDiscard if 
	//it presents in eiRetain 
	Iterator it2 = eiRetain.iterator();
	while (it2.hasNext()){
		ei2 = (EntityInstance)it2.next();
		//System.out.println("should retain: name = "+ei2.getName()); 

		if (eiDiscard.contains(ei2) )
			eiDiscard.remove(ei2);
	}
	
	//now deleting
	for (int i = 0; i<eiDiscard.size(); i++)
		removeEInstance((EntityInstance)eiDiscard.get(i));
	
   }//clearDMAllUnActIns()
	
    
//2002-1-21
//tracking instances
public static void trackingInstnaces(){
//System.out.println("starting parsing"); 

	ArrayList sv = new ArrayList();
	
	Manager.computeOrderedComs(sv);
	
	Collection v = Collections.unmodifiableCollection(sv);
	Iterator it = v.iterator();
	GenericComponent gc ;
	Task t;
	while (it.hasNext()) {
		gc= (GenericComponent)it.next();
			
		if (gc instanceof Task ) {
			t = (Task)gc;
			//System.out.println("task = "+t.getName()); 
	
			trackDM(t);
		} 
	}
	
	//clear unrefered instances
	dmInstance.clearDMAllUnIns();
	
}

    
	// 2002-1-21
public static void trackDM(Task t){
	String precon,preconID,feedback,feedbackID;
	ActionInstance ai = getAI(t);
	if (ai == null) return;
	
   DmRelation actionRelation = DmRelation.getInstance();
	EntityInstance ei,eiRel;
	String type;
   // get all action-entity relations
   TreeMap ae = ai.getActionRelations();
	String aRaltion[] = actionRelation.getAllActionRelations();
		for (int i = 0; i< aRaltion.length; i++){
			if (ae.get(aRaltion[i]) != null){
				ei = (EntityInstance)ae.get(aRaltion[i]);
				type = ei.getConceptOf().getType();
				eiRel = getRelatedEi(t,ei.getName(), type);
				//if ei of the same name and type exists in the 
				//task's predecessor, then refer to that entity instance
				if (eiRel != null) 
					ai.setActionRelation(aRaltion[i], eiRel);
			
			}
		}
 }
    
    
	// 2002-1-21
public static ActionInstance getAI(Task t){
	String seman= t.semantics;
	ActionInstance ai = null;
	EntityInstance ei,eiRel;
	String type;
	if (!(seman == null || seman.equals("")))
		ai=dmInstance.getAInstance(seman);
		
	if (ai != null) return ai;
	
	return null;	
}
    
    
	// 2002-1-21
public static EntityInstance getRelatedEi(Task t, String name, String type){
	Task temp;
	ActionInstance ai;
	EntityInstance ei,eiRel;
	GenericComponent gc;
	
	Collection taskPreCol = getAllPredecessors(t);
	Iterator it = taskPreCol.iterator();
	while (it.hasNext()) {
		gc = (GenericComponent)it.next();
		if (gc instanceof Task){
			temp= (Task)gc;
			ai = getAI(temp);
			if (ai != null) {
				return getRelatedEi(ai, name, type);
			}
		}
	}
	return null;

	
}

// 2002-1-21
public static Collection getPredecessorAi(Task t){
	SortArrayList sv = new SortArrayList (new DmClassCompare());

	Task temp;
	ActionInstance ai;
	EntityInstance ei,eiRel;
	GenericComponent gc;
	
	Collection taskPreCol = getAllPredecessors(t);
	Iterator it = taskPreCol.iterator();
	while (it.hasNext()) {
		gc = (GenericComponent)it.next();
		if (gc instanceof Task){
			temp= (Task)gc;
			ai = getAI(temp);
			if (ai != null) {
				sv.add(ai);
				//add act-act ais
				sv.add(ai.getActionActRelations().values());
			}
		}
	}
   sv.sort(); 
   return Collections.unmodifiableCollection(sv);
	
}
	// 2002-1-21
//if any instances in the ai relations have the same name as "name" and its
//concept-type as type, then that entity instance will be returned, otherwise
// null will be returned
public static EntityInstance getRelatedEi(ActionInstance ai, String name, String type){
   DmRelation actionRelation = DmRelation.getInstance();
	EntityInstance ei;
	String typeRel;
   // get all action-entity relations
   TreeMap ae = ai.getActionRelations();
	String aRaltion[] = actionRelation.getAllActionRelations();
	for (int i = 0; i< aRaltion.length; i++){
		if (ae.get(aRaltion[i]) != null){
			ei = (EntityInstance)ae.get(aRaltion[i]);
			typeRel = ei.getConceptOf().getType();
			if (ei.getName().equals(name) && typeRel.equals(type)) 
				return ei;
		
		}
	}
	
	return null;

	
}
    
    
	// 2002-1-21
 public static Collection getAllPredecessors(Task t){
 	Manager.resetPredecessorStore();
 	Manager.findPrecComs(t);
 	return Manager.getAllPredecessors();
 }
 
	//2002-6-5
//find all EntityInstances which are related to
// EntityInstance ei
public Collection findEInsRel(EntityInstance ei) {
	SortArrayList sv = new SortArrayList (new DmClassCompare());
	
	Iterator it2;
	EntityInstance eiTemp;
	TreeMap tm;
	
	tm = ei.getEntityRelations();
	it2 = tm.values().iterator();
	while (it2.hasNext()){
		eiTemp = (EntityInstance)it2.next();
		if (eiTemp != null && !(sv.contains(eiTemp))){
			sv.add(eiTemp);
			//go a level down 
			sv.addAll(findEInsRel(eiTemp));
		}
		
	}
 		//System.out.println(" concepts: " + aConcept.getName()
 		//	+ "type: \"" +aConcept.getType()+ "\"");
			
	
	sv.sort();

	return Collections.unmodifiableCollection(sv);

}//findAInsRel()

//return defualt parser
//shijian  6-6-2002
public Parser getParser() {
    return _defaultParser;
}  

  	/**
	 * @return void
	* test the class.
	*/
	public static void main(String args[]) {
    	
		// get DmManager instance
		DmManager dmm= DmManager.getInstance();
		
		DmConcept dc1= new DmConcept("menu");
		dc1.setType("entity type");
		DmConcept dc2= new DmConcept("menuitem");
		dc2.setType("entity type");
		
		// add concept to dmManager
		dmm.addConcept(dc1);
		dmm.addConcept(dc2);

		EntityInstance ei1= new EntityInstance ("file");
		ei1.setConceptOf(dc1);	
		
		EntityInstance ei2= new EntityInstance ("new");
		ei2.setConceptOf(dc2);
		ei2.setEntityRelation("part of",ei1);
		
		EntityInstance ei3= new EntityInstance ("open");
		ei3.setConceptOf(dc2);
		ei3.setEntityRelation("part of",ei1);
		
		EntityInstance ei4= new EntityInstance ("save");
		ei4.setConceptOf(dc2);
		ei4.setEntityRelation("part of",ei1);
		
		EntityInstance ei5= new EntityInstance ("somthing");
		EntityInstance ei6= new EntityInstance ("new thing");
		ei6.setConceptOf(dc1);
		
		// add instnaces to dmManager
		dmm.addEInstance(ei1);
		dmm.addEInstance(ei2);
		dmm.addEInstance(ei3);
		dmm.addEInstance(ei4);
		dmm.addEInstance(ei5);
		
		System.out.println("DmConcept: " + DmConcept.getDefaultEntityConcept().getName()+ " of type "+ dc1.getType()+" has the following instance:");
		DmInstance dc5In[]= DmConcept.getDefaultEntityConcept().getAllInstances();
		for (int i = 0; i < dc5In.length; i++) {
    		System.out.println("     "+i+"Instance: " + dc5In[i].getName() + " " + dc5In[i].getConceptOf().getName());				
       	}  
			
			
		System.out.println("DmConcept: " + dc1.getName()+ " of type "+ dc1.getType()+" has the following instance:");
		DmInstance dc1In[]= dc1.getAllInstances();
		for (int i = 0; i < dc1In.length; i++) {
    		System.out.println("     "+i+"Instance: " + dc1In[i].getName());				
       	}  
			
		System.out.println("DmConcept: " + dc2.getName()+ " of type "+ dc2.getType()+" has the following instance:");
		DmInstance dc2In[]= dc2.getAllInstances();
		for (int i = 0; i < dc2In.length; i++) {
    		System.out.println("     "+i+"Instance: " + dc2In[i].getName()+ " " + dc2In[i].getConceptOf().getName());
    		DmRelation relM = DmRelation.getInstance();

    		String allEnRle[] = relM.getAllEntityRelations();
			TreeMap reInstances = ((EntityInstance)dc2In[i]).getEntityRelations();    
			for (int j = 0; j < allEnRle.length; j++) {
    			System.out.println("     "+allEnRle[j]+" Instance: " 
    			+((DmInstance) reInstances.get(allEnRle[j])).getName());				
       		}  

       	}  
		
		System.out.println("entity insteance: " + ei3.getName() + " of concept " + ei3.getConceptOf().getName()+ " has relations: ");
		TreeMap relationInstances = ei3.getEntityRelations();
		DmRelation relM = DmRelation.getInstance();
		String allEnRle[] = relM.getAllEntityRelations();
		for (int i = 0; i < allEnRle.length; i++) {
    		System.out.println("     "+allEnRle[i]+" Instance: " 
    			+((DmInstance) relationInstances.get(allEnRle[i])).getName());				
       	}  
       	
       	// test dm-action related stuff
       	
		DmConcept user1= new DmConcept("user");
		user1.setType("user type");
		DmConcept select1= new DmConcept("select");
		select1.setType("action type");

		EntityInstance editor= new EntityInstance ("editor");
		editor.setConceptOf(user1);	
		
		
		// add concept to dmManager
		dmm.addConcept(user1);
		dmm.addConcept(select1);
		// add instnaces to dmManager
		dmm.addEInstance(editor);
		
		ActionInstance editorSelect1= new ActionInstance ("user select new from file menu");
		editorSelect1.setConceptOf(select1);	
		editorSelect1.setActionRelation("actor", editor);
		editorSelect1.setActionRelation("actee", ei2);
		editorSelect1.setActionRelation("source", ei1);

		ActionInstance editorSelect2= new ActionInstance ("user select save from file menu");
		//select1.addInstance(editorSelect2);	
		editorSelect2.setConceptOf(select1);	
		editorSelect2.setActionRelation("actor", editor);
		editorSelect2.setActionRelation("actee", ei4);
		editorSelect2.setActionRelation("source", ei1);
		
		ActionInstance ai1= new ActionInstance ("this is just a test");
		
		
		// add instnaces to dmManager
		dmm.addAInstance(editorSelect1);
		dmm.addAInstance(editorSelect2);
		dmm.addAInstance(ai1);
		
		// print out action related stuff
		System.out.println("action related stuff!! \n");
					
		System.out.println("DmConcept: " + DmConcept.getDefaultActionConcept().getName()+ " of type "+ " has the following instance:");
		DmInstance actionIn1[]= DmConcept.getDefaultActionConcept().getAllInstances();
		for (int i = 0; i < actionIn1.length; i++) {
    		System.out.println("     "+i+"Instance: " + actionIn1[i].getName() + " " + actionIn1[i].getConceptOf().getName());				
       	}  
		
//       	select1.setLexItem("chooSe");
		System.out.println("DmConcept: " + select1.getName());
		System.out.println("         : of type "+ select1.getType());
//		System.out.println("         lexical root: " + select1.getLexItem()+" has the following instance:");
		DmInstance selectIn1[]= select1.getAllInstances();
		System.out.println("     "+selectIn1.length);
    
		for (int k = 0; k < selectIn1.length; k++) {
    		System.out.println("     "+k+"Instance: " + selectIn1[k].getName());
    	
    		String allActRle[] = relM.getAllActionRelations();
			TreeMap reActInstances = ((ActionInstance)selectIn1[k]).getActionRelations();    
			for (int j = 0; j < allActRle.length; j++) {
				if (reActInstances.get(allActRle[j]) != null){
    				System.out.println("     "+allActRle[j]+" Instance: " 
    					+((DmInstance) reActInstances.get(allActRle[j])).getName());				
				}
       		}  
    		
       	}  
 		 // test the dmManager
       	
       	Collection conceptAll = dmm.getConceptAll();
       	Collection conceptEntity = dmm.getConceptSome("entity type");				
       	Collection conceptUser = dmm.getConceptSome("user type");				
       	Collection conceptSystem = dmm.getConceptSome("system type");				
       	Collection conceptAction = dmm.getConceptSome("action type");
       	
       	Collection instanceAction = dmm.getAInstanceAll();
       	Collection instanceEntity = dmm.getEInstanceAll();
       			
		System.out.println("\n ****** all concepts********");
		dmm.printConcept(conceptAll);		
       			
		System.out.println("\n ****** Entity concepts********");
		dmm.printConcept(conceptEntity);		
       			
		System.out.println("\n ****** User concepts********");
		dmm.printConcept(conceptUser);		
       			
		System.out.println("\n ****** System concepts******** ");
		dmm.printConcept(conceptSystem);		
       			
		System.out.println("\n ****** Action concepts********");
		dmm.printConcept(conceptAction);		
		
		System.out.println("\n ****** Action Instances********");
		dmm.printAInstance(instanceAction);		
		
		System.out.println("\n ****** Entity Instances********");
		dmm.printEInstance(instanceEntity);		
		
		ActionInstance test1= dmm.getAInstance(ai1.getID());
		System.out.println("\n "+ test1.getName() + " = this is just a test" );
		
		dmm.removeEInstance(ei5);
		instanceEntity = dmm.getEInstanceAll();
		System.out.println("\n ****** Entity Instances********");
		dmm.printEInstance(instanceEntity);		
		
		dmm.addConcept(new DmConcept("ccccc"));
		dmm.removeConcept(dc1);
		conceptAll = dmm.getConceptAll();
		System.out.println("\n ****** all concepts********");
		dmm.printConcept(conceptAll);
		
		//Check object ID
		
		DmConcept cid = new DmConcept ("cid", "new concept",ConceptType.getDefaultEntityType());
		EntityInstance eid=new EntityInstance ("eid","new entityInstance");
		ActionInstance aid= new ActionInstance ("aid", "new actionInstance");
		System.out.println("\n" + cid.getID() + "    "+ cid.getName()+
							"\n" +eid.getID() + "    " + eid.getName()+
							"\n"+ aid.getID() + "    " + aid.getName());
		
		
		//Build GUI hierarchy 
		DmConcept win = new DmConcept("window", "entity type");
		DmConcept dia = new DmConcept("dialog", "entity type");
		dia.setParent(win);
		DmConcept mess = new DmConcept("message box","entity type");
		mess.setParent(win);
		DmConcept warn = new DmConcept("warning box","entity type");

		DmConcept.setPCHierarchy(win,dia);
		DmConcept.setPCHierarchy(win,mess);
		DmConcept.setPCHierarchy(win,warn);

		System.out.println("\n"+dia.getName() + " is a kind of "+
							dia.getParent().getName());
		System.out.println("\n"+mess.getName() + " is a kind of "+
							mess.getParent().getName());
		System.out.println("\n"+warn.getName() + " is a kind of "+
							warn.getParent().getName());
		
		System.out.println("\n"+win.getName() + " has children: "+
							win.numberChild());
		DmConcept[] ch=win.getAllChildren();
		for ( int i =0; i<ch.length; i++){
			System.out.println("       " + 	ch[i].getName());
			
		}
		
		DmConcept newC= null;
		newC=new DmConcept("id", "name", "user type");
		newC.setNote("just a test");
		
		//test isConcept()
		System.out.println("" );
		System.out.println("test isConcept()..." );
		if (dmm.isConcept(" thinG ") ) 
			System.out.println("yes, thing is a concept" );
		if (! dmm.isConcept("userr") ) 
			System.out.println("no, userr is not a concept" );
		if (dmm.isEInstance(" fiLe ") ) 
			System.out.println("yes, file is an  entity instance" );
		if (! dmm.isEInstance("userr") ) 
			System.out.println("no, userr is not an  entity instance" );

		if (dmm.isAInstance(" user select new from file menu   ") ) 
			System.out.println("yes, 'user select new from file menu' is an action instance" );
		if (! dmm.isAInstance("userr") ) 
			System.out.println("no, userr is not an action instance" );

		//test getConcept,InstanceByName()
		System.out.println("" );
		System.out.println("test getConcept,InstanceByName()..." );
		DmConcept dcon1=dmm.getEConcept("menuiteM");
		if (dcon1 != null ) 
			System.out.println("yes, '"+ dcon1.getName()+"' is an  entity concept" );
		DmConcept dcon2=dmm.getUserConcept("user");
		if (dcon2 != null ) 
			System.out.println("yes, '"+ dcon2.getName()+"' is an  User concept" );
		DmConcept dcon3=dmm.getSystemConcept("system");
		if (dcon3 != null ) 
			System.out.println("yes, '"+ dcon3.getName()+"' is an  system concept" );
		DmConcept dcon4=dmm.getAConcept("use");
		if (dcon4 != null ) 
			System.out.println("yes, '"+ dcon4.getName()+"' is an  action concept" );

		EntityInstance eIns=dmm.getEInstanceByName("file");
		if (eIns != null ) 
			System.out.println("yes, '"+ eIns.getName()+"' is an  entity instance" );
			
		EntityInstance eIns2=dmm.getEInstanceByName("userr");
		if (eIns2 == null ) 
			System.out.println("no, userr is not an  entity instance" );
			
		ActionInstance aIns=dmm.getAInstanceByName(" user select new from file menu   ");
		if (aIns != null )
			System.out.println("yes, '"+ aIns.getName()+"' is an action instance" );
		ActionInstance aIns2=dmm.getAInstanceByName("userr ");
		if (aIns2 == null ) 
			System.out.println("no, userr is not an action instance" );
		
			//2001-2-14
			//tets findEInsECon() methods 
		dmm.printEInstance(dmm.findEInsECon(dc2));
		
			//tets findAInsRel() methods
		Iterator it = dmm.findEInsECon(dc2).iterator();
		EntityInstance eiTemp;
		SortArrayList sv = new SortArrayList (new DmClassCompare());

		while (it.hasNext()){
			eiTemp = (EntityInstance) it.next();
			sv.addAll(dmm.findAInsRel(eiTemp));
		}
		sv.sort();
		dmm.printAInstance(Collections.synchronizedCollection(sv));
		
			//tets findAInsACon() methods select1
		dmm.printAInstance(dmm.findAInsACon(select1));
		


	} //main()
}
