
/*
 * Canvas.java
 *
 * Created on April 18, 2001, 1:24 AM
 */
package cse605;
/**
 *
 * @author  adev
 * @version 
 */
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.font.*;

public class Canvas extends JPanel implements MouseListener, MouseMotionListener, ActionListener, Cloneable, Serializable{
    /** Creates new Canvas */
   public static final int DELETE = 1006;
    public static final int MOVE = 1007;        
    public static final int CREATE_BEAM = 1008;
    public static final int CREATE_LOAD = 1009;
        
    public static final int DO_NOTHING = 0;
    private boolean moveActivated = false;
    private boolean centerSelected = false;
    private boolean isDragged = false;
    private static int count = 0;
    private static int delay, blinks;
    private static int totalDelay;
    private static javax.swing.Timer timer, timer1, timer2, timer3, timer4, timer5, timer6, timer7, timer8, timer9, timer10, timer11;
    public LinkedList adjMatrix = new LinkedList();
    public int task;
    private Memento myMemento; 
    public boolean compiled = false;
    private LinkedList compList ;
    public boolean flowVisible = false;
    public boolean isPrinting = false;
    private JScrollPane container;
    private boolean isAllSelected=false;
    private boolean areaChanged;
    public Rectangle area;
    private CobUI parent ;
    private Rectangle selectRect;
    private int selectRect_X, selectRect_Y;
    private JTextArea c2TextArea ;
    public Canvas(Memento mmto, Color bgColor, CobUI par) {
        myMemento = mmto;
        parent = par;
        task = DO_NOTHING;
        setLayout(new BorderLayout());
        setBackground(bgColor);
        addMouseListener(this);
        addMouseMotionListener(this);
        area = new Rectangle(0,0);
	clearAll();        
    }
    
    public void changeBgColor(Color c){
        setBackground(c);        
    }

    public void setMemento(Memento mem)
    {
        myMemento = mem;
    }

    public void mouseClicked(MouseEvent evt) {
       
	 if(task==CREATE_BEAM) createBeam(evt.getX(),evt.getY());       
       	else if(task== MOVE){ 
           task=DO_NOTHING; 
	   clearSelection(); 
	   storeCurrentState();
	   parent.unselectButtons();
        }

   }
   
   /**
    * Needed for MouseListener.
    * @param evt the MouseEvent
    */
   public void mousePressed(MouseEvent evt) {
       //  if right clicked       
       if( evt.getModifiers() == evt.BUTTON3_MASK )
       {
           boolean componentClicked = false;
           Edge clickedEdge = null;
           Node clickedNode = null;

           ListIterator _enum = adjMatrix.listIterator();
           Node _node;
           while (_enum.hasNext() && !centerSelected) {
	     _node = (Node) _enum.next();
             if(_node.contains(evt.getPoint())){
                clickedNode = _node ;
                break;
             }
             for(int i=0; i<_node.edges.size(); i++){
                Edge edge = ((Edge)_node.edges.get(i)) ;
                componentClicked = edge.centerSelected(evt.getX(), evt.getY(), false) ;
                if(componentClicked){
                    clickedEdge = edge ;
                    break;
                }
             }
            }// end while

           if(clickedNode!=null){
               openComponentPopup(evt, clickedNode);
               return ;
           }
           else if(clickedEdge!=null){
               openComponentPopup(evt, clickedEdge);
               return ;
           }
           else {
               openComponentPopup(evt);
               return ;               
           }
       }// end right click tasks
       
       if(task==MOVE){
        for(int i=0; i<adjMatrix.size(); i++){
           Node node = (Node)adjMatrix.get(i);
           if(node.isSelected){
               node.setToMove(evt.getX(),evt.getY());
               flowVisible= false; 
           }
        }
       }
       
       if(task!=DO_NOTHING) return;

/*
 *  if node is clicked:
 *  1.  Select it
 *  2.  Make it Draggable
 *       or
 *  1.  Deselect it
 */
       ListIterator enum = adjMatrix.listIterator();
       Node node;
       boolean nodeClicked = false;
       while (enum.hasNext()) {
	 node = (Node) enum.next();
         if(node.contains(evt.getPoint())){
             flowVisible= false; 
             nodeClicked = true;
             if(!node.isSelected) {
                 node.select();
                 node.isDraggable = true;
             }
             else{
                 node.disSelect();
//                 if(!node.isDraggable) node.disSelect();
             }
             repaint();
             moveActivated = true;             
         }
       }
//       moveActivated = true;
       
// centre of edge cilicked :
/*
 *  If center of the edge is clicked :
 *  1.  mark centerSelected
 *  2.  activate moveActivated
 *  3.  mark nodes draggable
 *  4.  Set nodes to move
 */
        centerSelected = false;
        ListIterator _enum = adjMatrix.listIterator();
        Node _node;
        while (_enum.hasNext() && !centerSelected) {
	  _node = (Node) _enum.next();
          for(int i=0; i<_node.edges.size(); i++){
             centerSelected = ((Edge)_node.edges.get(i)).centerSelected(evt.getX(), evt.getY(), true) ;
             if(centerSelected) break;
          }
        }
        if(centerSelected){
            moveActivated = true;
            for(int i=0; i<adjMatrix.size(); i++){
               Node n = (Node)adjMatrix.get(i);
               if(n.isDraggable){
                   n.setToMove(evt.getX(),evt.getY());
                   flowVisible= false; 
               }
            }
            repaint();
        }
        
        selectRect_X = evt.getX();
        selectRect_Y = evt.getY();
        selectRect = new Rectangle(0,0,0,0);
   }
   
   /**
    * Needed for MouseListener.
    * @param evt the MouseEvent
    */
   public void mouseReleased(MouseEvent evt) {
//        System.out.println("\tMouse Released");

       //  if right clicked       
       if( evt.getModifiers() == evt.BUTTON3_MASK )
       {
           repaint();
           return ;
       }// end right click tasks

       if(task==MOVE){
        for(int i=0; i<adjMatrix.size(); i++){
           Node node = (Node)adjMatrix.get(i);
           if(node.isSelected){
               node.unsetToMove();
           }
        }
       }


        if(task!=DO_NOTHING){ 
            return;
        }
        
       ListIterator enum = adjMatrix.listIterator();
       Node node;
       boolean nodeClicked = false;
       while (enum.hasNext()) {
	 node = (Node) enum.next();
         if(node.contains(evt.getPoint())){
             nodeClicked = true;
             if(node.isSelected) {
                if(node.isDraggable && isDragged) node.disSelect();
                node.isDraggable = false;
             }
//             repaint();
         }
       }
       
       if(centerSelected)
       {
           centerSelected=false;
           for(int i =0; i< adjMatrix.size(); i++){
               Node n = (Node)adjMatrix.get(i);
               if(n.isDraggable){
                   n.isDraggable = false;
                   n.unsetToMove();
                   if(isDragged) n.disSelect();
               }
           }       
       }
           
       if(isDragged){ 
           for(int i =0; i< adjMatrix.size(); i++){
               Node n = (Node)adjMatrix.get(i);
               if(n.isDraggable){
                   n.disSelect();
                   n.isDraggable = false;
                   n.unsetToMove();
               }
           }
           storeCurrentState();
           isDragged = false;
           repaint();
       }
       moveActivated = false;

       int count = 0;
       boolean merged = false;
       while ( count < adjMatrix.size() ) {
           Node n = (Node)adjMatrix.get(count++);
           boolean isStored = false;
           for(int i = count; i< adjMatrix.size(); i++){
               Node _n = (Node)adjMatrix.get(i);
               if( n.contains(new Point2D.Float(_n.x,_n.y)) ){
                   //merge n and _n
//                   adjMatrix.remove(i);
//                   adjMatrix.remove(n);
                   merged = true;
                   Node newNode = new Node(n.x, n.y);
                   n.childID = newNode.nodeID;
                   _n.childID = newNode.nodeID;
                   newNode.parentID1 = n.nodeID;
                   newNode.parentID2 = _n.nodeID;
                   ListIterator enumer = n.edges.listIterator();
                   while (enumer.hasNext()) {
                       Edge edg = (Edge)enumer.next();
                       Node[] ns = edg.getNodes();
                       if(ns[0].nodeID == n.nodeID) edg.exchangeNode(newNode, Edge.LEFT_NODE, "");
                       else if(ns[1].nodeID == n.nodeID) edg.exchangeNode(newNode, Edge.RIGHT_NODE, "");
              	       newNode.edges.add( edg );
//                       if(!adjMatrix.contains(newNode)) adjMatrix.add(newNode);
                   }
                   ListIterator _enumer = _n.edges.listIterator();                   
                   while (_enumer.hasNext()) {
                       Edge edg = (Edge)_enumer.next();
                       Node[] ns = edg.getNodes();
                       if(ns[0].nodeID == _n.nodeID) edg.exchangeNode(newNode, Edge.LEFT_NODE, "");
                       else if(ns[1].nodeID == _n.nodeID) edg.exchangeNode(newNode, Edge.RIGHT_NODE, "");
              	       newNode.edges.add( edg );
                   }
                   storeCurrentState();
                   adjMatrix.remove(i);
                   adjMatrix.remove(n);
                   adjMatrix.add(newNode);
                   storeCurrentState();
                   for(int k =0; k< adjMatrix.size(); k++)
                   {
                       Node nd = (Node)adjMatrix.get(k);
                       for(int j = 0; j < nd.edges.size(); j++)
                       {
                           Edge edg = (Edge)nd.edges.get(j) ;
                           if(nd.edges.indexOf(edg)!=nd.edges.lastIndexOf(edg) )
                               do{
                               }while(nd.edges.remove(edg));// remove the duplicate edge
//                           System.out.println(k+", "+j+"->"+ ((Edge)nd.edges.get(j)).getID() );
                       }
                   }
                   repaint();
                   return;
               }
           }//end for
       }//end while
       if(merged){ 
           repaint();
           return;
       }
       
       if(((int)selectRect.getX())!=0 && ((int)selectRect.getY())!=0)
       {
	  repaint();
       }
       selectRect = null;
   }
   
   /**
    * Needed for MouseListener.
    * @param evt the MouseEvent
    */
   public void mouseEntered(MouseEvent evt) {
      // nothing needed here
   }
   
   /**
    * Needed for MouseListener.
    * @param evt the MouseEvent
    */
   public void mouseExited(MouseEvent evt) {
      // nothing needed here
   }

    public void mouseDragged(java.awt.event.MouseEvent p1) {
        
        if(selectRect!=null && !moveActivated){
            int X, Y, ex, ey, h, w;
            ex = p1.getX();
            ey = p1.getY();
            X = (ex > selectRect_X) ? selectRect_X:ex;
            Y = (ey > selectRect_Y) ? selectRect_Y:ey;
            w = Math.abs(selectRect_X-ex) ;
            h = Math.abs(selectRect_Y-ey) ;
            selectRect = new Rectangle(X,Y,w,h);
            mouseSelect();
        }

        if(task==MOVE || moveActivated){
            isDragged = true;
            shift(p1.getX(), p1.getY());
            return;
        }
    }    
    
    public void mouseMoved(java.awt.event.MouseEvent p1) {
    }



  public void createBeam(int x, int y)
   {
	Object[] input;
	int value;

	input = null;
	input = newEdgeInput("Beam");
	if(input == null )
	  {
	    task = DO_NOTHING;
	    parent.unselectButtons();
	    return;
	  }


	//Create nodes:	
        Node l_node = new Node(x,y);
        Node r_node = new Node(x+Beam.STD_WIDTH,y);

        Beam beam = new Beam(input, l_node, r_node);

	System.out.println("elast is = " + beam.getValue("elasticity"));
	System.out.println("len is = " + beam.getValue("length"));
	System.out.println("wid is = " + beam.getValue("width"));
	System.out.println("hei is = " + beam.getValue("height"));
	System.out.println("Sy is = " + beam.getValue("sy"));
	System.out.println("elast is = " + beam.getValue("f_bn"));
	System.out.println("elast is = " + beam.getValue("f_t"));
	System.out.println("elast is = " + beam.getValue("x"));
	System.out.println("elast is = " + beam.getValue("elasticity"));
	System.out.println("elast is = " + beam.getValue("elasticity"));

	if(input[11]!=null){
	  beam.removeAllInstanceConstriant();
	  for(int i=0 ; i< ((String[])input[11]).length ; i++)
	    beam.addInstanceConstriant( ((String[])input[11])[i] );
	}

	if(input[12]!=null){
	  Beam.removeAllConstraints();
	  for(int i=0 ; i< ((String[])input[12]).length ; i++)
	    Beam.addConstraints( ((String[])input[12])[i] );
	}
	
//      update the AdjMatrix now...

        l_node.edges.add(beam);
        r_node.edges.add(beam);
        adjMatrix.add(l_node);
        adjMatrix.add(r_node);
        task = DO_NOTHING;
        repaint();
        storeCurrentState();
		parent.unselectButtons();
   }
   
  	
  public void createLoad()
  {
	
	for(int i = 0; i< adjMatrix.size(); i++)
	{
	
		Node node = ((Node)adjMatrix.get(i));
	
		
		newLoadInput(i);
	
		LinkedList e = ((Node)adjMatrix.get(i)).edges;
		
			
			for(int j = 0; j < e.size(); j++ )
			{
		
			newAngleInput(i, j);
		
			}
		
		
		System.out.println("load is" + node.getLoad());
		System.out.println("is joint fixed??? " + node.getFixedJoint());
		System.out.println("is joint ground??? " + node.getGroundJoint());	
	}
	
	
	
	
	
	}	   
   public Edge getCommonEdge(Node n1, Node n2)
   {
       for(int i=0; i< n1.edges.size(); i++){
           Edge e1 = (Edge)n1.edges.get(i);
           for(int j=0; j<n2.edges.size(); j++){
               Edge e2 = (Edge)n2.edges.get(j);
               if(e1.getID().equals(e2.getID())) return e1;
           }
       }
       return null;
   }

   
   public void setToMove()
   {
       task = MOVE;
   }

   public void shift(int newX, int newY)
   {
       if(moveActivated){
           if(centerSelected){
            for(int i=0; i<adjMatrix.size(); i++){
                Node node = ((Node)adjMatrix.get(i));
                if(node.isDraggable){
                    node.changePosition(newX, newY);
                }
            }
            repaint();
            return;
           }
           else{
            for(int i=0; i<adjMatrix.size(); i++){
                Node node = ((Node)adjMatrix.get(i));
                if(node.isDraggable){
                    node.changePosition(newX, newY);
                    repaint();
                    return;
                }
            }
           }//end else
           
        return;        
       }

        for(int i=0; i<adjMatrix.size(); i++){
            Node node = ((Node)adjMatrix.get(i));
            if(node.isSelected){
                node.changePosition(newX, newY);
            }
        }

        //check if merging:
        for(int i=0; i<adjMatrix.size(); i++){
            Node node = ((Node)adjMatrix.get(i));
        }
        repaint();
   }

   public void delete()
   {
       LinkedList list = new LinkedList();

       for(int i=0; i< adjMatrix.size();i++)
       {
           Node n1 = (Node)adjMatrix.get(i);
           if(n1.isSelected)
           {
//               System.out.println("Size of node : "+ n1.nodeID +" is : "+ n1.edges.size());
               for(int j = 0 ; j < n1.edges.size(); j++)
               {
                   Edge e = (Edge) n1.edges.get(j);
                   if(e.bothEndsSelected()){
                       Node[] ns = e.getNodes();
                       ns[0].edges.remove(e);
                       ns[1].edges.remove(e);
                       list.add(ns[0]);
                       list.add(ns[1]);
                   }
               }
           }
       }
       
       for(int i = 0; i < list.size() ; i++){
           ((Node)list.get(i)).disSelect() ;
       }


//       System.out.println(" adj size = "+ adjMatrix.size());
       int i = 0;
       while(i<adjMatrix.size())
       {
//           System.out.println("Edges in node :"+((Node)adjMatrix.get(i)).nodeID+" = "+((Node)adjMatrix.get(i)).edges.size());
           if( ((Node)adjMatrix.get(i)).edges.size()==0) adjMatrix.remove(i);
           else i++;
       }
//       System.out.println(" adj size = "+ adjMatrix.size());
       storeCurrentState();
       repaint();
       task = DO_NOTHING;
   }

   public void clearSelection()
   {
       for(int i=0; i<adjMatrix.size();i++){
          ((Node)adjMatrix.get(i)).disSelect();
       }
       repaint();
       isAllSelected=false;
   }

    public void clearAll()
    {
        adjMatrix = new LinkedList();
               
        Beam.setCount(0);
        Node.setCount(0);
        
     	storeCurrentState();
        repaint();
    }

    public void selectAll()
    {
        for(int i =0; i<adjMatrix.size(); i++) ((Node)adjMatrix.get(i)).select();
        repaint();
       isAllSelected=true;    
    }

    private void mouseSelect()
    {
        for(int i=0; i<adjMatrix.size(); i++){
            Node n = (Node)adjMatrix.get(i);
            if(n.x>selectRect.x && n.x < selectRect.x+selectRect.width && n.y>selectRect.y && n.y < selectRect.y+selectRect.height){
                n.select();
                //set the identification for the mode of selection
                n.rectSelected = true;
            }
            else{
                if(n.rectSelected){
                    n.disSelect();
                    n.rectSelected = false;
                }
            }
        }
        repaint();
    }
    
   public void paintComponent(Graphics g) {
       try{
         if(areaChanged){
           scrollRectToVisible( new Rectangle(container.getSize()) );
           setPreferredSize( area.getSize() );
           container.revalidate();
           container.repaint();
//          System.out.println("circuit area X = "+ area.width +" Y ="+ area.height);
//          System.out.println(" canvas area X = "+ new Rectangle(container.getSize()).width +" Y ="+ new Rectangle(container.getSize()).height);
           return;
          }
	}
	catch (Exception exp){
	   // do nothing
	}
      actualPaintComponent(g);
   } // end paint

   public void actualPaintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;

      ListIterator enum = adjMatrix.listIterator();
      Node node;
      while (enum.hasNext()) {
	 node = (Node) enum.next();
	 g2.setColor(node.getColor());
	 g2.fill(node);
         for(int i = 0; i< node.edges.size(); i++)
            ((Edge)(node.edges.get(i))).draw(g);
      }

      if(flowVisible && isPrinting){
              for(int i=0; i< adjMatrix.size(); i++){
                Node n = (Node)adjMatrix.get(i);
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);

                g2.setRenderingHint(RenderingHints.KEY_RENDERING,
                            RenderingHints.VALUE_RENDER_QUALITY);
                int fontStyle = Font.ITALIC ;
                FontRenderContext frc = g2.getFontRenderContext();
                Font f = new Font("Times", fontStyle, 10);
                String s = new String("n"+ n.nodeID+", V"+n.nodeID);
                TextLayout tl = new TextLayout(s, f, frc);
                g2.setColor(new Color(179,17,179) );
                tl.draw(g2, n.x - 10, n.y - 10);
                for(int j=0; j< n.edges.size(); j++) ((Edge)n.edges.get(j)).showVals( g );
              }
//          showDirectedFlow();
      }
      
      if(selectRect!=null){ 
         g2.setColor(Color.lightGray);
         g.drawRect(selectRect.x, selectRect.y, selectRect.width, selectRect.height);
      }

   }   

    public void actionPerformed(ActionEvent e) {
    }
    
    public void storeCurrentState(){
        LinkedList list = new LinkedList();
        for(int i=0; i<adjMatrix.size(); i++){
            list.add( ((Node)adjMatrix.get(i)).getClone() );
        }
        myMemento.put(list);
    }

    public void saveCurrentState(){
        LinkedList list = new LinkedList();
        for(int i=0; i<adjMatrix.size(); i++){
            list.add( ((Node)adjMatrix.get(i)).getClone() );
        }
        myMemento.put(list);
    }

    public void retrievePrevState(){

        replaceAdjMatrix( myMemento.getPrevious() );
        for(int i=0; i<adjMatrix.size(); i++){
            ((Node)adjMatrix.get(i)).disSelect();
        }
        establishAssociation("B");
        repaint();
    }

    public void retrieveNextState(){
        replaceAdjMatrix( myMemento.getNext() );
        for(int i=0; i<adjMatrix.size(); i++){
            ((Node)adjMatrix.get(i)).disSelect();
        }
        establishAssociation("F");
        repaint();
    }

    private void establishAssociation(String flag)
    {
        for(int i=0; i<adjMatrix.size(); i++){
            Node node = (Node)adjMatrix.get(i);


            for(int j=0; j<node.edges.size(); j++){
               Edge neighbor = (Edge)node.edges.get(j);
               Node[] peerNodes = neighbor.getNodes();

               if( peerNodes[0].nodeID == node.nodeID){
                   neighbor.exchangeNode(node, Edge.LEFT_NODE, "");
               }
               else if( peerNodes[1].nodeID == node.nodeID){
                   neighbor.exchangeNode(node,Edge.RIGHT_NODE, "");
               }

               if(flag.equals("F")){
                   if( peerNodes[0].nodeID == node.parentID1){
                       neighbor.exchangeNode(node, Edge.LEFT_NODE, "");
                   }
                   else if( peerNodes[1].nodeID == node.parentID1){
                       neighbor.exchangeNode(node,Edge.RIGHT_NODE, "");
                   }
                   if( peerNodes[0].nodeID == node.parentID2){
                       neighbor.exchangeNode(node, Edge.LEFT_NODE, "");
                   }
                   else if( peerNodes[1].nodeID == node.parentID2){
                       neighbor.exchangeNode(node,Edge.RIGHT_NODE, "");
                   }
               }
               if(flag.equals("B")){
                   if( peerNodes[0].nodeID == node.childID ){
                       neighbor.exchangeNode(node, Edge.LEFT_NODE, "");
                   }
                   else if( peerNodes[1].nodeID == node.childID ){
                       neighbor.exchangeNode(node, Edge.RIGHT_NODE, "");
                   }
               }

            }

        }
    }



    public boolean finalize(CobCode cobCode)
    {
        compList = cobCode.identifyComponents(adjMatrix) ;
        if(compList!=null){
            createLoad();
            blink();
        }//end if
        else{
           JOptionPane.showMessageDialog(null,"No Circuit Drawn","ERROR", JOptionPane.ERROR_MESSAGE);
           return false;
        }
        return true;
    }

    private void blink()
    {
        delay = 200;
        blinks = 6;
        timer = new javax.swing.Timer(delay, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if(isAllSelected) {
                  clearSelection();
                }
                else{
                  selectAll();
                }
                blinks--;
                if( blinks<1){
                 timer.stop();
                 clearSelection();		 
	         timer = new javax.swing.Timer(100, new ActionListener() {
	            public void actionPerformed(ActionEvent evt) {        	       
		       timer.stop();
		    }
		 });
		 timer.start();
		 
                }
            }
         });
        timer.start();
    }

    private void showDirectedFlow(){
              for(int i=0; i< adjMatrix.size(); i++){
                Node n = (Node)adjMatrix.get(i);
                Graphics g = getGraphics();
                Graphics2D g2 = (Graphics2D) g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);

                g2.setRenderingHint(RenderingHints.KEY_RENDERING,
                            RenderingHints.VALUE_RENDER_QUALITY);
			    

                for(int j=0; j< n.edges.size(); j++) ((Edge)n.edges.get(j)).showVals( g );
              }
    }

    public void setContainer(JScrollPane cont)
    {
        container = cont;
    }
    
    public void replaceAdjMatrix(LinkedList list)
    {
        adjMatrix = list;
        int maxBeamCount = 0, maxNodeCount = 0, maxCurrCount = 0;
        if(list.size()>0){
            maxNodeCount = ((Node)list.get(0)).getIDVal();
            for(int i = 0; i< list.size() ; i++)
            {
                Node node = (Node)list.get(i) ;
                if(node.getIDVal() > maxNodeCount){
                    maxNodeCount = node.getIDVal();
                }
                for(int j = 0; j< node.edges.size() ; j++)
                {
                    Edge edge = (Edge)node.edges.get(j) ;
					
                    if(edge.getType().equals("Beam")){
                        int cval = edge.getIDVal() ;
                        if(cval > maxBeamCount) maxBeamCount = cval ;
                    }
                    else{
                    }
		    
                }//end for j
            }//end for i           
        }// end if
		
		Beam.setCount(maxBeamCount);
        Node.setCount(maxNodeCount);
        
    }
    
    public void modifyArea()
    {
        int maxX = 0, maxY=0;
        for(int i =0; i < adjMatrix.size(); i++)
        {
            Node node = (Node)adjMatrix.get(i);
            if(maxX < node.x+node.w/2)  maxX = (int)(node.x+node.w/2) ;
            if(maxY < node.y+node.h/2)  maxY = (int)(node.y+node.h/2) ;
        }
        if( area.height != maxY+30 || area.width != maxX+30 ){
            area = new Rectangle(maxX+30, maxY+30);
            areaChanged = true;
        }
        else areaChanged = false;
    }

    private void openComponentPopup(MouseEvent e, Node n)
    {
        final Node node  = n;
        Component parent = this;
	final JPopupMenu menu = new JPopupMenu("Node");
        menu.setInvoker(parent);

        menu.add(new AbstractAction("About"){
	    public void actionPerformed(ActionEvent evt){
                String text = "";
                text +="Node ID : "+node.nodeID;
                text +="\nNumber of edges linked to this node : "+node.edges.size();
                String cText = "";
                LinkedList list = Node.getConstraints();
                for(int i=0; i<list.size(); i++)
                    cText+=(String)list.get(i)+"\n";
                text+="\n____________________";
                text+="\nConstraints :\n"+cText;                
                JOptionPane.showMessageDialog(null, text);
                menu.setVisible(false);
	    }
	  });

          menu.add(new AbstractAction("Change"){
	    public void actionPerformed(ActionEvent evt){
                modifyNode();
                menu.setVisible(false);
	    }
	  });

          menu.show(parent, e.getX(), e.getY());          
    }
    
    private void openComponentPopup(MouseEvent e, Edge edg)
    {
        final Edge edge = edg;
        Component parent = this;
	final JPopupMenu menu = new JPopupMenu("Edge - "+edge.getType());
        menu.setInvoker(parent);

        menu.add(new AbstractAction("Change"){
	    public void actionPerformed(ActionEvent evt){
                modifyEdge(edge);
                menu.setVisible(false);
	    }
	  });

          menu.add(new AbstractAction("Delete"){
	    public void actionPerformed(ActionEvent evt){
                // select nodes at both the ends :
                Node[] nodes = edge.getNodes();
                nodes[0].select();
                nodes[1].select();
                delete();
                menu.setVisible(false);
	    }
	  });

        menu.add(new AbstractAction("About"){
	    public void actionPerformed(ActionEvent evt){
                String text = "";
                text +="Edge Type : "+edge.getType();
                text +="\n\nEdge ID : "+edge.getID();
                text +="\nValue : "+edge.getValue("elasticity");
				//text +="\nCurrent : "+edge.getCurrent();
                text +="\n\nLeft node : "+((Node)(edge.getNodes()[0])).nodeID;
                text +="\nRight node : "+((Node)(edge.getNodes()[1])).nodeID;

                String lcText = "";
		String[] clist = edge.getInstanceConstraint();
		for(int i=0; i<clist.length; i++)
		  lcText+= clist[i]+"\n";
		if(clist.length==0)
		  lcText+= "NIL\n";
                text+="\n____________________";
                text+="\nInstance Constraints :\n"+lcText;

                String cText = "";
                if(edge.getType().equals("Beam")){
                    LinkedList list = Beam.getConstraints();
                    for(int i=0; i<list.size(); i++)
                        cText+=(String)list.get(i)+"\n";
                }
                            
                text+="\n____________________";
                text+="\nType Constraints :\n"+cText;
                JOptionPane.showMessageDialog(null, text);
                menu.setVisible(false);
	    }
	  });
        menu.show(parent, e.getX(), e.getY());          
    }
    
    private void openComponentPopup(MouseEvent e)
    {
        final Canvas parent = this;
	final JPopupMenu menu = new JPopupMenu("Drawing Canvas");
        menu.setInvoker(parent);

        menu.add( parent.parent.saveAction.getAction()) ;
        menu.add( parent.parent.saveAsAction.getAction()) ;
        menu.add( parent.parent.closeAction.getAction()) ;
        menu.addSeparator();
        menu.add( parent.parent.runAction.getAction()) ;
        menu.add( parent.parent.compileAction.getAction()) ;
        menu.addSeparator();
        menu.add( parent.parent.bgAction.getAction()) ;
        menu.show(parent, e.getX(), e.getY());
    }

    private void modifyNode()
    {
        String message = "Modify the constraints for the Nodes";
/*
 *      Constraints
 */     
        String cText = "";
        LinkedList list = Node.getConstraints();
        for(int i=0; i<list.size(); i++)
                cText+=(String)list.get(i)+"\n";
        
        JTextArea cTextArea = new JTextArea(cText,4,30);
        JPanel cPane = new JPanel();
        cPane.add(new JScrollPane(cTextArea));
        cPane.setBorder( BorderFactory.createEmptyBorder(20,20,20,20) );
        cPane.setBorder(BorderFactory.createTitledBorder( "Constraints for Node" ));        
        int result;
        result = JOptionPane.
        showOptionDialog(this,
                          new Object[] { message, cPane},
                          "Node properties", JOptionPane.OK_CANCEL_OPTION,
                          JOptionPane.QUESTION_MESSAGE, null, null, null);
    }



    private Object[] newEdgeInput(String type )
    {
        String message = "Please enter following values for the "+ type;
	Object input[];
	final String t = type;
	boolean validInput = false;

/*
 *      Resistance/Voltage Value
 */
        
        	JTextField valField1 = new JTextField( "" );
        	JPanel valPane1 = new JPanel(new GridLayout(1,2)) ;

		  	valPane1.add( new JLabel("Young's Modulus (E)") );	
			valPane1.add(valField1);
       

        	JTextField valField2 = new JTextField( "" );
	        JPanel valPane2 = new JPanel(new GridLayout(1,2)) ;
	
		  	valPane2.add( new JLabel("Sy") );	
			valPane2.add(valField2);


	        JTextField valField3 = new JTextField( "" );
    	    JPanel valPane3 = new JPanel(new GridLayout(1,2)) ;
	
	  		valPane3.add( new JLabel("Length") );	
			valPane3.add(valField3);


    	    JTextField valField4 = new JTextField( "" );
        	JPanel valPane4 = new JPanel(new GridLayout(1,2)) ;
	
		  	valPane4.add( new JLabel("Width") );	
			valPane4.add(valField4);


        	JTextField valField5 = new JTextField( "" );
	        JPanel valPane5 = new JPanel(new GridLayout(1,2)) ;
	
		  	valPane5.add( new JLabel("Height") );			
			valPane5.add(valField5);


	        JTextField valField6 = new JTextField( "" );
    	    JPanel valPane6 = new JPanel(new GridLayout(1,2)) ;
	
		  	valPane6.add( new JLabel("Bending Force") );			
			valPane6.add(valField6);

	        JTextField valField7 = new JTextField( "" );
    	    JPanel valPane7 = new JPanel(new GridLayout(1,2)) ;
	
		  	valPane7.add( new JLabel("Buckling Force") );			
			valPane7.add(valField7);

    	    JTextField valField8 = new JTextField( "" );
        	JPanel valPane8 = new JPanel(new GridLayout(1,2)) ;
	
		  	valPane8.add( new JLabel("Tensile Force") );	
			valPane8.add(valField8);


	        JTextField valField9 = new JTextField( "" );
    	    JPanel valPane9 = new JPanel(new GridLayout(1,2)) ;
	
		  	valPane9.add( new JLabel("Sigma") );	
			valPane9.add(valField9);


	        JTextField valField10 = new JTextField( "" );
    	    JPanel valPane10 = new JPanel(new GridLayout(1,2)) ;
	
		  	valPane10.add( new JLabel("Enter I") );	
			valPane10.add(valField10);


	        JTextField valField11 = new JTextField( "" );
    	    JPanel valPane11 = new JPanel(new GridLayout(1,2)) ;
	
		  	valPane11.add( new JLabel("Enter F") );	
			valPane11.add(valField11);


		
	String instanceVariables = " ";
	instanceVariables += "Instance Variables :\t";
			
	if(type.equals("Beam"))
	  instanceVariables += "B"+(Beam.count+1)+",  ";

	instanceVariables += "V.left,  V.right";
	JTextField ivField = new JTextField(instanceVariables);
	ivField.setDisabledTextColor(Color.darkGray);
	ivField.setBackground(Color.lightGray);
	ivField.setEnabled(false);
	JPanel ivPane = new JPanel(new GridLayout(1,1) );
	ivPane.add( ivField );
        
        JTextArea c1TextArea = new JTextArea("",4,30);
        JPanel c1Pane = new JPanel(new BorderLayout());
        c1Pane.add(new JScrollPane(c1TextArea), BorderLayout.NORTH);
        c1Pane.add( ivPane, BorderLayout.SOUTH);
        c1Pane.setBorder( BorderFactory.createEmptyBorder(20,20,20,20) );
        c1Pane.setBorder(BorderFactory.createTitledBorder( "Constraint for this "+type));

        String cText = "";
        
        
            LinkedList list = Beam.getConstraints();
            for(int i=0; i<list.size(); i++)
                cText+=(String)list.get(i)+"\n";
             
        c2TextArea = new JTextArea(cText,4,30);
        final Color textAreaColor = c2TextArea.getBackground();
        c2TextArea.setBackground(Color.lightGray);
        c2TextArea.setDisabledTextColor(Color.darkGray);
        c2TextArea.setEnabled(false);


        final JRadioButton rbut = new JRadioButton("Change");
        rbut.addActionListener(new ActionListener() {
    	 public void actionPerformed(ActionEvent e) {
             if(rbut.isSelected()) {
                 c2TextArea.setEnabled(true);
                 c2TextArea.setBackground(textAreaColor);
             }
             else  {
                 c2TextArea.setEnabled(false);
                 c2TextArea.setBackground(Color.lightGray);
             }
	 }
        });
        
 	String globalVariables = " ";
	globalVariables += "Global Variables :\t";
	
	if(type.equals("Beam"))
	  globalVariables += "Got to put these in";
	
	JTextField gvField = new JTextField(globalVariables);
	gvField.setDisabledTextColor(Color.darkGray);
	gvField.setBackground(Color.lightGray);
	gvField.setEnabled(false);
    JPanel gvPane = new JPanel(new GridLayout(1,1));
	gvPane.add( gvField );
	
	

        JPanel c2Pane = new JPanel(new BorderLayout());
        c2Pane.add(rbut,  BorderLayout.NORTH);
        c2Pane.add(new JScrollPane(c2TextArea),  BorderLayout.CENTER);
		c2Pane.add( gvPane,  BorderLayout.SOUTH);
        c2Pane.setBorder( BorderFactory.createEmptyBorder(20,20,20,20) );
        c2Pane.setBorder(BorderFactory.createTitledBorder( "Constraint for "+type+" Type" ));

	input = null;
	
	while(!validInput)
	  {
	    int result;
	    validInput = true;
	    input = new Object[14];
	    input[0] = null;
	    result = JOptionPane.
	      showOptionDialog(this,
                      new Object[] { message, getHelpDropdown(type), valPane1,
                      valPane2, valPane3, valPane4, valPane5, valPane6,
                      valPane7, valPane8, valPane9, valPane10, valPane11, new JPanel(), 
                      //c1Pane, 
                      new JPanel(), new JPanel()
                      //, c2Pane
                      },
                      "New "+type+" properties", JOptionPane.OK_CANCEL_OPTION,
                      JOptionPane.QUESTION_MESSAGE, null, null, null);

	    if(result==JOptionPane.OK_OPTION ){
	      input[0] = valField1.getText();
	      input[1] = valField2.getText();
	      input[2] = valField3.getText();
	      input[3] = valField4.getText();
	      input[4] = valField5.getText();
	      input[5] = valField6.getText();
	      input[6] = valField7.getText();
	      input[7] = valField8.getText();
	      input[8] = valField9.getText();
		  input[9] = valField10.getText();
		  input[10] = valField11.getText();
		  	
	      input[11] = c1TextArea.getText();
	      StringTokenizer st = new StringTokenizer((String)input[11],";\n", false);

	      if( st.countTokens() > 0 ){
		int count=0;
		LinkedList cl = new LinkedList();
		while(st.hasMoreTokens())
		  {
		    String tok = st.nextToken();
		    StringTokenizer testTok = new StringTokenizer(tok);
		    if(testTok.countTokens() > 0)
		      cl.add( tok + ";");
		  }
		String[] localConstraints = new String[cl.size()];
		for(int i=0; i< cl.size(); i++) 
		  localConstraints[i] = (String)cl.get(i);
		input[11] = localConstraints;
	      }
	      else input[11] = null;


	      input[12] = c2TextArea.getText();
	      st = new StringTokenizer((String)input[12],";\n", false);
	      if( st.countTokens() > 0 ){
		int count=0;
		LinkedList cl = new LinkedList();
		while(st.hasMoreTokens())
		  {
		    String tok = st.nextToken();
		    StringTokenizer testTok = new StringTokenizer(tok);
		    if(testTok.countTokens() > 0)
		      cl.add( tok + ";");
		  }
		String[] globalConstraints = new String[cl.size()];
		for(int i=0; i< cl.size(); i++) 
		  globalConstraints[i] = (String)cl.get(i);
		input[12] = globalConstraints;
	      }
	      else input[12] = null;

	      /*
	       * Check if the Non-Integer value was input.
	       * Use this only if needed 
	       *
	       
	      try{
	    for(int y = 0; y< 10; y++)  
		if(!input[y].equals(""))
		  Float.parseFloat((String)input[y]);
		else input[y] = "?";
	      }
	      catch(NumberFormatException nfe){
		JOptionPane.showMessageDialog(null,"Non-Integer value entered as "+type+" value.\nPlease enter Integer value","ERROR", JOptionPane.ERROR_MESSAGE);		
		validInput = false;
	      }
	      
	      *
	      *
	      */

	    }
	    else{
	      return null;
	    }
	  }//end while
	return input;
    }


    private void newLoadInput(int i)
    {
        String message = "Please enter following entries for the node N" + 
        Integer.toString(((Node)adjMatrix.get(i)).getIDVal()) + " ";
	boolean validInput = false;
	
/*
 *      Resistance/Voltage Value
 */
        
        	JTextField valField1 = new JTextField( "" );
        	JPanel valPane1 = new JPanel(new GridLayout(1,2)) ;

		  	valPane1.add( new JLabel("Load ") );	
			valPane1.add(valField1);
       	
        	JTextField valField2 = new JTextField( "" );
        	JPanel valPane2 = new JPanel(new GridLayout(1,2)) ;

		  	valPane2.add( new JLabel("Load Angle") );	
			valPane2.add(valField2);
          	
        final JRadioButton rbut1 = new JRadioButton("Pin Joint/Hinge");
        rbut1.addActionListener(new ActionListener() {
    	 public void actionPerformed(ActionEvent e) {
             }
        });
        
        final JRadioButton rbut2 = new JRadioButton("Rolling Joint");
        rbut2.addActionListener(new ActionListener() {
    	 public void actionPerformed(ActionEvent e) {
             }
        });

	while(!validInput)
	  {
	    int result;
	    validInput = true;
	    result = JOptionPane.
	      showOptionDialog(this,
                      new Object[] { message, getHelpDropdown("Beam"), valPane1,
                      valPane2, rbut1, rbut2, new JPanel(), new JPanel(), new JPanel()},
                      "New Beam properties", JOptionPane.OK_CANCEL_OPTION,
                      JOptionPane.QUESTION_MESSAGE, null, null, null);

	    if(result==JOptionPane.OK_OPTION ){
	    
	      ((Node)adjMatrix.get(i)).setLoad(valField1.getText());
	      ((Node)adjMatrix.get(i)).setLoadAngle(valField2.getText());
	      ((Node)adjMatrix.get(i)).setFixedJoint(rbut1.isSelected());      
	      ((Node)adjMatrix.get(i)).setGroundJoint(rbut2.isSelected());      
	    	
	    }
	    
	  }//end while
	
    }


    
    private void newAngleInput(int i, int j)
    {
        
	    Node node = (Node)adjMatrix.get(i);
		LinkedList e = node.edges;
        Bar b = (Bar)e.get(j);
        String message = "Please enter following angles for the node N" +
        Integer.toString(((Node)adjMatrix.get(i)).getIDVal()) + 
        " of the beam " + b.getID();
	boolean validInput = false;
	
/*
 *      Resistance/Voltage Value
 */
        
        	JTextField valField1 = new JTextField( "" );
        	JPanel valPane1 = new JPanel(new GridLayout(1,2)) ;

		  	valPane1.add( new JLabel("Angle ") );	
			valPane1.add(valField1);
       	
        	
	while(!validInput)
	  {
	    int result;
	    validInput = true;
	    result = JOptionPane.
	      showOptionDialog(this,
                      new Object[] { message, getHelpDropdown("Beam"), valPane1,
                      new JPanel(), new JPanel(), new JPanel()},
                      "New Beam properties", JOptionPane.OK_CANCEL_OPTION,
                      JOptionPane.QUESTION_MESSAGE, null, null, null);

	    if(result==JOptionPane.OK_OPTION ){
	    
	    
	    node.angleInfo[j] = b.getID();
	    
	    node.angle[j] = valField1.getText();
	    
	    }
	    
	  }//end while
	
    }
    
    private void modifyEdge(Edge edge)
    {
        String message = "Please enter following values for the "+ edge.getType();
	Object input[];
	boolean validInput = false;
	JPanel valPane = null;
	final Edge edg = edge;


/*
 *      Resistance/Voltage Value
 */ 

	JPanel valPane1 = new JPanel(new GridLayout(1,2)) ;
	valPane1.add( new JLabel("Young's Modulus E") );	
	JTextField valField1 = null;
	if(!edge.getValue("elasticity").equals("?"))
	    {
	       String val = String.valueOf(edge.getValue("elasticity"));
	       valField1 = new JTextField( val ) ;
	    }
	  else
	    valField1 = new JTextField("");
	
	valPane1.add(valField1);

	JPanel valPane2 = new JPanel(new GridLayout(1,2)) ;
	valPane2.add( new JLabel("Sy") );	
	JTextField valField2 = null;
	if(!edge.getValue("sy").equals("?"))
	    {
	       String val = String.valueOf(edge.getValue("sy"));
	       valField2 = new JTextField( val ) ;
	    }
	  else
	    valField2 = new JTextField("");
	
	valPane2.add(valField2);

	JPanel valPane3 = new JPanel(new GridLayout(1,2)) ;
	valPane3.add( new JLabel("Length") );	
	JTextField valField3 = null;
	if(!edge.getValue("length").equals("?"))
	    {
	       String val = String.valueOf(edge.getValue("length"));
	       valField3 = new JTextField( val ) ;
	    }
	  else
	    valField3 = new JTextField("");
	
	valPane3.add(valField3);

	JPanel valPane4 = new JPanel(new GridLayout(1,2)) ;
	valPane4.add( new JLabel("Width") );	
	JTextField valField4 = null;
	if(!edge.getValue("width").equals("?"))
	    {
	       String val = String.valueOf(edge.getValue("width"));
	       valField4 = new JTextField( val ) ;
	    }
	  else
	    valField4 = new JTextField("");
	
	valPane4.add(valField4);

	JPanel valPane5 = new JPanel(new GridLayout(1,2)) ;
	valPane5.add( new JLabel("Height") );	
	JTextField valField5 = null;
	if(!edge.getValue("height").equals("?"))
	    {
	       String val = String.valueOf(edge.getValue("height"));
	       valField5 = new JTextField( val ) ;
	    }
	  else
	    valField5 = new JTextField("");
	
	valPane5.add(valField5);

	JPanel valPane6 = new JPanel(new GridLayout(1,2)) ;
	valPane6.add( new JLabel("Buckling Force") );	
	JTextField valField6 = null;
	if(!edge.getValue("f_bn").equals("?"))
	    {
	       String val = String.valueOf(edge.getValue("f_bn"));
	       valField6 = new JTextField( val ) ;
	    }
	  else
	    valField6 = new JTextField("");
	
	valPane6.add(valField6);

	JPanel valPane7 = new JPanel(new GridLayout(1,2)) ;
	valPane7.add( new JLabel("Tensile Force") );	
	JTextField valField7 = null;
	if(!edge.getValue("f_t").equals("?"))
	    {
	       String val = String.valueOf(edge.getValue("f_t"));
	       valField7 = new JTextField( val ) ;
	    }
	  else
	    valField7 = new JTextField("");
	
	valPane7.add(valField7);

	JPanel valPane8 = new JPanel(new GridLayout(1,2)) ;
	valPane8.add( new JLabel("Sigma") );	
	JTextField valField8 = null;
	if(!edge.getValue("sigma").equals("?"))
	    {
	       String val = String.valueOf(edge.getValue("sigma"));
	       valField8 = new JTextField( val ) ;
	    }
	  else
	    valField8 = new JTextField("");
	
	valPane8.add(valField8);

	JPanel valPane9 = new JPanel(new GridLayout(1,2)) ;
	valPane9.add( new JLabel("Enter I") );	
	JTextField valField9 = null;
	if(!edge.getValue("bar_i").equals("?"))
	    {
	       String val = String.valueOf(edge.getValue("bar_i"));
	       valField9 = new JTextField( val ) ;
	    }
	  else
	    valField9 = new JTextField("");
	
	valPane9.add(valField9);

	JPanel valPane10 = new JPanel(new GridLayout(1,2)) ;
	valPane10.add( new JLabel("Enter F") );	
	JTextField valField10 = null;
	if(!edge.getValue("bar_f").equals("?"))
	    {
	       String val = String.valueOf(edge.getValue("bar_f"));
	       valField10 = new JTextField( val ) ;
	    }
	  else
	    valField10 = new JTextField("");
	
	valPane10.add(valField10);

	JPanel valPane11 = new JPanel(new GridLayout(1,2)) ;
	valPane11.add( new JLabel("Angle") );		
	JTextField valField11 = null;
	if(!edge.getValue("angle").equals("?"))
	    {
	       String val = String.valueOf(edge.getValue("angle"));
	       valField11 = new JTextField( val ) ;
	    }
	  else
	    valField11 = new JTextField("");
	
	valPane11.add(valField11);
             
	

/*
 *      Current Value
 */




/*
 *      Instance Constraints
 */
        String icText = "";
        String[] iclist = edge.getInstanceConstraint();
        for(int i=0; i<iclist.length; i++) icText+=iclist[i]+"\n";

	String instanceVariables = " ";
	instanceVariables += "Instance Variables :\t";
	
	//instanceVariables += edge.getCurrentID()+",  ";
	
	if(!edge.getType().equals("Wire"))
	  instanceVariables += edge.getID()+",  ";
	instanceVariables += "V.left,  V.right";
	JTextField ivField = new JTextField(instanceVariables);
	ivField.setDisabledTextColor(Color.darkGray);
	ivField.setBackground(Color.lightGray);
	ivField.setEnabled(false);
	JPanel ivPane = new JPanel(new GridLayout(1,1) );
	ivPane.add( ivField );
	
        JTextArea c1TextArea = new JTextArea(icText,4,30);
        JPanel c1Pane = new JPanel(new BorderLayout());
        c1Pane.add(new JScrollPane(c1TextArea), BorderLayout.NORTH);
		c1Pane.add( ivPane,  BorderLayout.SOUTH);
	
        c1Pane.setBorder( BorderFactory.createEmptyBorder(20,20,20,20) );
        c1Pane.setBorder(BorderFactory.createTitledBorder( "Constraint for "+edge.getType()+" "+edge.getID() ));
        
/*
 *      Type Constraints
 */
        String cText = "";
        
		if(edge.getType().equals("Beam")){
            LinkedList list = Beam.getConstraints();
            for(int i=0; i<list.size(); i++)
                cText+=(String)list.get(i)+"\n";
        }

       c2TextArea = new JTextArea(cText,4,30);
        final Color textAreaColor = c2TextArea.getBackground();
        c2TextArea.setBackground(Color.lightGray);
        c2TextArea.setDisabledTextColor(Color.darkGray);
        c2TextArea.setEnabled(false);

        final JRadioButton rbut = new JRadioButton("Change");
        rbut.addActionListener(new ActionListener() {
    	 public void actionPerformed(ActionEvent e) {
             if(rbut.isSelected()) {
                 c2TextArea.setEnabled(true);
                 c2TextArea.setBackground(textAreaColor);
             }
             else  {
                 c2TextArea.setEnabled(false);
                 c2TextArea.setBackground(Color.lightGray);
             }
	 }
        });

 	String globalVariables = " ";
	globalVariables += "Global Variables :\t";

	if(edge.getType().equals("Beam"))
	  globalVariables += "Dunno these either";
	
	
	/*
	else if(edge.getType().equals("Resistor"))
	  globalVariables += "I,  R,  N1.V,  N2.V";
	*/
	
	JTextField gvField = new JTextField(globalVariables);
	gvField.setDisabledTextColor(Color.darkGray);
	gvField.setBackground(Color.lightGray);
	gvField.setEnabled(false);
        JPanel gvPane = new JPanel(new GridLayout(1,1));
	gvPane.add( gvField );
	

        JPanel c2Pane = new JPanel(new BorderLayout() );
	c2Pane.add(rbut,  BorderLayout.NORTH);
        c2Pane.add(new JScrollPane(c2TextArea),  BorderLayout.CENTER);
	c2Pane.add(gvPane,  BorderLayout.SOUTH);
        c2Pane.setBorder( BorderFactory.createEmptyBorder(20,20,20,20) );
        c2Pane.setBorder(BorderFactory.createTitledBorder( "Constraint for "+edge.getType()+" Type" ));

	input = null;
	while(!validInput)
	  {
	    validInput = true;
	    input = new Object[14];
	    input[0] = null;
	    int result;
	    if(!edge.getType().equals("Wire")){
	     
	    //Commented some stuff here
	     
	      result = JOptionPane.showOptionDialog(this,
                             new Object[] { message,
                             getHelpDropdown(edge.getType()), valPane, valPane1,
                             valPane2, valPane3, valPane4, valPane5, valPane6,
                             valPane7, valPane8, valPane9, valPane10, valPane11,
                             new JPanel(), //c1Pane, 
                             new JPanel(),new JPanel()//, c2Pane
                             },
                             edge.getType()+" "+edge.getID()+" properties", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
	    }
	    else{
	      result = JOptionPane.
		showOptionDialog(this,
                             new Object[] { message, getHelpDropdown("Wire"), new JPanel(), c1Pane, new JPanel(),new JPanel(), c2Pane},
                             edge.getType()+" "+edge.getID()+" properties", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
	    }

	    
	    if(result==JOptionPane.OK_OPTION ){
	      input[0] = valField1.getText();
	      input[1] = valField2.getText();
	      input[2] = valField3.getText();
	      input[3] = valField4.getText();
	      input[4] = valField5.getText();
	      input[5] = valField6.getText();
	      input[6] = valField7.getText();
	      input[7] = valField8.getText();
	      input[8] = valField9.getText();
		  input[9] = valField10.getText();
		  input[10] = valField11.getText();
		  	
	      
	      input[11] = c1TextArea.getText();
	      StringTokenizer st = new StringTokenizer((String)input[11],";\n", false);

	      if( st.countTokens() > 0 ){
		int count=0;
		LinkedList cl = new LinkedList();
		while(st.hasMoreTokens())
		  {
		    String tok = st.nextToken();
		    StringTokenizer testTok = new StringTokenizer(tok);
		    if(testTok.countTokens() > 0)
		      cl.add( tok + ";");
		  }
		String[] localConstraints = new String[cl.size()];
		for(int i=0; i< cl.size(); i++) 
		  localConstraints[i] = (String)cl.get(i);
		input[11] = localConstraints;
	      }
	      else input[11] = null;


	      input[12] = c2TextArea.getText();
	      st = new StringTokenizer((String)input[12],";\n", false);
	      if( st.countTokens() > 0 ){
		int count=0;
		LinkedList cl = new LinkedList();
		while(st.hasMoreTokens())
		  {
		    String tok = st.nextToken();
		    StringTokenizer testTok = new StringTokenizer(tok);
		    if(testTok.countTokens() > 0)
		      cl.add( tok + ";");
		  }
		String[] globalConstraints = new String[cl.size()];
		for(int i=0; i< cl.size(); i++) 
		  globalConstraints[i] = (String)cl.get(i);
		input[12] = globalConstraints;
	      }
	      else input[12] = null;


	      /*
	       * Check if the Non-Integer value was input.
	       * Use this only if needed 
	       *

	      if(!edge.getType().equals("Wire")){
		try{
		  if(!input[0].equals(""))
		    Integer.parseInt((String)input[0]);
		  else input[0] = "?";
		}
		catch(NumberFormatException nfe){
		JOptionPane.showMessageDialog(null,"Non-Integer value entered as "+ edge.getType() +" value.\nPlease enter Integer value","ERROR", JOptionPane.ERROR_MESSAGE);

		  validInput = false;
		}
	      }// end if != wire



	      try{
		if(!input[1].equals(""))
		  Integer.parseInt((String)input[1]);
		else input[1] = "?";
	      }
	      catch(NumberFormatException nfe){
		JOptionPane.showMessageDialog(null,"Non-Integer value entered as current value.\nPlease enter Integer value","ERROR", JOptionPane.ERROR_MESSAGE);		
		validInput = false;
	      }

	      *
	      *
	      */

	    }
	    else{
	      return;
	    }
	  }//end while

	  if(!edge.getType().equals("Wire")){
	    edge.setValue(input);
          }

	  if(input[11]!=null){
	    edge.removeAllInstanceConstriant();
	    for(int i=0 ; i< ((String[])input[11]).length ; i++)
	      edge.addInstanceConstriant( ((String[])input[11])[i] );
	  }
	  else edge.removeAllInstanceConstriant();


	  if(input[12]!=null){
	    
	    if(edge.getType().equals("Beam")){
	      Beam.removeAllConstraints();
	      for(int i=0 ; i< ((String[])input[12]).length ; i++)
		Beam.addConstraints( ((String[])input[12])[i] );
	    }
	    
	  }
	  else{

	    if(edge.getType().equals("Beam")){
	      Beam.removeAllConstraints();
	    }
	  
	    
	  }
	  
     }
     
     private void showInstanceInputHelp(String type)
     {
     	String text = "";

	if(type.equals("Beam"))
	{
	    text += "Help on Input for Beams\n";
	    text += "---------------------------\n\n";
	    text += "Enter beam value(if known) against field marked";
	}
		
	else return;
	
	JOptionPane.showMessageDialog(null, text);	
     }
     
     private JComboBox getHelpDropdown(String type)
     {
     	JComboBox helpBox;

     	if(type.equals("Beam")) 
     	{
	    String list[] = {"Help", "Value", "Load", "Angles"};
	    helpBox = new JComboBox(list);
	    helpBox.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
	        JComboBox cb = (JComboBox)e.getSource() ;
                String pick = (String)((cb).getSelectedItem());
		if(pick.equals("Value"))
		{
		    String text = "";
		    text += "Help on Input for Beam\n";
		    text += "---------------------------\n\n";
		    text += "Value :\n";
		    text += "Enter beam values(if known) against the corresponding fields.\n";
		    text += " The units shouldn't be entered.\n\n";
		    text += "Leave this column blank if the values are not known.";
		    JOptionPane.showMessageDialog(null, text);
		}
		if(pick.equals("Angles"))
		{
		    String text = "";
		    text += "Help on Input for Beam\n";
		    text += "---------------------------\n\n";
		    text += "Angle :\n";
		    text += "Enter the angle that the beam makes with the corresponding node(if known).\n";
		    text += " The units are degrees and shouldn't be entered.\n\n";
		    text += "Leave this column blank if the values are not known.";
		    JOptionPane.showMessageDialog(null, text);
		}
		else if(pick.equals("Load"))
		{
		    String text = "";
		    text += "Help on Input for Beam\n";
		    text += "---------------------------\n\n";
		    text += "Load :\n";
		    text += "Enter load value(if known) in lbs against field \n";
		    text += "marked \"Load\". The units shouldn't be entered.\n\n";
		    text += "Leave this column blank if the values are not known.";
		    JOptionPane.showMessageDialog(null, text);			    		
		}
		else if(pick.equals("Instance Constraints"))
		{
		    String text = "";
		    text += "Help on Input for Beam\n";
		    text += "---------------------------\n\n";
		    text += "Instance Constraints:\n";
		    text += "Insert the constraints that you want to put over this\n";
		    text += "Beam. You can put more than one constraint. Make\n";
		    text += "sure that every constraint ends with a semi-colon(;).\n";
		    text += "The variables should be picked from the list given below\n";
		    text += "the input text box.\n";
		    text += "e.g.\n          I3 = 2*R3;\n          V.left > V.right;";
		    JOptionPane.showMessageDialog(null, text);	

		}
		else if(pick.equals("Type Constraints"))
		{
		    String text = "";
		    text += "Help on Input for Beam\n";
		    text += "---------------------------\n\n";
		    text += "Type Constraints:\n";
		    text += "Insert the constraints that you want to put over the\n";
		    text += "Beam type. These constraints will apply over all\n";
		    text += "the resistors that you put in the circuit. You can put\n";
		    text += "more than one constraint. The input text-box contains \n";
		    text += "the default constraints. Make sure that every constraint\n";
		    text += "ends with a semi-colon(;). The variables should be picked\n";
		    text += "from the list given below the input text box. \n";
		    text += "e.g.\n         I * R = (N1.V - N2.V);\n         R < 5*I;\n";		
		    JOptionPane.showMessageDialog(null, text);
		}
		else{
		 /* do nothing */
		}
		cb.setSelectedIndex(0);
              }
            });

	}
     	else helpBox = null;
	
	return helpBox;
     }
     


}
