

// JDK
package icsDyn;

import gov.nist.div897.Asn1ILib.Asn1Object;
import gov.nist.div897.Asn1Lib.CHOICE;
import gov.nist.div897.Asn1Lib.INTEGER;
import gov.nist.div897.Asn1Lib.OCTETSTRING;
import gov.nist.div897.DimLib.EnumObsValue;
import gov.nist.div897.DimLib.NuObsValue;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import addingsToAsnLib.NodeXmlDataType;

import units.UnitsBuilder;

/**
 * This panel contains buttons to generate the XML Batch File
 * @author Rick Rivello
 */
public class ICSGenerationPanel extends JPanel implements ActionListener, Observer {

    private static final long serialVersionUID = 1L;
	
    private ICSModel icsModel;

    private JButton btnGenerate;
    private JButton btnExportXML;
    private JButton btnExportHL7XML;
    private JButton btnMapXML;


    /**
     * Constructor
     */
    public ICSGenerationPanel() {
    
	setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

	JPanel p0 = new JPanel();
	p0.setLayout(new BoxLayout(p0, BoxLayout.LINE_AXIS));

	JLabel lbl = new JLabel("Generate xml file: ");
	p0.add(lbl);
	p0.add(Box.createRigidArea(new Dimension(10, 0)));

	btnGenerate = new JButton("Generate");
	btnGenerate.setBackground(new Color(204, 204, 255));
	btnGenerate.setEnabled(true);
	btnGenerate.addActionListener(this);
	p0.add(btnGenerate);
	p0.add(Box.createRigidArea(new Dimension(10, 0)));
	
	btnExportXML = new JButton("Export XML File");
	btnExportXML.setBackground(new Color(204, 204, 255));
	btnExportXML.addActionListener(this);
	p0.add(btnExportXML);
	p0.add(Box.createRigidArea(new Dimension(10, 0)));
	
	btnMapXML = new JButton("Map XML File to HL7");
	btnMapXML.setBackground(new Color(204, 204, 255));
	btnMapXML.setEnabled(true);
	btnMapXML.addActionListener(this);
	p0.add(btnMapXML);
	p0.add(Box.createRigidArea(new Dimension(10, 0)));
	
	btnExportHL7XML = new JButton("Export HL7 XML File");
	btnExportHL7XML.setBackground(new Color(204, 204, 255));
	btnExportHL7XML.addActionListener(this);
	p0.add(btnExportHL7XML);
	p0.add(Box.createRigidArea(new Dimension(10, 0)));

	add(p0);
	setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
	init();
    }

    /**
     * Handles a click event
     * @param evt The event
     */
    public void actionPerformed(ActionEvent evt) {
    	
	if(evt.getSource() == btnGenerate) {
	   generateXML("");
	   icsModel.fireEvent(new MVCArg("generateXML", doc));
           btnExportXML.setEnabled(true);		
	}
	if(evt.getSource() == btnMapXML) {
		   generateXML("mapXML");
		   icsModel.fireEvent(new MVCArg("mapXML", doc));
	        //   btnMapXML.setEnabled(true);	
	           btnExportXML.setEnabled(false);	
	           btnExportHL7XML.setEnabled(true);
		}
	
	if(evt.getSource() == btnExportHL7XML) {
		   // Open a JFileChooser
		   JFileChooser fc = new JFileChooser();
		   // Set the chooser to accept only XML files.
		   fc.addChoosableFileFilter(new XMLFileFilter());
		   fc.setAcceptAllFileFilterUsed(false);
		   try {
		      // Create a File object containing the canonical path of the
		      // desired directory
		      File f = new File(new File("..\\xml").getCanonicalPath());
		    
		      // Set the current directory
		      fc.setCurrentDirectory(f);
		   } 
	           catch (IOException e) {
		   }

		   fc.setSelectedFile(new File("BatchHL7.xml"));
		   int returnVal = fc.showSaveDialog(this);
		   File f = null;
		   if(returnVal == JFileChooser.APPROVE_OPTION) {
		      f = fc.getSelectedFile();
		      if(!f.getPath().endsWith(".xml")) {
		         f = new File(f.getPath() + ".xml");
		      }
		      if (!f.exists()){
		        writeXMLFile(f);
		      }
		      else { //file exists
		         String msg = "The file \"{0}\" already exists!\nDo you want to replace it?";
		         msg = MessageFormat.format( msg, new Object[] { f.getName() } );
			 String title = getDialogTitle();
			 int option = JOptionPane.showConfirmDialog( this, msg, title, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE );
			 if ( option == JOptionPane.NO_OPTION ) {
			    return;
		         } 	
			 else if ( option == JOptionPane.YES_OPTION ) {
			    writeXMLFile(f);
			 } 	
		      }
		   }
		   btnExportHL7XML.setEnabled(false);
		}
	else if(evt.getSource() == btnExportXML) {
	   // Open a JFileChooser
	   JFileChooser fc = new JFileChooser();
	   // Set the chooser to accept only XML files.
	   fc.addChoosableFileFilter(new XMLFileFilter());
	   fc.setAcceptAllFileFilterUsed(false);
	   try {
	      // Create a File object containing the canonical path of the
	      // desired directory
	      File f = new File(new File("..\\xml").getCanonicalPath());
	    
	      // Set the current directory
	      fc.setCurrentDirectory(f);
	   } 
           catch (IOException e) {
	   }

	   fc.setSelectedFile(new File("Batch.xml"));
	   int returnVal = fc.showSaveDialog(this);
	   File f = null;
	   if(returnVal == JFileChooser.APPROVE_OPTION) {
	      f = fc.getSelectedFile();
	      if(!f.getPath().endsWith(".xml")) {
	         f = new File(f.getPath() + ".xml");
	      }
	      if (!f.exists()){
	        writeXMLFile(f);
	      }
	      else { //file exists
	         String msg = "The file \"{0}\" already exists!\nDo you want to replace it?";
	         msg = MessageFormat.format( msg, new Object[] { f.getName() } );
		 String title = getDialogTitle();
		 int option = JOptionPane.showConfirmDialog( this, msg, title, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE );
		 if ( option == JOptionPane.NO_OPTION ) {
		    return;
	         } 	
		 else if ( option == JOptionPane.YES_OPTION ) {
		    writeXMLFile(f);
		 } 	
	      }
	   }
	   btnExportXML.setEnabled(false);
	}
    }
    private void writeXMLFile(File f) {
	try {
	    Transformer transformer = TransformerFactory.newInstance().newTransformer();
	    DOMSource source = new DOMSource(doc);
	    StreamResult result = new StreamResult(f);
	    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
	    transformer.transform(source, result);
	}
	catch(TransformerConfigurationException tce) {
	    System.err.println("TransformerConfigurationException " + tce.getMessage());
	    tce.printStackTrace();
	}
	catch(TransformerException te) {
	    System.err.println("TransformerException " + te.getMessage());
	    te.printStackTrace();
	}
    }

    
	private String getDialogTitle() {
		// TODO Auto-generated method stub
		return null;
	}


    /**
     * MVC
     * @param o The observable object
     * @param arg An argument passed to the notifyObservers method
     */
    public void update(Observable o, Object arg) {
	if(o instanceof ICSModel) {
	   if(arg instanceof MVCArg) {
    	      if("isEnable".equals(((MVCArg)arg).getName())) {
    	         btnGenerate.setEnabled(((MVCArg)arg).getBValue());
    	         generateXML("");
    	         icsModel.fireEvent(new MVCArg("NewDom", doc));
    	      }	
	      if("node".equals(((MVCArg)arg).getName())) {			
	         btnExportXML.setEnabled(false);
	      }
              if ("mdsType".equals(((MVCArg)arg).getName())) {
                 btnGenerate.setEnabled(true);
                 btnMapXML.setEnabled(true);
              }
	   }
        }
    }
    

    /**
     * Set the model
     * @param model The model
     */
    public void setICSModel(ICSModel model) {
	icsModel = model;
    }

    /**
     * Init the panel
     */
    public void init() {
	btnGenerate.setEnabled(false);
	btnExportXML.setEnabled(false);	
	btnMapXML.setEnabled(false);
	btnExportHL7XML.setEnabled(false);
	VMDContNum=0;
    ChannelContNum=0;
    MDSContNum=0;
    OBSItemContNum=0;
    }

    public Document doc;
    
    int VMDContNum=0;
    int ChannelContNum=0;
    int MDSContNum=0;
    int OBSItemContNum=0;

    private String MOCName;
    private String MOCObjectName;
    private String MOCObjectNameLabel;
    private String MOCObjectId;
    private String MOCTermCode;
    private String MOCReference;
    private String MOCRestrictions;
    private String MOCApplicationGuidance;
    private String MOCServicesSupported;
    private String MOCComment;
    private String MOCTypeID;
    private String MOCTypeTermCode;

    private String AttributeName;
    private String AttributeId;
    private String AttributeType;
    private String AttributeTermCode;
    private String AttributeReference;
    private String AttributeQual;
    private String AttributeAccess;
    private String AttributeValueRange;
    private String AttributeRestrictions;
    private String AttributeApplicationGuidance;
    private String AttributeComment;

    private String BehaviourMethodName;
    private String BehaviourMethodId;
    private String BehaviourActionParameter;
    private String BehaviourActionResult;
    private String BehaviourTermCode;
    private String BehaviourReference;
    private String BehaviourQual;
    private String BehaviourRestrictions;
    private String BehaviourComment;

    private String NotificationName;
    private String NotificationId;
    private String NotificationEventParameter;
    private String NotificationTermCode;
    private String NotificationReference;
    private String NotificationQual;
    private String NotificationRestrictions;
    private String NotificationComment;

    private Element xmlRoot;
    private Element obxRoot;
    
    private Element xmlObjectName;
    private Element xmlObjectId;
    private Element xmlMOCTermCode;
    private Element xmlMOCReference;
    private Element xmlMOCRestrictions;
    private Element xmlMOCApplicationGuidance;
    private Element xmlMOCServicesSupported;
    private Element xmlMOCComment;
    private Element xmlMOCTypeID;
    private Element xmlMOCTypeTermCode;

    private Element xmlAttributeInfo;
    private Element xmlPrivateAttribute;
    private Element xmlAttribute;    
    private Element xmlAttributeName;
    private Element xmlAttributeId;
    private Element xmlAttributeType;
    private Element xmlAttributeTermCode;
    private Element xmlAttributeReference;
    private Element xmlAttributeQual;
    private Element xmlAttributeAccess;
    private Element xmlAttributeValueRange;
    private Element xmlAttributeSampleValue;
    private Element xmlAttributeRestrictions;
    private Element xmlAttributeApplicationGuidance;
    private Element xmlAttributeComment;

    private Element xmlBehaviourInfo;
    private Element xmlPrivateBehaviour;
    private Element xmlBehaviour;    
    private Element xmlBehaviourMethodName;
    private Element xmlBehaviourMethodId;
    private Element xmlBehaviourActionParameter;
    private Element xmlBehaviourActionResult;
    private Element xmlBehaviourTermCode;
    private Element xmlBehaviourReference;
    private Element xmlBehaviourQual;
    private Element xmlBehaviourRestrictions;
    private Element xmlBehaviourComment;

    private Element xmlNotificationInfo;
    private Element xmlPrivateNotification;
    private Element xmlNotification;    
    private Element xmlNotificationName;
    private Element xmlNotificationId;
    private Element xmlNotificationEventParameter;
    private Element xmlNotificationTermCode;
    private Element xmlNotificationReference;
    private Element xmlNotificationQual;
    private Element xmlNotificationRestrictions;
    private Element xmlNotificationComment;
          
    private Element xmlObx2Name;			
    private Element xmlObx3Name;			
    private Element xmlObx3OneName;			
    private Element xmlObx3TwoName;			
    private Element xmlObx3ThreeName;			
    private Element xmlObx4Name;			
    private Element xmlObx5Name;
    private Element xmlObx5OneName;			
    private Element xmlObx5TwoName;			
    private Element xmlObx5ThreeName;	
    private Element xmlObx6Name;			
    private Element xmlObx6OneName;			
    private Element xmlObx6TwoName;			
    private Element xmlObx6ThreeName;
    private Element xmlObx7Name;
    
    /**
     * Generate the XML batch file
     */
    public void generateXML(String typeButton) { 

        DefaultMutableTreeNode root,dimNd;

        //  Create a XML Document
    	try {
    	    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    	    DocumentBuilder builder = factory.newDocumentBuilder();
    	    doc = builder.newDocument();
    	}
    	catch(ParserConfigurationException pce) {
    	    System.err.println("ParserConfigurationException " + pce.getMessage());
    	    pce.printStackTrace();
    	}
        
        Node dimRoot = null;
        obxRoot = null;

        if ("mapXML".equals(typeButton)){
        	obxRoot = doc.createElement("ORU_R01");
       	 	doc.appendChild(obxRoot);
	       	 VMDContNum=0;
	         ChannelContNum=0;
	         MDSContNum=0;
	         OBSItemContNum=0;
        }
          else {
        	  Document d1 = icsModel.getDOMDocument(); //from the model get the dim xml file

              Element defroot = d1.getDocumentElement(); //getting the root element of the document (xml)
              
               dimRoot = doc.importNode(defroot,false); //creates a new copy of the root node (element)

              doc.appendChild(dimRoot);//adds the root node to the output xml file 
	  
          }

    	DefaultMutableTreeNode DMTree = icsModel.getTree();
        Enumeration treeEnum = DMTree.preorderEnumeration();
        root = (DefaultMutableTreeNode) treeEnum.nextElement();

        ArrayList<DefaultMutableTreeNode> rootList = new ArrayList<DefaultMutableTreeNode>();       
        Enumeration rootChildren = (Enumeration) root.children();
        while (rootChildren.hasMoreElements()) {               
           rootList.add((DefaultMutableTreeNode)rootChildren.nextElement());
        } 

  	Collections.sort(rootList, new Comparator<DefaultMutableTreeNode>() {
	   public int compare(DefaultMutableTreeNode o1, DefaultMutableTreeNode o2) {
	      DefaultMutableTreeNode dfmtnString1 = (DefaultMutableTreeNode)o1;
	      DefaultMutableTreeNode dfmtnString2 = (DefaultMutableTreeNode)o2;
	      return dfmtnString1.toString().compareTo(dfmtnString2.toString());
	   }
	});

        rootChildren = Collections.enumeration(rootList);
        while (rootChildren.hasMoreElements()) {               
           dimNd = (DefaultMutableTreeNode) rootChildren.nextElement();
           xmlRoot = doc.createElement(dimNd.toString()); 
           
           if ("mapXML".equals(typeButton)){
              	generateHL7XMLNode(dimNd);
           }
           else {
              	xmlRoot = generateXMLNode(dimNd);
               dimRoot.appendChild(xmlRoot);}
        }
              	
         	
    }
    private int getParNum(String refId){
    	int partNum = 2;
    	if (refId.contains("MDC_MOC")|| refId.contains("MDC_ALSTAT")|| refId.contains("MDC_ATTR_GRP")|| refId.contains("MDC_ATTR") || refId.contains("MDC_ACT") || refId.contains("MDC_NOTI") || refId.contains("MDC_DEV")){
    		partNum = 1;
    	}
    	if (refId.contains("MDC_EVT")){
    		partNum = 3;
    	}
    	if (refId.contains("MDC_DIM")){
    		partNum = 4;
    	}
    	return partNum;
    }
   
	private Element generateHL7XMLNode(DefaultMutableTreeNode node) {
    		Element xmlRoot1;
            
            String strcontexFreeNomCode = "";
            int intMocTermCode = 0;
            int contexFreeNomCode = 0;
            int partNum = 1;
            Object obj = node.getUserObject(); //get object from tree
            MOCNode selMoc = (MOCNode) obj; // convert that object to a MOCNode class

            
            int mocIdNumber = selMoc.getMocIdNumber(); // get the mocIdNumber associated to selected mocNode
            
            int inx = icsModel.getcurVMoc().indexOf(selMoc); //get the loc of the moc in the currVMov vector
            MOCNode mocNode = (MOCNode)icsModel.getcurVMoc().get(inx); //get the mocNode class of the moc from vector
            int tempmocIdNumber = mocNode.getMocIdNumber(); //assign tem modIdNumber to current moc.

            while (tempmocIdNumber != mocIdNumber) {
               inx = icsModel.getcurVMoc().indexOf(selMoc,inx+1);
               mocNode = (MOCNode)icsModel.getcurVMoc().get(inx);
               tempmocIdNumber = mocNode.getMocIdNumber();
            }
            

            MOCName             = mocNode.getObjectName();
            MOCTypeTermCode		= mocNode.getTypeIDTermCode();
            MOCTypeID			= mocNode.getTypeID();            
            if(MOCTypeTermCode.toString() != ""){
	            partNum = getParNum(MOCTypeID);
	            intMocTermCode = Integer.parseInt(MOCTypeTermCode.toString());
	            contexFreeNomCode = (int) ((partNum * Math.pow(2,16)) + intMocTermCode);
	            strcontexFreeNomCode = Integer.toString(contexFreeNomCode);
            }
            
            xmlObx2Name			= doc.createElement("OBX.2");
            xmlObx3Name			= doc.createElement("OBX.3");
            xmlObx3OneName		= doc.createElement("CE.1");
            xmlObx3TwoName		= doc.createElement("CE.2");
            xmlObx3ThreeName	= doc.createElement("CE.3");
            xmlObx4Name			= doc.createElement("OBX.4");
            xmlObx5Name			= doc.createElement("OBX.5");
            xmlObx5OneName		= doc.createElement("CE.1");
            xmlObx5TwoName		= doc.createElement("CE.2");
            xmlObx5ThreeName	= doc.createElement("CE.3");
            xmlObx6Name			= doc.createElement("OBX.6");
            xmlObx6OneName		= doc.createElement("CE.1");
            xmlObx6TwoName		= doc.createElement("CE.2");
            xmlObx6ThreeName	= doc.createElement("CE.3");
            xmlObx7Name			= doc.createElement("OBX.7");
            
            
            xmlRoot1 = doc.createElement("OBXToRemove");
            if (mocNode.getObjectName().equals("Simple_MDS") || mocNode.getObjectName().equals("Hydra_MDS")){
             	MDSContNum = MDSContNum +1;
             	xmlRoot1 = doc.createElement("OBX");
            	OBSItemContNum = 0;
            	Integer channelLevel = new Integer(ChannelContNum);
            	Integer vmdLevel = new Integer(VMDContNum);
            	Integer mdsLevel = new Integer(MDSContNum);
            	Integer obsItemLevel = new Integer(OBSItemContNum);
            	
            	String objItemContLevel = mdsLevel.toString().concat(".").concat(vmdLevel.toString()).concat(".").concat(channelLevel.toString()).concat(".").concat(obsItemLevel.toString());
            	xmlObx5OneName.appendChild(doc.createTextNode(strcontexFreeNomCode));
            	xmlObx5TwoName.appendChild(doc.createTextNode(MOCTypeID));
            	xmlObx5ThreeName.appendChild(doc.createTextNode("MDC"));
            	
            	xmlObx5Name.appendChild(xmlObx5OneName);
                xmlObx5Name.appendChild(xmlObx5TwoName);
                xmlObx5Name.appendChild(xmlObx5ThreeName);
            	
            	contexFreeNomCode = (int) ((partNum * Math.pow(2,16)) + 2438);
                strcontexFreeNomCode = Integer.toString(contexFreeNomCode);
            	
                xmlObx3OneName.appendChild(doc.createTextNode(strcontexFreeNomCode));
            	xmlObx3TwoName.appendChild(doc.createTextNode("MDC_ATTR_SYS_TYPE"));
            	xmlObx3ThreeName.appendChild(doc.createTextNode("MDC"));
            	
            	xmlObx4Name.appendChild(doc.createTextNode(objItemContLevel));
            	
            	xmlObx3Name.appendChild(xmlObx3OneName);
                xmlObx3Name.appendChild(xmlObx3TwoName);
                xmlObx3Name.appendChild(xmlObx3ThreeName);
                
                xmlObx6Name.appendChild(xmlObx6OneName);
                xmlObx6Name.appendChild(xmlObx6TwoName);
                xmlObx6Name.appendChild(xmlObx6ThreeName);
            	 
                xmlObx2Name.appendChild(doc.createTextNode("CE"));
                
                
                
            	//xmlRoot1.setAttribute("Object", MOCName);
            	xmlRoot1.appendChild(xmlObx2Name);
            	xmlRoot1.appendChild(xmlObx3Name);
            	xmlRoot1.appendChild(xmlObx4Name);
            	xmlRoot1.appendChild(xmlObx5Name);
            	xmlRoot1.appendChild(xmlObx6Name);
            	xmlRoot1.appendChild(xmlObx7Name);
             	
             }
            if (mocNode.getObjectName().equals("VMD")){
             	VMDContNum = VMDContNum +1;
             	xmlRoot1 = doc.createElement("OBX");
            	OBSItemContNum = 0;
            	Integer channelLevel = new Integer(ChannelContNum);
            	Integer vmdLevel = new Integer(VMDContNum);
            	Integer mdsLevel = new Integer(MDSContNum);
            	Integer obsItemLevel = new Integer(OBSItemContNum);
            	
            	String objItemContLevel = mdsLevel.toString().concat(".").concat(vmdLevel.toString()).concat(".").concat(channelLevel.toString()).concat(".").concat(obsItemLevel.toString());
            	            	
            	xmlObx2Name.appendChild(doc.createTextNode("CE"));
            	 
            	xmlObx5OneName.appendChild(doc.createTextNode(strcontexFreeNomCode));
            	xmlObx5TwoName.appendChild(doc.createTextNode(MOCTypeID));
            	xmlObx5ThreeName.appendChild(doc.createTextNode("MDC"));
            	
            	xmlObx5Name.appendChild(xmlObx5OneName);
                xmlObx5Name.appendChild(xmlObx5TwoName);
                xmlObx5Name.appendChild(xmlObx5ThreeName);
            	
            	contexFreeNomCode = (int) ((partNum * Math.pow(2,16)) + 2438);
                strcontexFreeNomCode = Integer.toString(contexFreeNomCode);
            	
                xmlObx3OneName.appendChild(doc.createTextNode(strcontexFreeNomCode));
            	xmlObx3TwoName.appendChild(doc.createTextNode("MDC_ATTR_SYS_TYPE"));
            	xmlObx3ThreeName.appendChild(doc.createTextNode("MDC"));
            	
            	xmlObx4Name.appendChild(doc.createTextNode(objItemContLevel));
            	
            	
                xmlObx3Name.appendChild(xmlObx3OneName);
                xmlObx3Name.appendChild(xmlObx3TwoName);
                xmlObx3Name.appendChild(xmlObx3ThreeName);
                
                xmlObx6Name.appendChild(xmlObx6OneName);
                xmlObx6Name.appendChild(xmlObx6TwoName);
                xmlObx6Name.appendChild(xmlObx6ThreeName);
            	xmlRoot1.appendChild(xmlObx2Name);
            	xmlRoot1.appendChild(xmlObx3Name);
            	xmlRoot1.appendChild(xmlObx4Name);
            	xmlRoot1.appendChild(xmlObx5Name);
            	xmlRoot1.appendChild(xmlObx6Name);
            	xmlRoot1.appendChild(xmlObx7Name);
             }
            if (mocNode.getObjectName().equals("Channel")){
             	ChannelContNum = ChannelContNum +1; 
             	xmlRoot1 = doc.createElement("OBX");
            	OBSItemContNum = 0;
            	Integer channelLevel = new Integer(ChannelContNum);
            	Integer vmdLevel = new Integer(VMDContNum);
            	Integer mdsLevel = new Integer(MDSContNum);
            	Integer obsItemLevel = new Integer(OBSItemContNum);
            	
            	String objItemContLevel = mdsLevel.toString().concat(".").concat(vmdLevel.toString()).concat(".").concat(channelLevel.toString()).concat(".").concat(obsItemLevel.toString());
            	xmlObx2Name.appendChild(doc.createTextNode("CE"));
           	 
            	xmlObx5OneName.appendChild(doc.createTextNode(strcontexFreeNomCode));
            	xmlObx5TwoName.appendChild(doc.createTextNode(MOCTypeID));
            	xmlObx5ThreeName.appendChild(doc.createTextNode("MDC"));
            	
            	xmlObx5Name.appendChild(xmlObx5OneName);
                xmlObx5Name.appendChild(xmlObx5TwoName);
                xmlObx5Name.appendChild(xmlObx5ThreeName);
            	
            	contexFreeNomCode = (int) ((partNum * Math.pow(2,16)) + 2438);
                strcontexFreeNomCode = Integer.toString(contexFreeNomCode);
            	
                xmlObx3OneName.appendChild(doc.createTextNode(strcontexFreeNomCode));
            	xmlObx3TwoName.appendChild(doc.createTextNode("MDC_ATTR_SYS_TYPE"));
            	xmlObx3ThreeName.appendChild(doc.createTextNode("MDC"));
            	
            	xmlObx4Name.appendChild(doc.createTextNode(objItemContLevel));
            	
            	xmlObx3Name.appendChild(xmlObx3OneName);
                xmlObx3Name.appendChild(xmlObx3TwoName);
                xmlObx3Name.appendChild(xmlObx3ThreeName);
                
                xmlObx6Name.appendChild(xmlObx6OneName);
                xmlObx6Name.appendChild(xmlObx6TwoName);
                xmlObx6Name.appendChild(xmlObx6ThreeName);
            	 
            	
            	//xmlRoot1.setAttribute("Object", MOCName);
            	xmlRoot1.appendChild(xmlObx2Name);
            	xmlRoot1.appendChild(xmlObx3Name);
            	xmlRoot1.appendChild(xmlObx4Name);
            	xmlRoot1.appendChild(xmlObx5Name);
            	xmlRoot1.appendChild(xmlObx6Name);
            	xmlRoot1.appendChild(xmlObx7Name);
             }
           
            if (mocNode.getObjectName().equals("Numeric")|| mocNode.getObjectName().equals("Enumeration")){

            	xmlRoot1 = doc.createElement("OBX");
            	OBSItemContNum = OBSItemContNum +1;
            	Integer channelLevel = new Integer(ChannelContNum);
            	Integer vmdLevel = new Integer(VMDContNum);
            	Integer mdsLevel = new Integer(MDSContNum);
            	Integer obsItemLevel = new Integer(OBSItemContNum);
            	
            	String objItemContLevel = mdsLevel.toString().concat(".").concat(vmdLevel.toString()).concat(".").concat(channelLevel.toString()).concat(".").concat(obsItemLevel.toString());
            	xmlObx3OneName.appendChild(doc.createTextNode(strcontexFreeNomCode));
            	xmlObx3TwoName.appendChild(doc.createTextNode(MOCTypeID));
            	xmlObx3ThreeName.appendChild(doc.createTextNode("MDC"));
            	
            	xmlObx4Name.appendChild(doc.createTextNode(objItemContLevel));
            	
            	
                xmlObx3Name.appendChild(xmlObx3OneName);
                xmlObx3Name.appendChild(xmlObx3TwoName);
                xmlObx3Name.appendChild(xmlObx3ThreeName);
                
                xmlObx6Name.appendChild(xmlObx6OneName);
                xmlObx6Name.appendChild(xmlObx6TwoName);
                xmlObx6Name.appendChild(xmlObx6ThreeName);
                   
            	if(mocNode.getObjectName().equals("Numeric")){  
            		String[] val = getValueOfNumeric(mocNode);
	            	xmlObx2Name.appendChild(doc.createTextNode("NM"));
	            	
	            	xmlObx5Name.appendChild(doc.createTextNode(val[0]));
	            	
	            	partNum = getParNum(MOCTypeID);
	            	if(val[1]!= ""){
		                intMocTermCode = Integer.parseInt(val[1]);
		                contexFreeNomCode = (int) ((partNum * Math.pow(2,16)) + intMocTermCode);
		                strcontexFreeNomCode = Integer.toString(contexFreeNomCode);
	            	}
	            	else
	            		strcontexFreeNomCode = "";
	            	xmlObx6OneName.appendChild(doc.createTextNode(strcontexFreeNomCode));
	            	xmlObx6TwoName.appendChild(doc.createTextNode(UnitsBuilder.getUnit(intMocTermCode).getReferenceId()));
	            	xmlObx6ThreeName.appendChild(doc.createTextNode("MDC"));
	            	
	            	
	            	String range = getNuObservedValueRange(mocNode);
	            	xmlObx7Name.appendChild(doc.createTextNode(range));
            	}
            	else{
            		String[] val = getValueOfEnumeration(mocNode);
            		xmlObx2Name.appendChild(doc.createTextNode(val[0]));
            		xmlObx5Name.appendChild(doc.createTextNode(val[1]));
            	}
            	xmlRoot1.appendChild(xmlObx2Name);
            	xmlRoot1.appendChild(xmlObx3Name);
            	xmlRoot1.appendChild(xmlObx4Name);
            	xmlRoot1.appendChild(xmlObx5Name);
            	xmlRoot1.appendChild(xmlObx6Name);
            	xmlRoot1.appendChild(xmlObx7Name);
            }
            if(xmlRoot1.getNodeName() == "OBXToRemove")
            	xmlRoot1 = null;
            if(xmlRoot1 != null)
            	obxRoot.appendChild(xmlRoot1);
            if (!node.isLeaf()) {
            	 ArrayList<DefaultMutableTreeNode> rootList = new ArrayList<DefaultMutableTreeNode>();
                 Enumeration chldrn = node.children();
                 while (chldrn.hasMoreElements()) {               
                     rootList.add((DefaultMutableTreeNode)chldrn.nextElement());
                  } 

                Collections.sort(rootList, new Comparator<DefaultMutableTreeNode>(){
                	public int compare(DefaultMutableTreeNode arg0, DefaultMutableTreeNode arg1) {
                		return arg0.toString().compareTo(arg1.toString());
                	}
                });
                chldrn = Collections.enumeration(rootList); 
                while (chldrn.hasMoreElements()) {
                   DefaultMutableTreeNode tnd = (DefaultMutableTreeNode) chldrn.nextElement();
               	   generateHL7XMLNode(tnd);   
                                   
                }
             } 
            
           
            return xmlRoot1;
            
    }
    private String[] getValueOfNumeric(MOCNode moc){
    	String val0 = "";
    	String val1 = "";
    	if(moc.getObjectName().equals("Numeric")){
    		Vector vectAttr = moc.getAttribute();
    		//we look for NuObservedValueAttr
    		for(int i = 0; i < vectAttr.size(); i++){
    			AttributeNode attr = (AttributeNode) vectAttr.get(i);
    			if(attr.getAttributeName().equals("Nu-Observed-Value")){
    				NuObsValue asnObsVal = (NuObsValue)attr.getAttributeSampleValue();
    				if(asnObsVal != null){
    					INTEGER asnObj = (INTEGER)asnObsVal.getSequenceObject("value");
    					if(asnObj.getData() != null)
    						val0 = asnObj.getDataAsBigInteger().toString();
    					asnObj = (INTEGER)asnObsVal.getSequenceObject("unit-code");
    					if(asnObj.getData() != null)
    						val1 = asnObj.getDataAsBigInteger().toString();
    				}
    				i = vectAttr.size();
    			}
    		}
    	}
    	return new String[]{val0, val1};
    }
    
    private String getNuObservedValueRange(MOCNode moc){
    	String val = "";
    	if(moc.getObjectName().equals("Numeric")){
    		Vector vectAttr = moc.getAttribute();
    		//we look for NuObservedValueAttr
    		for(int i = 0; i < vectAttr.size(); i++){
    			AttributeNode attr = (AttributeNode) vectAttr.get(i);
    			if(attr.getAttributeName().equals("Nu-Observed-Value")){
    				val = attr.getAttributeValueRange();
    			}
    		}
    	}
    	return val;
    }
    private String[] getValueOfEnumeration(MOCNode moc){
    	String val0 = "";
    	String val1 = "";
    	if(moc.getObjectName().equals("Enumeration")){
    		Vector vectAttr = moc.getAttribute();
    		//we look for NuObservedValueAttr
    		for(int i = 0; i < vectAttr.size(); i++){
    			AttributeNode attr = (AttributeNode) vectAttr.get(i);
    			if(attr.getAttributeName().equals("Enum-Observed-Value")){
    				EnumObsValue asnObsVal = (EnumObsValue)attr.getAttributeSampleValue();
    				if(asnObsVal != null){
    					CHOICE asnObj = (CHOICE)asnObsVal.getSequenceObject("value");
    					Asn1Object asnChosen = asnObj.getChoice();
    					if (asnChosen instanceof INTEGER) {
							INTEGER asnInteger = (INTEGER) asnChosen;
							val0 = "NM";
							val1 = asnInteger.getDataAsBigInteger().toString();
							
						}
    					else if (asnChosen instanceof OCTETSTRING) {
							OCTETSTRING asnString = (OCTETSTRING) asnChosen;
							val0 = "ST";
							if(asnString.getData() != null)
								val1 = new String(asnString.getData());
						}
    					
    				}
    				i = vectAttr.size();
    			}
    		}
    	}
    	return new String[]{val0, val1};
    }
    private Element generateXMLNode(DefaultMutableTreeNode node) {
    	
            Element xmlRoot1;

            Object obj = node.getUserObject();
            MOCNode selMoc = (MOCNode) obj;

            int mocIdNumber = selMoc.getMocIdNumber();
            int inx = icsModel.getcurVMoc().indexOf(selMoc);
            MOCNode mocNode = (MOCNode)icsModel.getcurVMoc().get(inx);
            int tempmocIdNumber = mocNode.getMocIdNumber();

            while (tempmocIdNumber != mocIdNumber) {
               inx = icsModel.getcurVMoc().indexOf(selMoc,inx+1);
               mocNode = (MOCNode)icsModel.getcurVMoc().get(inx);
               tempmocIdNumber = mocNode.getMocIdNumber();
            }

            if(mocNode.isPrivate)
            	MOCName                = "Private-MOC";
            else
            	MOCName                = mocNode.getObjectName();
            MOCObjectName          = mocNode.getObjectName();
            MOCObjectNameLabel     = mocNode.getObjectNameLabel();
            MOCObjectId            = mocNode.getObjectId();
            MOCTermCode            = mocNode.getMocTermCode();
            MOCReference           = mocNode.getReference();
            MOCRestrictions        = mocNode.getMocRestrictions();
            MOCApplicationGuidance = mocNode.getMocApplicationGuidance();
            MOCServicesSupported   = mocNode.getMocServicesSupported();
            MOCComment             = mocNode.getMocComment();
            MOCTypeID			   = mocNode.getTypeID();
            MOCTypeTermCode		   = mocNode.getTypeIDTermCode();
           

            if (MOCRestrictions == null) {
               MOCRestrictions = "";
            }
            if (MOCApplicationGuidance == null) {
               MOCApplicationGuidance = "";
            }
            if (MOCServicesSupported == null) {
               MOCServicesSupported = "";
            }
            if (MOCComment == null) {
               MOCComment = "";
            }

            
            xmlObjectName             = doc.createElement("OBJECT_NAME");
            xmlObjectId               = doc.createElement("OBJECT_ID");
            xmlMOCTermCode            = doc.createElement("TERM_CODE");
            xmlMOCReference           = doc.createElement("Reference");
            xmlMOCRestrictions        = doc.createElement("MOC_RESTRICTIONS");
            xmlMOCApplicationGuidance = doc.createElement("MOC_APPLICATION_GUIDANCE");
            xmlMOCServicesSupported   = doc.createElement("MOC_SERVICES_SUPPORTED");
            xmlMOCComment             = doc.createElement("MOC_COMMENT");
            xmlMOCTypeID			  = doc.createElement("MOC_TYPE_ID");
            xmlMOCTypeTermCode		  = doc.createElement("MOC_TYPE_TERM_CODE");

            xmlObjectName.setAttribute("Label",MOCObjectNameLabel);

            xmlObjectName.appendChild(doc.createTextNode(MOCObjectName));
            xmlObjectId.appendChild(doc.createTextNode(MOCObjectId));
            xmlMOCTermCode.appendChild(doc.createTextNode(MOCTermCode));
            xmlMOCTypeID.appendChild(doc.createTextNode(MOCTypeID));
            xmlMOCTypeTermCode.appendChild(doc.createTextNode(MOCTypeTermCode));
            xmlMOCReference.appendChild(doc.createTextNode(MOCReference));
            xmlMOCRestrictions.appendChild(doc.createTextNode(MOCRestrictions));
            xmlMOCApplicationGuidance.appendChild(doc.createTextNode(MOCApplicationGuidance));
            xmlMOCServicesSupported.appendChild(doc.createTextNode(MOCServicesSupported));
            xmlMOCComment.appendChild(doc.createTextNode(MOCComment));
            
           
            xmlRoot1 = doc.createElement(MOCName);

            xmlRoot1.appendChild(xmlObjectName);
            xmlRoot1.appendChild(xmlObjectId);
            xmlRoot1.appendChild(xmlMOCTypeID);
            xmlRoot1.appendChild(xmlMOCTypeTermCode);
            xmlRoot1.appendChild(xmlMOCTermCode);
            xmlRoot1.appendChild(xmlMOCReference);
            xmlRoot1.appendChild(xmlMOCRestrictions);
            xmlRoot1.appendChild(xmlMOCApplicationGuidance);
            xmlRoot1.appendChild(xmlMOCServicesSupported);
            xmlRoot1.appendChild(xmlMOCComment);
            

    	    Vector<AttributeNode> vAttribute = mocNode.getAttribute();

    	    xmlAttributeInfo = doc.createElement("Attribute_Info");
            if (vAttribute.size() > 0) {
              
	       Collections.sort(vAttribute, new Comparator<AttributeNode>() {
	          public int compare(AttributeNode o1, AttributeNode o2) {
	             AttributeNode an1 = (AttributeNode)o1;
	   	     AttributeNode an2 = (AttributeNode)o2;
        	     return an1.getAttributeName().compareTo(an2.getAttributeName());
	          }
	       });	         
            }
            Vector<AttributeNode> vPrivateAttr = new Vector<AttributeNode>();
            Vector<AttributeNode> vPublicAttr = new Vector<AttributeNode>();
            for (int ac = 0; ac < vAttribute.size(); ac++) {
            	AttributeNode attr = (AttributeNode) vAttribute.get(ac);
            	if(attr.isPrivate)
            		vPrivateAttr.add(attr);
            	else
            		vPublicAttr.add(attr);
            }
            int ac = -1;
            xmlPrivateAttribute = null;
            boolean privateAttr = false;
    	    for (int i = 0; i < vAttribute.size(); i++) {
    	    	AttributeNode attr; 
    	    	if(ac < vPublicAttr.size() - 1 && !privateAttr)
    	    	{	
    	    		ac++;
    	    		attr = (AttributeNode) vPublicAttr.get(ac);
    	    		xmlAttribute                    = doc.createElement(attr.getAttributeName());
    	    		
    	    		
    	    		xmlAttribute.setAttribute("attrGrpName",((DIMMOC) vAttribute.get(ac)).getAttributeGroupName());
                    xmlAttribute.setAttribute("attrGrpId",((DIMMOC) vAttribute.get(ac)).getAttributeGroupId());
                    xmlAttribute.setAttribute("attrGrpTermCode",((DIMMOC) vAttribute.get(ac)).getAttributeGroupTermCode());
                    xmlAttribute.setAttribute("derivedFrom",((DIMMOC) vAttribute.get(ac)).getAttributeDerivedFrom());
    	    	}
    	    	else if(ac == vPublicAttr.size() - 1 && ac < vAttribute.size() - 1 && !privateAttr){
    	    		ac = 0;
    	    		attr = (AttributeNode) vPrivateAttr.get(ac);
    	    		privateAttr = true;
    	    		xmlAttribute                    = doc.createElement("Attributes");
    	    		xmlPrivateAttribute = doc.createElement("Private-Attributes");
    	    	}
    	    	else{
    	    		ac++;
    	    		attr = (AttributeNode) vPrivateAttr.get(ac);
    	    		xmlAttribute                    = doc.createElement("Attributes");
    	    	}
               

                


                xmlAttributeName                = doc.createElement("ATTRIBUTE_NAME");
                xmlAttributeId                  = doc.createElement("ATTRIBUTE_ID");
                xmlAttributeType                = doc.createElement("ATTRIBUTE_TYPE");
                xmlAttributeTermCode            = doc.createElement("TERM_CODE");
    	    	xmlAttributeReference           = doc.createElement("Reference");
    	    	xmlAttributeQual                = doc.createElement("Qual");
                xmlAttributeAccess              = doc.createElement("ATTRIBUTE_ACCESS");
                xmlAttributeValueRange          = doc.createElement("ATTRIBUTE_VALUE_RANGE");
                xmlAttributeSampleValue          = doc.createElement("ATTRIBUTE_SAMPLE_VALUE");
                xmlAttributeRestrictions        = doc.createElement("ATTRIBUTE_RESTRICTIONS");
                xmlAttributeApplicationGuidance = doc.createElement("ATTRIBUTE_APPLICATION_GUIDANCE");
                xmlAttributeComment             = doc.createElement("ATTRIBUTE_COMMENT");

    	    	AttributeName                = attr.getAttributeName();
    	    	AttributeId                  = attr.getAttributeId();
                AttributeType                = attr.getAttributeType();
                AttributeTermCode            = attr.getAttributeTermCode();
    	    	AttributeReference           = attr.getAttributeReference();
    	    	AttributeQual                = attr.getAttributeQual();
                AttributeAccess              = attr.getAttributeAccess();
                AttributeValueRange          = attr.getAttributeValueRange();
                AttributeRestrictions        = attr.getAttributeRestrictions();
                AttributeApplicationGuidance = attr.getAttributeApplicationGuidance();
                AttributeComment             = attr.getAttributeComment();

                if (AttributeAccess == null) {
                   AttributeAccess = "";
                }
                if (AttributeValueRange == null) {
                   AttributeValueRange = "";
                }
                if (AttributeRestrictions == null) {
                   AttributeRestrictions = "";
                }
                if (AttributeApplicationGuidance == null) {
                   AttributeApplicationGuidance = "";
                }
                if (AttributeComment == null) {
                   AttributeComment = "";
                }

    	    	xmlAttributeName.appendChild(doc.createTextNode(AttributeName));
    	    	xmlAttributeId.appendChild(doc.createTextNode(AttributeId));
                xmlAttributeType.appendChild(doc.createTextNode(AttributeType));
                xmlAttributeTermCode.appendChild(doc.createTextNode(AttributeTermCode));
    	    	xmlAttributeReference.appendChild(doc.createTextNode(AttributeReference));
    	    	xmlAttributeQual.appendChild(doc.createTextNode(AttributeQual));
                xmlAttributeAccess.appendChild(doc.createTextNode(AttributeAccess));
                xmlAttributeValueRange.appendChild(doc.createTextNode(AttributeValueRange));
                if(!privateAttr && attr.getAttributeSampleValue()!= null){
                	Node nodeTemp = NodeXmlDataType.NodeFromASN1Object(attr.getAttributeSampleValue(), doc, true);
                	if(nodeTemp != null)
                		xmlAttributeSampleValue.appendChild(nodeTemp);
                }
                
                xmlAttributeRestrictions.appendChild(doc.createTextNode(AttributeRestrictions));
                xmlAttributeApplicationGuidance.appendChild(doc.createTextNode(AttributeApplicationGuidance));                xmlAttributeComment.appendChild(doc.createTextNode(AttributeComment));
                
    	    	xmlAttribute.appendChild(xmlAttributeName);
    	    	xmlAttribute.appendChild(xmlAttributeId);
                xmlAttribute.appendChild(xmlAttributeType);
                xmlAttribute.appendChild(xmlAttributeTermCode);
    	    	xmlAttribute.appendChild(xmlAttributeReference);
    	    	xmlAttribute.appendChild(xmlAttributeQual);
                xmlAttribute.appendChild(xmlAttributeAccess);
                xmlAttribute.appendChild(xmlAttributeValueRange);
                if(xmlAttributeSampleValue.hasChildNodes())
                	xmlAttribute.appendChild(xmlAttributeSampleValue);
                xmlAttribute.appendChild(xmlAttributeRestrictions);
                xmlAttribute.appendChild(xmlAttributeApplicationGuidance);
                xmlAttribute.appendChild(xmlAttributeComment);

                if(!privateAttr)
                	xmlAttributeInfo.appendChild(xmlAttribute);
                else
                	xmlPrivateAttribute.appendChild(xmlAttribute);
                if(xmlPrivateAttribute != null)
        	    	xmlAttributeInfo.appendChild(xmlPrivateAttribute);
        	    xmlRoot1.appendChild(xmlAttributeInfo);
    	    	
 	    }
    	    if(xmlPrivateAttribute != null)
    	    	xmlAttributeInfo.appendChild(xmlPrivateAttribute);
    	    xmlRoot1.appendChild(xmlAttributeInfo);
           
    	    Vector<BehaviourNode> vBehaviour = mocNode.getBehaviour();

            if (vBehaviour.size() > 0) {
               xmlBehaviourInfo = doc.createElement("Behaviour_Info");

	       Collections.sort(vBehaviour, new Comparator<BehaviourNode>() {
	          public int compare(BehaviourNode o1, BehaviourNode o2) {
	             BehaviourNode bn1 = (BehaviourNode)o1;
	   	     BehaviourNode bn2 = (BehaviourNode)o2;
		     return bn1.getMethodName().compareTo(bn2.getMethodName());
	          }
	       });         
            }

            Vector<BehaviourNode> vPrivateBehav = new Vector<BehaviourNode>();
            Vector<BehaviourNode> vPublicBehav = new Vector<BehaviourNode>();
            for (int bc = 0; bc < vBehaviour.size(); bc++) {
            	BehaviourNode behav = (BehaviourNode) vBehaviour.get(bc);
            	if(behav.isPrivate)
            		vPrivateBehav.add(behav);
            	else
            		vPublicBehav.add(behav);
            }
            int bc = -1;
            xmlPrivateBehaviour = null;
            
            boolean privateBehav = false;
    	    for (int i = 0; i < vBehaviour.size(); i++) {	
    	    	
    	    	
    	    	BehaviourNode Behav; 
    	    	if(bc < vPublicBehav.size() - 1 && !privateBehav)
    	    	{	
    	    		bc++;
    	    		Behav = (BehaviourNode) vPublicBehav.get(bc);
    	    		
    	    		xmlBehaviour                    = doc.createElement(Behav.getMethodName()); 
    	    	}
    	    	else if(bc == vPublicBehav.size() - 1 && bc < vBehaviour.size() - 1 && !privateBehav){
    	    		bc = 0;
    	    		Behav = (BehaviourNode) vPrivateBehav.get(bc);
    	    		privateBehav = true;
    	    		xmlBehaviour                    = doc.createElement("Behaviour");
    	    		xmlPrivateBehaviour = doc.createElement("Private-Behaviour");
    	    	}
    	    	else{
    	    		bc++;
    	    		Behav = (BehaviourNode) vPrivateBehav.get(bc);
    	    		xmlBehaviour                    = doc.createElement("Behaviour");
    	    	}
    	    	

                xmlBehaviourMethodName          = doc.createElement("METHOD_NAME");
                xmlBehaviourMethodId            = doc.createElement("METHOD_ID");
                xmlBehaviourActionParameter     = doc.createElement("BEHAVIOUR_ACTION_PARAMETER");
                xmlBehaviourActionResult        = doc.createElement("BEHAVIOUR_ACTION_RESULT");
                xmlBehaviourTermCode            = doc.createElement("TERM_CODE");
    	    	xmlBehaviourReference           = doc.createElement("Reference");
                xmlBehaviourQual                = doc.createElement("Qual");
                xmlBehaviourRestrictions        = doc.createElement("BEHAVIOUR_RESTRICTIONS");
                xmlBehaviourComment             = doc.createElement("BEHAVIOUR_COMMENT");

    	    	BehaviourMethodName      = Behav.getMethodName();
    	    	BehaviourMethodId        = Behav.getMethodId();
    	    	BehaviourActionParameter = Behav.getBehaviourActionParameter();
    	    	BehaviourActionResult    = Behav.getBehaviourActionResult();
                BehaviourTermCode        = Behav.getBehaviourTermCode();
    	    	BehaviourReference       = Behav.getBehaviourReference();
    	    	BehaviourQual            = Behav.getBehaviourQual();
                BehaviourRestrictions    = Behav.getBehaviourRestrictions();
                BehaviourComment         = Behav.getBehaviourComment();

                if (BehaviourActionParameter == null) {
                   BehaviourActionParameter = "";
                }
                if (BehaviourActionResult == null) {
                   BehaviourActionResult = "";
                }
                if (BehaviourRestrictions == null) {
                   BehaviourRestrictions = "";
                }
                if (BehaviourComment == null) {
                   BehaviourComment = "";
                }

    	    	xmlBehaviourMethodName.appendChild(doc.createTextNode(BehaviourMethodName));
    	    	xmlBehaviourMethodId.appendChild(doc.createTextNode(BehaviourMethodId));
                xmlBehaviourActionParameter.appendChild(doc.createTextNode(BehaviourActionParameter));
                xmlBehaviourActionResult.appendChild(doc.createTextNode(BehaviourActionResult));
                xmlBehaviourTermCode.appendChild(doc.createTextNode(BehaviourTermCode));
    	    	xmlBehaviourReference.appendChild(doc.createTextNode(BehaviourReference));
    	    	xmlBehaviourQual.appendChild(doc.createTextNode(BehaviourQual));
                xmlBehaviourRestrictions.appendChild(doc.createTextNode(BehaviourRestrictions));
                xmlBehaviourComment.appendChild(doc.createTextNode(BehaviourComment));

    	    	xmlBehaviour.appendChild(xmlBehaviourMethodName);
    	    	xmlBehaviour.appendChild(xmlBehaviourMethodId);
                xmlBehaviour.appendChild(xmlBehaviourActionParameter);
                xmlBehaviour.appendChild(xmlBehaviourActionResult);
                xmlBehaviour.appendChild(xmlBehaviourTermCode);
    	    	xmlBehaviour.appendChild(xmlBehaviourReference);
    	    	xmlBehaviour.appendChild(xmlBehaviourQual);
                xmlBehaviour.appendChild(xmlBehaviourRestrictions);
                xmlBehaviour.appendChild(xmlBehaviourComment);

                if(!privateBehav)
                	xmlBehaviourInfo.appendChild(xmlBehaviour);
                else
                	xmlPrivateBehaviour.appendChild(xmlBehaviour);
                if(xmlPrivateBehaviour != null)
        	    	xmlBehaviourInfo.appendChild(xmlPrivateBehaviour);
        	    xmlRoot1.appendChild(xmlBehaviourInfo);
 	    }

    	    Vector<NotificationNode> vNotification = mocNode.getNotification();

            if (vNotification.size() > 0) {
               xmlNotificationInfo = doc.createElement("Notification_Info");
         
	       Collections.sort(vNotification, new Comparator<NotificationNode>() {
	          public int compare(NotificationNode o1, NotificationNode o2) {
	             NotificationNode nn1 = (NotificationNode)o1;
	   	     NotificationNode nn2 = (NotificationNode)o2;
                     return nn1.getNotificationName().compareTo(nn2.getNotificationName());
	          }
	       });	         
            }

            Vector<NotificationNode> vPrivateNoti = new Vector<NotificationNode>();
            Vector<NotificationNode> vPublicNoti = new Vector<NotificationNode>();
            for (int nc = 0; nc < vNotification.size(); nc++) {
            	NotificationNode Noti = (NotificationNode) vNotification.get(nc);
            	if(Noti.isPrivate)
            		vPrivateNoti.add(Noti);
            	else
            		vPublicNoti.add(Noti);
            }
            int nc = -1;
            xmlPrivateNotification = null;
            boolean privateNoti = false;
    	    for (int i = 0; i < vNotification.size(); i++) {	
    	    	
    	    	NotificationNode noti; 
    	    	if(nc < vPublicNoti.size() - 1 && !privateNoti)
    	    	{	
    	    		nc++;
    	    		noti = (NotificationNode) vPublicNoti.get(nc);
    	    		
    	    		xmlNotification                    = doc.createElement(noti.getNotificationName()); 
    	    	}
    	    	else if(nc == vPublicNoti.size() - 1 && nc < vNotification.size() - 1 && !privateNoti){
    	    		nc = 0;
    	    		noti = (NotificationNode) vPrivateNoti.get(nc);
    	    		privateNoti = true;
    	    		xmlNotification                    = doc.createElement("Notification");
    	    		xmlPrivateNotification = doc.createElement("Private-Notification");
    	    	}
    	    	else{
    	    		nc++;
    	    		noti = (NotificationNode) vPrivateNoti.get(nc);
    	    		xmlNotification                    = doc.createElement("Notification");
    	    	}
                
    	    	
                xmlNotificationName           = doc.createElement("NOTIFICATION_NAME");
                xmlNotificationId             = doc.createElement("NOTIFICATION_ID");
                xmlNotificationEventParameter = doc.createElement("NOTIFICATION_EVENT_PARAMETER");
                xmlNotificationTermCode       = doc.createElement("TERM_CODE");
    	    	xmlNotificationReference      = doc.createElement("Reference");
                xmlNotificationQual           = doc.createElement("Qual");
                xmlNotificationRestrictions   = doc.createElement("NOTIFICATION_RESTRICTIONS");
                xmlNotificationComment        = doc.createElement("NOTIFICATION_COMMENT");

    	    	NotificationName           = noti.getNotificationName();
    	    	NotificationId             = noti.getNotificationId();
                NotificationEventParameter = noti.getNotificationEventParameter();
                NotificationTermCode       = noti.getNotificationTermCode();
    	    	NotificationReference      = noti.getNotificationReference();
    	    	NotificationQual           = noti.getNotificationQual();
                NotificationRestrictions   = noti.getNotificationRestrictions();
                NotificationComment        = noti.getNotificationComment();

                if (NotificationEventParameter == null) {
                   NotificationEventParameter = "";
                }
                if (NotificationRestrictions == null) {
                   NotificationRestrictions = "";
                }
                if (NotificationComment == null) {
                   NotificationComment = "";
                }

    	    	xmlNotificationName.appendChild(doc.createTextNode(NotificationName));
    	    	xmlNotificationId.appendChild(doc.createTextNode(NotificationId));
                xmlNotificationEventParameter.appendChild(doc.createTextNode(NotificationEventParameter));
                xmlNotificationTermCode.appendChild(doc.createTextNode(NotificationTermCode));
    	    	xmlNotificationReference.appendChild(doc.createTextNode(NotificationReference));
    	    	xmlNotificationQual.appendChild(doc.createTextNode(NotificationQual));
                xmlNotificationRestrictions.appendChild(doc.createTextNode(NotificationRestrictions));
                xmlNotificationComment.appendChild(doc.createTextNode(NotificationComment));

    	    	xmlNotification.appendChild(xmlNotificationName);
    	    	xmlNotification.appendChild(xmlNotificationId);
                xmlNotification.appendChild(xmlNotificationEventParameter);
    	    	xmlNotification.appendChild(xmlNotificationTermCode);
    	    	xmlNotification.appendChild(xmlNotificationReference);
    	    	xmlNotification.appendChild(xmlNotificationQual);
                xmlNotification.appendChild(xmlNotificationRestrictions);
                xmlNotification.appendChild(xmlNotificationComment);

                if(!privateNoti)
                	xmlNotificationInfo.appendChild(xmlNotification);
                else
                	xmlPrivateNotification.appendChild(xmlNotification);
                if(xmlPrivateNotification != null)
        	    	xmlNotificationInfo.appendChild(xmlPrivateNotification);
        	    xmlRoot1.appendChild(xmlNotificationInfo);
 	    }

            if (!node.isLeaf()) {
               Enumeration chldrn = node.children();



        ArrayList<DefaultMutableTreeNode> rootList = new ArrayList<DefaultMutableTreeNode>();       
        Enumeration childrn = (Enumeration) node.children();
        while (childrn.hasMoreElements()) {               
           rootList.add((DefaultMutableTreeNode)childrn.nextElement());
        } 

               Collections.sort(rootList, new Comparator<DefaultMutableTreeNode>() {
	          public int compare(DefaultMutableTreeNode o1, DefaultMutableTreeNode o2) {
	             DefaultMutableTreeNode dfmtnString1 = (DefaultMutableTreeNode)o1;
	             DefaultMutableTreeNode dfmtnString2 = (DefaultMutableTreeNode)o2;
	             return dfmtnString1.toString().compareTo(dfmtnString2.toString());
	          }
	       });
               chldrn = Collections.enumeration(rootList); 
               while (chldrn.hasMoreElements()) {
                  DefaultMutableTreeNode tnd = (DefaultMutableTreeNode) chldrn.nextElement();
                  xmlRoot1.appendChild(generateXMLNode(tnd));                  
               }
            } 
            return xmlRoot1;
    }
}
