*/
		public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
	          if (pageIndex > 0) {
	            return(NO_SUCH_PAGE);
	          } else {
	            Graphics2D g2d = (Graphics2D)g;
	            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
	            double fHeight = pageFormat.getImageableHeight();
	            double fWidth = pageFormat.getImageableWidth();
	            int xMax = 1;
	            int yMax = 1;
	            for (int iNode = 0; iNode < m_BayesNet.getNrOfNodes(); iNode++) {
	            	if (xMax < m_BayesNet.getPositionX(iNode)) {
	            		xMax = m_BayesNet.getPositionX(iNode);
	            	}
	            	if (yMax < m_BayesNet.getPositionY(iNode)) {
	            		yMax = m_BayesNet.getPositionY(iNode);
	            	}
	            }
	            double fCurrentScale = m_fScale;
	            xMax += m_nPaddedNodeWidth + 100;
	            if (fWidth/xMax < fHeight/yMax) {
	            	m_fScale = fWidth/xMax; 
	            } else {
	            	m_fScale = fHeight/yMax;
	            }
	            
	            // Turn off double buffering
	            paint(g2d);
	            m_fScale = fCurrentScale;
	            // Turn double buffering back on
	            return(PAGE_EXISTS);
	          }
	        } // print
				
	} // class GraphPanel

	/**
	 * Table Model for the Table for editing CPTs
	 */
	private class GraphVisualizerTableModel extends AbstractTableModel {

		/** for serialization */
		private static final long serialVersionUID = -4789813491347366596L;
		/** labels for the columns */
		final String [] m_sColumnNames;
		/** probability table data **/
		final double [][] m_fProbs;
		/** nr of node for currently editted CPT */
		int m_iNode;

		public GraphVisualizerTableModel(int iNode) {
			m_iNode = iNode;
			double [][] probs = m_BayesNet.getDistribution(iNode);
			m_fProbs = new double[probs.length][probs[0].length];
			for (int i = 0; i < probs.length; i++) {
				for (int j = 0; j < probs[0].length; j++) {
					m_fProbs[i][j] = probs[i][j];
				}
			}
			m_sColumnNames = m_BayesNet.getValues(iNode);
		} // c'tor

		/** method that generates random CPTs
		 */
		public void randomize() {
			int nProbs = m_fProbs[0].length;
			Random random = new Random();
			for (int i = 0; i < m_fProbs.length; i++) {
				// get random nrs
				for (int j = 0; j < nProbs-1; j++) {
					m_fProbs[i][j] = random.nextDouble();
				}
				// sort
				for (int j = 0; j < nProbs-1; j++) {
					for (int k = j+1; k < nProbs-1; k++) {
						if (m_fProbs[i][j] > m_fProbs[i][k]) {
							double h = m_fProbs[i][j]; 
							m_fProbs[i][j] = m_fProbs[i][k];
							m_fProbs[i][k] = h;
						}
					}
				}
				double sum = m_fProbs[i][0];
				for (int j = 1; j < nProbs-1; j++) {
					m_fProbs[i][j] = m_fProbs[i][j] - sum;
					sum += m_fProbs[i][j]; 
				}
				m_fProbs[i][nProbs - 1] = 1.0 - sum;
			}
		} // randomize
		
		public void setData() {}

		/** return nr of colums */
		public int getColumnCount() {
			return m_sColumnNames.length;
		}

		/** return nr of rows */
		public int getRowCount() {
			return m_fProbs.length;
		}

		/** return name of specified colum 
		 * @param iCol index of the column
		 */
		public String getColumnName(int iCol) {
			return m_sColumnNames[iCol];
		}
		/** return data point 
		 * @param iRow index of row in table
		 * @param iCol index of column in table
		 */
		public Object getValueAt(int iRow, int iCol) {
			return new Double(m_fProbs[iRow][iCol]);
		}

		/** Set data point, assigns value to CPT entry
		 * specified by row and column. The remainder of the
		 * CPT is normalized so that the values add up to 1.
		 * IF a value below zero of over 1 is given, no changes
		 * take place.
		 * @param oProb data point
		 * @param iRow index of row in table
		 * @param iCol index of column in table
		 */
		public void setValueAt(Object oProb, int iRow, int iCol) {
			Double fProb = (Double) oProb;
			if (fProb < 0 || fProb > 1) {
				return;
			}
			m_fProbs[iRow][iCol] = (double) fProb;
			double sum = 0;
			for (int i = 0; i < m_fProbs[iRow].length; i++) {
				sum += m_fProbs[iRow][i];
			}

			if (sum > 1) {
				// handle overflow
				int i = m_fProbs[iRow].length - 1;
				while (sum > 1) {
					if (i != iCol) {
						if (m_fProbs[iRow][i] > sum - 1) {
							m_fProbs[iRow][i] -= sum - 1;
							sum = 1;
						} else {
							sum -= m_fProbs[iRow][i];
							m_fProbs[iRow][i] = 0;
						}
					}
					i--;
				}
			} else {
				// handle underflow
				int i = m_fProbs[iRow].length - 1;
				while (sum < 1) {
					if (i != iCol) {
						m_fProbs[iRow][i] += 1 - sum;
						sum = 1;
					}
					i--;
				}

			}
			validate();
		} // setData

		/*
		 * JTable uses this method to determine the default renderer/ editor for
		 * each cell.
		 */
		public Class getColumnClass(int c) {
			return getValueAt(0, c).getClass();
		}

		/*
		 * Implemented this to make sure the table is uneditable.
		 */
		public boolean isCellEditable(int row, int col) {
			return true;
		}
	} // class GraphVisualizerTableModel

	/**
	 * Listener class for processing mouseClicked
	 */
	private class GraphVisualizerMouseListener extends MouseAdapter {

		/** A left mouseclick on a node adds node to selection (depending
		 * on shift and ctrl keys).
		 * A right mouseclick on a node pops up menu with actions to be
		 * performed on the node.
		 * A right mouseclick outside another node pops up menu.
		 */
		public void mouseClicked(MouseEvent me) {
			int x, y;

			Rectangle r = new Rectangle(0, 0, (int) (m_nPaddedNodeWidth * m_fScale), (int) (m_nNodeHeight * m_fScale));
			x = me.getX();
			y = me.getY();

			for (int iNode = 0; iNode < m_BayesNet.getNrOfNodes(); iNode++) {
				r.x = (int) (m_BayesNet.getPositionX(iNode) * m_fScale);
				r.y = (int) (m_BayesNet.getPositionY(iNode) * m_fScale);
				if (r.contains(x, y)) {
					m_nCurrentNode = iNode;					
					if (me.getButton() == MouseEvent.BUTTON3) {
						handleRightNodeClick(me);
					}
					if (me.getButton() == MouseEvent.BUTTON1) {
						if ((me.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) != 0) {
							m_Selection.toggleSelection(m_nCurrentNode);
						} else if ((me.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0) {
							m_Selection.addToSelection(m_nCurrentNode);
						} else {
							m_Selection.clear();
							m_Selection.addToSelection(m_nCurrentNode);
						}
						repaint();
					}
					return;
				}
			}
			if (me.getButton() == MouseEvent.BUTTON3) {
				handleRightClick(me, (int)(x/m_fScale), (int)(y/m_fScale));
			}
		} // mouseClicked
		
		/* update selection
		 *  (non-Javadoc)
		 * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
		 */
		public void mouseReleased(MouseEvent me) {
	    	if (m_nSelectedRect != null) {
				if ((me.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) != 0) {
					m_Selection.toggleSelection(m_nSelectedRect);
				} else if ((me.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0) {
					m_Selection.addToSelection(m_nSelectedRect);
				} else {
					m_Selection.clear();
		    		m_Selection.addToSelection(m_nSelectedRect);
				}
	    		m_nSelectedRect = null;
	    		repaint();
	    	}
	    } // mouseReleased

		/** position clicked on */
	    int m_nPosX = 0, m_nPosY = 0;
	    
	    /* pop up menu with actions that apply in general or to selection (if any exists)
	     */
	    void handleRightClick(MouseEvent me, int nPosX, int nPosY) {
	
			ActionListener act = new ActionListener() {
				public void actionPerformed(ActionEvent ae) {
					if (ae.getActionCommand().equals("Add node")) {
						a_addnode.addNode(m_nPosX, m_nPosY);
						return;
					}
					repaint();
				}
			};
			JPopupMenu popupMenu = new JPopupMenu("Choose a value");

			JMenuItem addNodeItem = new JMenuItem("Add node");
			addNodeItem.addActionListener(act);
			popupMenu.add(addNodeItem);

			FastVector selected = m_Selection.getSelected();
			JMenu addArcMenu = new JMenu("Add parent");
			popupMenu.add(addArcMenu);
			if (selected.size() == 0) {
				addArcMenu.setEnabled(false);
			} else {
			int nNodes = m_BayesNet.getNrOfNodes();
			boolean[] isNotAllowedAsParent = new boolean[nNodes];
			// prevent it being a parent of itself
			for (int iNode = 0; iNode < selected.size(); iNode++) {
				isNotAllowedAsParent[(Integer) selected.elementAt(iNode)] = true;
			}
			// prevent a descendant being a parent, since it introduces cycles
			for (int i = 0; i < nNodes; i++) {
				for (int iNode = 0; iNode < nNodes; iNode++) {
					for (int iParent = 0; iParent < m_BayesNet.getNrOfParents(iNode); iParent++) {
						if (isNotAllowedAsParent[m_BayesNet.getParent(iNode, iParent)]) {
							isNotAllowedAsParent[iNode] = true;
						}
					}
				}
			}
			// prevent nodes that are already a parent
			for (int iNode = 0; iNode < selected.size(); iNode++) {
				int nNode = (Integer) selected.elementAt(iNode);
				for (int iParent = 0; iParent < m_BayesNet.getNrOfParents(nNode); iParent++) {
					isNotAllowedAsParent[m_BayesNet.getParent(nNode, iParent)] = true;
				}
			}
			ActionListener addParentAction = new ActionListener() {
				public void actionPerformed(ActionEvent ae) {
					try {
						m_BayesNet.addArc(ae.getActionCommand(), m_Selection.getSelected());
						m_jStatusBar.setText(m_BayesNet.lastActionMsg());
						updateStatus();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			// count nr of remaining candidates
			int nCandidates = 0;
			for (int i = 0; i < nNodes; i++) {
				if (!isNotAllowedAsParent[i]) {
					JMenuItem item = new JMenuItem(m_BayesNet.getNodeName(i));
					item.addActionListener(addParentAction);
					addArcMenu.add(item);
					nCandidates++;
				}
			}
			if (nCandidates == 0) {
				addArcMenu.setEnabled(false);
			}
			}
			m_nPosX = nPosX;
			m_nPosY = nPosY;
			popupMenu.setLocation(me.getX(), me.getY());
			popupMenu.show(m_GraphPanel, me.getX(), me.getY());
	    } // handleRightClick
		
	    /* pop up menu with actions that apply to node that was clicked on
	     */
	    void handleRightNodeClick(MouseEvent me) {
			m_Selection.clear();
			repaint();
			ActionListener renameValueAction = new ActionListener() {
				public void actionPerformed(ActionEvent ae) {
					renameValue(m_nCurrentNode, ae.getActionCommand());
				}
			};
			ActionListener delValueAction = new ActionListener() {
				public void actionPerformed(ActionEvent ae) {
					delValue(m_nCurrentNode, ae.getActionCommand());
				}
			};
			ActionListener addParentAction = new ActionListener() {
				public void actionPerformed(ActionEvent ae) {
					try {
						m_BayesNet.addArc(ae.getActionCommand(), m_BayesNet.getNodeName(m_nCurrentNode));
						m_jStatusBar.setText(m_BayesNet.lastActionMsg());
						updateStatus();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			ActionListener delParentAction = new ActionListener() {
				public void actionPerformed(ActionEvent ae) {
					deleteArc(m_nCurrentNode, ae.getActionCommand());
				}
			};
			ActionListener delChildAction = new ActionListener() {
				public void actionPerformed(ActionEvent ae) {
					deleteArc(ae.getActionCommand(), m_nCurrentNode);
				}
			};
			ActionListener setAvidenceAction = new ActionListener() {
				public void actionPerformed(ActionEvent ae) {
					try {
						String [] outcomes = m_BayesNet.getValues(m_nCurrentNode);
						int iValue = 0;
						while (iValue < outcomes.length && !outcomes[iValue].equals(ae.getActionCommand())) {
							iValue++;
						}

						if (iValue == outcomes.length) {
							iValue = -1;
						}
						if (iValue < outcomes.length) {
						    m_jStatusBar.setText("Set evidence for " + m_BayesNet.getNodeName(m_nCurrentNode));
								if (m_BayesNet.getEvidence(m_nCurrentNode) < 0 && iValue >= 0) {
									m_BayesNet.setEvidence(m_nCurrentNode, iValue);
									m_marginCalculatorWithEvidence.setEvidence(m_nCurrentNode, iValue);
								} else {
									m_BayesNet.setEvidence(m_nCurrentNode, iValue);
									SerializedObject so = new SerializedObject(m_marginCalculator);
									m_marginCalculatorWithEvidence = (MarginCalculator) so.getObject();
									for (int iNode = 0; iNode < m_BayesNet.getNrOfNodes(); iNode++) {
										if (m_BayesNet.getEvidence(iNode) >= 0) {
											m_marginCalculatorWithEvidence.setEvidence(iNode, m_BayesNet.getEvidence(iNode));
										}
									}
								}
							for (int iNode = 0; iNode < m_BayesNet.getNrOfNodes(); iNode++) {
								m_BayesNet.setMargin(iNode, m_marginCalculatorWithEvidence.getMargin(iNode));
							}
						}
						} catch (Exception e) {
							e.printStackTrace();
						}
						repaint();
				}
			};
			
			ActionListener act = new ActionListener() {
				public void actionPerformed(ActionEvent ae) {
					if (ae.getActionCommand().equals("Rename")) {
						renameNode(m_nCurrentNode);
						return;
					}
					if (ae.getActionCommand().equals("Add parent")) {
						addArcInto(m_nCurrentNode);
						return;
					}
					if (ae.getActionCommand().equals("Add value")) {
						addValue();
						return;
					}
					if (ae.getActionCommand().equals("Delete node")) {
						deleteNode(m_nCurrentNode);
						return;
					}
					if (ae.getActionCommand().equals("Edit CPT")) {
						editCPT(m_nCurrentNode);
						return;
					}
					repaint();
				}
			};
			try {
			JPopupMenu popupMenu = new JPopupMenu("Choose a value");

			JMenu setEvidenceMenu = new JMenu("Set evidence");
			String [] outcomes = m_BayesNet.getValues(m_nCurrentNode);
			for (int iValue = 0; iValue < outcomes.length; iValue++) {
				JMenuItem item = new JMenuItem(outcomes[iValue]);
				item.addActionListener(setAvidenceAction);
				setEvidenceMenu.add(item);
			}
			setEvidenceMenu.addSeparator();
			JMenuItem item = new JMenuItem("Clear");
			item.addActionListener(setAvidenceAction);
			setEvidenceMenu.add(item);
			popupMenu.add(setEvidenceMenu);

			setEvidenceMenu.setEnabled(m_bViewMargins);

			popupMenu.addSeparator();

			JMenuItem renameItem = new JMenuItem("Rename");
			renameItem.addActionListener(act);
			popupMenu.add(renameItem);

			JMenuItem delNodeItem = new JMenuItem("Delete node");
			delNodeItem.addActionListener(act);
			popupMenu.add(delNodeItem);

			JMenuItem editCPTItem = new JMenuItem("Edit CPT");
			editCPTItem.addActionListener(act);
			popupMenu.add(editCPTItem);

			popupMenu.addSeparator();
			
			JMenu addArcMenu = new JMenu("Add parent");
			popupMenu.add(addArcMenu);
			int nNodes = m_BayesNet.getNrOfNodes();
			boolean[] isNotAllowedAsParent = new boolean[nNodes];
			// prevent it being a parent of itself
			isNotAllowedAsParent[m_nCurrentNode] = true;
			// prevent a descendant being a parent, since it introduces cycles
			for (int i = 0; i < nNodes; i++) {
				for (int iNode = 0; iNode < nNodes; iNode++) {
					for (int iParent = 0; iParent < m_BayesNet.getNrOfParents(iNode); iParent++) {
						if (isNotAllowedAsParent[m_BayesNet.getParent(iNode, iParent)]) {
							isNotAllowedAsParent[iNode] = true;
						}
					}
				}
			}
			// prevent nodes that are already a parent
			for (int iParent = 0; iParent < m_BayesNet.getNrOfParents(m_nCurrentNode); iParent++) {
				isNotAllowedAsParent[m_BayesNet.getParent(m_nCurrentNode, iParent)] = true;
			}
			// count nr of remaining candidates
			int nCandidates = 0;
			for (int i = 0; i < nNodes; i++) {
				if (!isNotAllowedAsParent[i]) {
					item = new JMenuItem(m_BayesNet.getNodeName(i));
					item.addActionListener(addParentAction);
					addArcMenu.add(item);
					nCandidates++;
				}
			}
			if (nCandidates == 0) {
				addArcMenu.setEnabled(false);
			}
									
			JMenu delArcMenu = new JMenu("Delete parent");
			popupMenu.add(delArcMenu);
			if (m_BayesNet.getNrOfParents(m_nCurrentNode) == 0) {
				delArcMenu.setEnabled(false);
			}
			for (int iParent = 0; iParent < m_BayesNet.getNrOfParents(m_nCurrentNode); iParent++) {
				item = new JMenuItem(m_BayesNet.getNodeName(m_BayesNet.getParent(m_nCurrentNode, iParent)));
				item.addActionListener(delParentAction);
				delArcMenu.add(item);
			}
			JMenu delChildMenu = new JMenu("Delete child");
			popupMenu.add(delChildMenu);
			FastVector nChildren = m_BayesNet.getChildren(m_nCurrentNode); 
			if (nChildren.size() == 0) {
				delChildMenu.setEnabled(false);
			}
			for (int iChild = 0; iChild < nChildren.size(); iChild++) {
				item = new JMenuItem(m_BayesNet.getNodeName((Integer) nChildren.elementAt(iChild)));
				item.addActionListener(delChildAction);
				delChildMenu.add(item);
			}

			popupMenu.addSeparator();

			JMenuItem addValueItem = new JMenuItem("Add value");
			addValueItem.addActionListener(act);
			popupMenu.add(addValueItem);

			JMenu renameValue = new JMenu("Rename value");
			popupMenu.add(renameValue);
			for (int iValue = 0; iValue < outcomes.length; iValue++) {
				item = new JMenuItem(outcomes[iValue]);
				item.addActionListener(renameValueAction);
				renameValue.add(item);
			}

			JMenu delValue = new JMenu("Delete value");
			popupMenu.add(delValue);
			if (m_BayesNet.getCardinality(m_nCurrentNode) <= 2) {
				delValue.setEnabled(false);
			}
			for (int iValue = 0; iValue < outcomes.length; iValue++) {
				JMenuItem delValueItem = new JMenuItem(outcomes[iValue]);
				delValueItem.addActionListener(delValueAction);
				delValue.add(delValueItem);
			}
			
			popupMenu.setLocation(me.getX(), me.getY());
			popupMenu.show(m_GraphPanel, me.getX(), me.getY());
			} catch (Exception e) {
				e.printStackTrace();
			}
		} // handleRightNodeClick
	} // class GraphVisualizerMouseListener

	/**
	 * private class for handling mouseMoved events to highlight nodes if the
	 * the mouse is moved on one, move it around or move selection around
	 */
	private class GraphVisualizerMouseMotionListener extends MouseMotionAdapter {

		/* last node moved over. Used for turning highlight on and off */
		int m_nLastNode = -1;
		/* current mouse position clicked */
		int m_nPosX, m_nPosY;

		/* identify the node under the mouse
		 * @returns node index of node under mouse, or -1 if there is no such node 
		 */
		int getGraphNode(MouseEvent me) {
			m_nPosX = m_nPosY  = 0;

			Rectangle r = new Rectangle(0, 0, (int) (m_nPaddedNodeWidth * m_fScale), (int) (m_nNodeHeight * m_fScale));
			m_nPosX += me.getX();
			m_nPosY += me.getY();

			for (int iNode = 0; iNode < m_BayesNet.getNrOfNodes(); iNode++) {				
				r.x = (int) (m_BayesNet.getPositionX(iNode) * m_fScale);
				r.y = (int) (m_BayesNet.getPositionY(iNode) * m_fScale);
				if (r.contains(m_nPosX, m_nPosY)) {
					return iNode;
				}
			}
			return -1;
		} // getGraphNode

		/* handle mouse dragging event
		 *  (non-Javadoc)
		 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
		 */
		public void mouseDragged(MouseEvent me) {
			if (m_nSelectedRect != null) {
				m_nSelectedRect.width = me.getPoint().x - m_nSelectedRect.x;
				m_nSelectedRect.height = me.getPoint().y - m_nSelectedRect.y;
				repaint();
				return;
			}
			int iNode = getGraphNode(me);
			if (iNode >= 0) {
				if (m_Selection.getSelected().size() > 0) {
					if (m_Selection.getSelected().contains(iNode)) {
						m_BayesNet.setPosition(iNode, (int) ((m_nPosX / m_fScale - m_nPaddedNodeWidth / 2)),
							(int) ((m_nPosY / m_fScale - m_nNodeHeight / 2)), m_Selection.getSelected());
					} else {
						m_Selection.clear();
						m_BayesNet.setPosition(iNode, (int) ((m_nPosX / m_fScale - m_nPaddedNodeWidth / 2)),
								(int) ((m_nPosY / m_fScale - m_nNodeHeight / 2)));
					}
					repaint();
				} else {
					m_BayesNet.setPosition(iNode, (int) ((m_nPosX / m_fScale - m_nPaddedNodeWidth / 2)),
						(int) ((m_nPosY / m_fScale - m_nNodeHeight / 2)));
				}
			    m_jStatusBar.setText(m_BayesNet.lastActionMsg());
				a_undo.setEnabled(true);
				a_redo.setEnabled(false);
				m_GraphPanel.highLight(iNode);
			}
			if (iNode < 0) {
				if (m_nLastNode >= 0) {
					m_GraphPanel.repaint();
					m_nLastNode = -1;
				} else {
					m_nSelectedRect = new Rectangle(me.getPoint().x, me.getPoint().y, 1, 1);
					m_GraphPanel.repaint();
				}
			}
		} // mouseDragged
		
		/* handles mouse move event
		 *  (non-Javadoc)
		 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
		 */
		public void mouseMoved(MouseEvent me) {
			int iNode = getGraphNode(me);
			if (iNode >= 0) {
				if (iNode != m_nLastNode) {
					m_GraphPanel.highLight(iNode);
					if (m_nLastNode >= 0) {
						m_GraphPanel.highLight(m_nLastNode);
					}
					m_nLastNode = iNode;
				}
			}
			if (iNode < 0 && m_nLastNode >= 0) {
				m_GraphPanel.repaint();
				m_nLastNode = -1;
			}
		} // mouseMoved
		
	} // class GraphVisualizerMouseMotionListener

	/* apply graph layout algorithm to Bayesian network 
	 */
	void layoutGraph() {
		if (m_BayesNet.getNrOfNodes() == 0) {
			return;
		}
		try {
			FastVector m_nodes = new FastVector();
			FastVector m_edges = new FastVector();
			BIFParser bp = new BIFParser(m_BayesNet.toXMLBIF03(), m_nodes, m_edges);
			bp.parse();
			updateStatus();
			m_layoutEngine = new HierarchicalBCEngine(m_nodes, m_edges, m_nPaddedNodeWidth, m_nNodeHeight);
			m_layoutEngine.addLayoutCompleteEventListener(this);
			m_layoutEngine.layoutGraph();
		} catch (Exception e) {
			e.printStackTrace();
		}
	} // layoutGraph
	
	/* Update status of various items that need regular updating
	 * such as enabled status of some menu items, marginal distributions
	 * if shown, repainting of graph.
	 */
	void updateStatus() {
		a_undo.setEnabled(m_BayesNet.canUndo());
		a_redo.setEnabled(m_BayesNet.canRedo());

		a_datagenerator.setEnabled(m_BayesNet.getNrOfNodes() > 0);

		if (!m_bViewMargins && !m_bViewCliques) {
			repaint();
			return;
		}

		try {
			m_marginCalculator = new MarginCalculator();
			m_marginCalculator.calcMargins(m_BayesNet);
			SerializedObject so = new SerializedObject(m_marginCalculator);
			m_marginCalculatorWithEvidence = (MarginCalculator) so.getObject();
			for (int iNode = 0; iNode < m_BayesNet.getNrOfNodes(); iNode++) {
				if (m_BayesNet.getEvidence(iNode) >= 0) {
					m_marginCalculatorWithEvidence.setEvidence(iNode, m_BayesNet.getEvidence(iNode));
				}
			}
			for (int iNode = 0; iNode < m_BayesNet.getNrOfNodes(); iNode++) {
				m_BayesNet.setMargin(iNode, m_marginCalculatorWithEvidence.getMargin(iNode));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		repaint();
	} // updateStatus

	/* add arc with node iChild as child. 
	 * This pops up a selection list with potential parents for the child.
	 * All decendants and current parents are excluded from the list as is
	 * the child node itself.
	 * @param iChild index of the node for which to add an arc
	 */
	void addArcInto(int iChild) {
		String sChild = m_BayesNet.getNodeName(iChild);
		try {
			int nNodes = m_BayesNet.getNrOfNodes();
			boolean[] isNotAllowedAsParent = new boolean[nNodes];
			// prevent it being a parent of itself
			isNotAllowedAsParent[iChild] = true;
			// prevent a descendant being a parent, since it introduces cycles
			for (int i = 0; i < nNodes; i++) {
				for (int iNode = 0; iNode < nNodes; iNode++) {
					for (int iParent = 0; iParent < m_BayesNet.getNrOfParents(iNode); iParent++) {
						if (isNotAllowedAsParent[m_BayesNet.getParent(iNode, iParent)]) {
							isNotAllowedAsParent[iNode] = true;
						}
					}
				}
			}
			// prevent nodes that are already a parent
			for (int iParent = 0; iParent < m_BayesNet.getNrOfParents(iChild); iParent++) {
				isNotAllowedAsParent[m_BayesNet.getParent(iChild, iParent)] = true;
			}
			// count nr of remaining candidates
			int nCandidates = 0;
			for (int i = 0; i < nNodes; i++) {
				if (!isNotAllowedAsParent[i]) {
					nCandidates++;
				}
			}
			if (nCandidates == 0) {
				JOptionPane.showMessageDialog(null, "No potential parents available for this node (" + sChild
						+ "). Choose another node as child node.");
				return;
			}
			String[] options = new String[nCandidates];
			int k = 0;
			for (int i = 0; i < nNodes; i++) {
				if (!isNotAllowedAsParent[i]) {
					options[k++] = m_BayesNet.getNodeName(i);
				}
			}
			String sParent = (String) JOptionPane.showInputDialog(null, "Select parent node for " + sChild, "Nodes", 0,
					null, options, options[0]);
			if (sParent == null || sParent.equals("")) {
				return;
			}
			// update all data structures
			m_BayesNet.addArc(sParent, sChild);
		    m_jStatusBar.setText(m_BayesNet.lastActionMsg());
		    updateStatus();
		} catch (Exception e) {
			e.printStackTrace();
		}
	} // addArcInto

	/* deletes arc from node with name sParent into child with index iChild
	 * 
	 */
	void deleteArc(int iChild, String sParent) {
		try {
			m_BayesNet.deleteArc(m_BayesNet.getNode(sParent), iChild);
		    m_jStatusBar.setText(m_BayesNet.lastActionMsg());
		} catch (Exception e) {
			e.printStackTrace();
		}
		updateStatus();
	} // deleteArc
	
	/* deletes arc from node with index iParent into child with name sChild
	 * 
	 */
	void deleteArc(String sChild, int iParent) {
		try {
			m_BayesNet.deleteArc(iParent, m_BayesNet.getNode(sChild));
		    m_jStatusBar.setText(m_BayesNet.lastActionMsg());
		} catch (Exception e) {
			e.printStackTrace();
		}
		updateStatus();
	} // deleteArc

	/* deletes arc. Pops up list of arcs listed in 'options' as 
	 * "<Node1> -> <Node2>".
	 */
	void deleteArc(String[] options) {
		String sResult = (String) JOptionPane.showInputDialog(null, "Select arc to delete", "Arcs", 0, null, options,
				options[0]);
		if (sResult != null && !sResult.equals("")) {
			int nPos = sResult.indexOf(" -> ");
			String sParent = sResult.substring(0, nPos);
			String sChild = sResult.substring(nPos + 4);
			try {
				m_BayesNet.deleteArc(sParent, sChild);
			    m_jStatusBar.setText(m_BayesNet.lastActionMsg());
			} catch (Exception e) {
				e.printStackTrace();
			}
			updateStatus();
		}
	} // deleteArc

	/* Rename node with index nTargetNode.
	 * Pops up window that allwos for entering a new name.
	 */
	void renameNode(int nTargetNode) {
		String sName = (String) JOptionPane.showInputDialog(null, m_BayesNet.getNodeName(nTargetNode), "New name for node",
				JOptionPane.OK_CANCEL_OPTION);
		if (sName == null || sName.equals("")) {
			return;
		}
		try {
			while (m_BayesNet.getNode2(sName) >= 0) {
				sName = (String) JOptionPane.showInputDialog(null, "Cannot rename to " + sName
						+ ".\nNode with that name already exists.");
				if (sName == null || sName.equals("")) {
					return;
				}
			}
			m_BayesNet.setNodeName(nTargetNode, sName);
		    m_jStatusBar.setText(m_BayesNet.lastActionMsg());
		} catch (Exception e) {
			e.printStackTrace();
		}
		repaint();
	} // renameNode

	/* Rename value with name sValeu of a node with index nTargetNode.
	 * Pops up window that allows entering a new name.
	 */
	void renameValue(int nTargetNode, String sValue) {
		String sNewValue = (String) JOptionPane.showInputDialog(null, "New name for value " + sValue, "Node "
				+ m_BayesNet.getNodeName(nTargetNode), JOptionPane.OK_CANCEL_OPTION);
		if (sNewValue == null || sNewValue.equals("")) {
			return;
		}
		m_BayesNet.renameNodeValue(nTargetNode, sValue, sNewValue);
	    m_jStatusBar.setText(m_BayesNet.lastActionMsg());
		a_undo.setEnabled(true);
		a_redo.setEnabled(false);
		repaint();
	} // renameValue

	/* delete a single node with index iNode */
	void deleteNode(int iNode) {
		try {
			m_BayesNet.deleteNode(iNode);
		    m_jStatusBar.setText(m_BayesNet.lastActionMsg());
		} catch (Exception e) {
			e.printStackTrace();
		}
		updateStatus();
	} // deleteNode

	/* Add a value to currently selected node.
	 * Shows window that allows to enter the name of the value. 
	 */
	void addValue() {
		//GraphNode n = (GraphNode) m_nodes.elementAt(m_nCurrentNode);
		String sValue = "Value" + (m_BayesNet.getCardinality(m_nCurrentNode) + 1);
		String sNewValue = (String) JOptionPane.showInputDialog(null, "New value " + sValue, "Node " + m_BayesNet.getNodeName(m_nCurrentNode),
				JOptionPane.OK_CANCEL_OPTION);
		if (sNewValue == null || sNewValue.equals("")) {
			return;
		}
		try {
			m_BayesNet.addNodeValue(m_nCurrentNode, sNewValue);
		    m_jStatusBar.setText(m_BayesNet.lastActionMsg());
			//n.outcomes = m_BayesNet.getValues(m_nCurrentNode);
			//for (int iNode = 0; iNode < m_BayesNet.getNrOfNodes(); iNode++) {
			//	n = (GraphNode) m_nodes.elementAt(iNode);
			//	n.probs = m_BayesNet.getDistribution(iNode);
			//}
		} catch (Exception e) {
			e.printStackTrace();
		}
		updateStatus();
	} // addValue

	/* remove value with name sValue from the node with index nTargetNode
	 */
	void delValue(int nTargetNode, String sValue) {
		try {
			m_BayesNet.delNodeValue(nTargetNode, sValue);
		    m_jStatusBar.setText(m_BayesNet.lastActionMsg());
		} catch (Exception e) {
			e.printStackTrace();
		}
		updateStatus();
	} // delValue

	/* Edits CPT of node with index nTargetNode. 
	 * Pops up table with probability table that the user can change or just view.
	 */
	void editCPT(int nTargetNode) {
		m_nCurrentNode = nTargetNode;
		final GraphVisualizerTableModel tm = new GraphVisualizerTableModel(nTargetNode);

		JTable jTblProbs = new JTable(tm); 

		JScrollPane js = new JScrollPane(jTblProbs);

		int nParents = m_BayesNet.getNrOfParents(nTargetNode);
		if (nParents > 0) {
			GridBagConstraints gbc = new GridBagConstraints();
			JPanel jPlRowHeader = new JPanel(new GridBagLayout());

			// indices of the parent nodes in the Vector
			int[] idx = new int[nParents];
			// max length of values of each parent
			int[] lengths = new int[nParents];

			// Adding labels for rows
			gbc.anchor = GridBagConstraints.NORTHWEST;
			gbc.fill = GridBagConstraints.HORIZONTAL;
			gbc.insets = new Insets(0, 1, 0, 0);
			int addNum = 0, temp = 0;
			boolean dark = false;
			while (true) {
				gbc.gridwidth = 1;
				for (int k = 0; k < nParents; k++) {
					int iParent2 = m_BayesNet.getParent(nTargetNode, k); 
					JLabel lb = new JLabel(m_BayesNet.getValueName(iParent2,idx[k]));
					lb.setFont(new Font("Dialog", Font.PLAIN, 12));
					lb.setOpaque(true);
					lb.setBorder(BorderFactory.createEmptyBorder(1, 2, 1, 1));
					lb.setHorizontalAlignment(JLabel.CENTER);
					if (dark) {
						lb.setBackground(lb.getBackground().darker());
						lb.setForeground(Color.white);
					} else
						lb.setForeground(Color.black);

					temp = lb.getPreferredSize().width;
					lb.setPreferredSize(new Dimension(temp, jTblProbs.getRowHeight()));
					if (lengths[k] < temp)
						lengths[k] = temp;
					temp = 0;

					if (k == nParents - 1) {
						gbc.gridwidth = GridBagConstraints.REMAINDER;
						dark = (dark == true) ? false : true;
					}
					jPlRowHeader.add(lb, gbc);
					addNum++;
				}

				for (int k = nParents - 1; k >= 0; k--) {
					int iParent2 = m_BayesNet.getParent(m_nCurrentNode, k);
					if (idx[k] == m_BayesNet.getCardinality(iParent2) - 1 && k != 0) {
						idx[k] = 0;
						continue;
					} else {
						idx[k]++;
						break;
					}
				}

				int iParent2 = m_BayesNet.getParent(m_nCurrentNode, 0);
				if (idx[0] == m_BayesNet.getCardinality(iParent2)) {
					JLabel lb = (JLabel) jPlRowHeader.getComponent(addNum - 1);
					jPlRowHeader.remove(addNum - 1);
					lb.setPreferredSize(new Dimension(lb.getPreferredSize().width, jTblProbs
							.getRowHeight()));
					gbc.gridwidth = GridBagConstraints.REMAINDER;
					gbc.weighty = 1;
					jPlRowHeader.add(lb, gbc);
					gbc.weighty = 0;
					break;
				}
			}

			gbc.gridwidth = 1;
			// The following panel contains the names of the
			// parents
			// and is displayed above the row names to identify
			// which value belongs to which parent
			JPanel jPlRowNames = new JPanel(new GridBagLayout());
			for (int j = 0; j < nParents; j++) {
				JLabel lb2;
				JLabel lb1 = new JLabel(m_BayesNet.getNodeName(m_BayesNet.getParent(nTargetNode, j)));
				lb1.setBorder(BorderFactory.createEmptyBorder(1, 2, 1, 1));
				Dimension tempd = lb1.getPreferredSize();
				if (tempd.width < lengths[j]) {
					lb1.setPreferredSize(new Dimension(lengths[j], tempd.height));
					lb1.setHorizontalAlignment(JLabel.CENTER);
					lb1.setMinimumSize(new Dimension(lengths[j], tempd.height));
				} else if (tempd.width > lengths[j]) {
					lb2 = (JLabel) jPlRowHeader.getComponent(j);
					lb2.setPreferredSize(new Dimension(tempd.width, lb2.getPreferredSize().height));
				}
				jPlRowNames.add(lb1, gbc);
			}
			js.setRowHeaderView(jPlRowHeader);
			js.setCorner(JScrollPane.UPPER_LEFT_CORNER, jPlRowNames);
		}

		final JDialog dlg = new JDialog((Frame) GUI.this.getTopLevelAncestor(),
				"Probability Distribution Table For " + m_BayesNet.getNodeName(nTargetNode), true);
		dlg.setSize(500, 400);
		dlg.setLocation(GUI.this.getLocation().x + GUI.this.getWidth() / 2
				- 250, GUI.this.getLocation().y + GUI.this.getHeight() / 2
				- 200);

		dlg.getContentPane().setLayout(new BorderLayout());
		dlg.getContentPane().add(js, BorderLayout.CENTER);

		JButton jBtRandomize = new JButton("Randomize");
		jBtRandomize.setMnemonic('R');
		jBtRandomize.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				tm.randomize();
				dlg.repaint();
			}
		});
		
		JButton jBtOk = new JButton("Ok");
		jBtOk.setMnemonic('O');
		jBtOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				tm.setData();
				try {
					m_BayesNet.setDistribution(m_nCurrentNode, tm.m_fProbs);
				    m_jStatusBar.setText(m_BayesNet.lastActionMsg());
					updateStatus();
				} catch (Exception e) {
					e.printStackTrace();
				}
				dlg.setVisible(false);
			}
		});
		JButton jBtCancel = new JButton("Cancel");
		jBtCancel.setMnemonic('C');
		jBtCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				dlg.setVisible(false);
			}
		});
		Container c = new Container();
		c.setLayout(new GridBagLayout());
		c.add(jBtRandomize);
		c.add(jBtOk);
		c.add(jBtCancel);

		dlg.getContentPane().add(c, BorderLayout.SOUTH);
		dlg.setVisible(true);
	} // editCPT

	/**
	 * Main method. Builds up menus and reads from file if one is specified.
	 */
	public static void main(String[] args) {

		weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started");
	    
		LookAndFeel.setLookAndFeel();
		
		JFrame jf = new JFrame("Bayes Network Editor");
		final GUI g = new GUI();
		JMenuBar menuBar = g.getMenuBar();

		if (args.length>0) {
			try {
				g.readBIFFromFile(args[0]);
			} catch (IOException ex) {
				ex.printStackTrace();
			} catch (BIFFormatException bf) {
				bf.printStackTrace();
				System.exit(-1);
			}
		}