package cl.jtv;
/*
 * JTV.java
 *
 * Created on 17 de julio de 2001, 11:45 PM
 */


/**
 *
 * @author  Marco Mora Godoy
 * @version
 */

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*; 
import java.awt.*;
import java.awt.print.PrinterJob;
import java.awt.print.*;
import java.util.*;
import java.io.*;
import java.net.*;



public class JTV extends javax.swing.JFrame {
    
    /** Creates new form JTV */
    public static final String LANG_ESP="esp";
    public static final String LANG_ENG="eng";
    public static final String LANG_FRA="fra";
    public static final String LANG_BUNDLE_PATH="languages/";
    
    public static final int ESTADO_INICIAL=-1;
    public static final int ESTADO_SIMBOLO=0;
    public static final int ESTADO_BLANCO=1;
    public static final int ESTADO_SIGMA=2;
    public static final int ESTADO_L=3;
    public static final int ESTADO_R=4;
    public static final int ESTADO_CONCENTRADOR=5;
    public static final int ESTADO_L_SIGMA=6;
    public static final int ESTADO_R_SIGMA=7;
    public static final int ESTADO_AUTOENLACE=8;
    public static final int ESTADO_L_NO_SIGMA=9;
    public static final int ESTADO_R_NO_SIGMA=10;
    public static final int ESTADO_ENLACE=11;
    public static final int ESTADO_SL=12;
    public static final int ESTADO_SR=13;
    public static final int ESTADO_ENLACE_CONDICIONAL=14;
    public static final int ESTADO_COPIADORA=15;
    public static final int ESTADO_SUBMAQUINA=16;
    public static final int ESTADO_PUNTERO=17;
    public static final int ESTADO_PARAMETRO=18;
    
    public static final int MAXIMO_NUMERO_CINTAS=10;
    
    public static final int DRAGGED_NOTHING=0;
    public static final int DRAGGED_MACHINE=1;
    public static final int DRAGGED_POINT=2;
    public static final int DRAGGED_CLIPBOARD=3;
    
    public static ListaMaquinasRecientes listaMaquinasRecientes = new ListaMaquinasRecientes();
    
    public static class ListaMaquinasRecientes{
        
        public static final int MAX_MAQUINAS_RECIENTES = 10;
        
        private Vector<String> maquinas;
        
        public ListaMaquinasRecientes(){
            
            maquinas = new Vector<String>();
        }
        
        public boolean add(String maquina){
            
            if(maquinas.contains(maquina)) return false;
            
            if(maquinas.size() < MAX_MAQUINAS_RECIENTES)
                maquinas.add(maquina);
            else{
                maquinas.removeElementAt(0);
                maquinas.add(maquina);
            }
            
            return true;
        }
        
        public void remove(int index){
            maquinas.removeElementAt(index);
        }
        
        public Enumeration<String> getListaMaquinas(){
            return maquinas.elements();
        }
        
        public String getXML(){
            
            String xml="    <maquinas-recientes>\n";
            
            Enumeration<String> en = getListaMaquinas();
            
            while(en.hasMoreElements()){
                
                xml+= ("        " + "<maquina>" + en.nextElement() + "</maquina>\n");
            }
            
            xml+="   </maquinas-recientes>\n";
            
            return xml;
            
        }
    }
    
    class MyRenderer extends DefaultTreeCellRenderer {
        ImageIcon iconoL;
        ImageIcon iconoR;
        private ImageIcon iconos[];
        
        public static final int MAX_ICONOS=21;
        
        public static final int ICONO_L=0;
        public static final int ICONO_R=1;
        public static final int ICONO_ENLACE=2;
        public static final int ICONO_ESCRITORA=3;
        public static final int ICONO_EXPANDIR=4;
        public static final int ICONO_AUTOENLACE=5;
        public static final int ICONO_STOP=6;
        public static final int ICONO_WARNING=7;
        public static final int ICONO_RAMA=8;
        public static final int ICONO_RECHAZA=9;
        public static final int ICONO_SUBMAQUINA=10;
        public static final int ICONO_ND=11;
        public static final int ICONO_CONCENTRADOR=12;
        public static final int ICONO_LHD=13;
        public static final int ICONO_RHD=14;
        public static final int ICONO_ATE=15;
        public static final int ICONO_SUBMAQUINA_ERROR=16;
        public static final int ICONO_SUBMAQUINA_COLGADA=17;
        public static final int ICONO_SUBMAQUINA_ND=18;
        public static final int ICONO_SUBMAQUINA_EXPANDIR=19;
        public static final int ICONO_SUBMAQUINA_HALT=20;
        
        public MyRenderer() {
            iconos = new ImageIcon[MAX_ICONOS];
            iconos[ICONO_L] = new ImageIcon(getClass().getResource("/images/L_pequenha.gif"));
            iconos[ICONO_R] = new ImageIcon(getClass().getResource("/images/R_pequenha.gif"));
            iconos[ICONO_ENLACE] = new ImageIcon(getClass().getResource("/images/enlaceATE.gif")); //null;
            iconos[ICONO_ESCRITORA] = new ImageIcon(getClass().getResource("/images/a_pequenha.gif"));
            iconos[ICONO_EXPANDIR] = new ImageIcon(getClass().getResource("/images/expandirATE.gif"));
            iconos[ICONO_AUTOENLACE] = new ImageIcon(getClass().getResource("/images/autoenlaceATE.gif"));
            iconos[ICONO_STOP] = new ImageIcon(getClass().getResource("/images/stopATE.gif"));
            iconos[ICONO_WARNING] = new ImageIcon(getClass().getResource("/images/warningATE.gif"));
            iconos[ICONO_RAMA] = null;
            iconos[ICONO_RECHAZA] = new ImageIcon(getClass().getResource("/images/rechazaATE.gif"));
            iconos[ICONO_SUBMAQUINA] = new ImageIcon(getClass().getResource("/images/M_pequenha.gif"));
            iconos[ICONO_ND] = new ImageIcon(getClass().getResource("/images/ND_pequenha.gif"));
            iconos[ICONO_CONCENTRADOR] = new ImageIcon(getClass().getResource("/images/ball_pequenha.gif"));
            iconos[ICONO_LHD] = new ImageIcon(getClass().getResource("/images/LDH_pequenha.gif"));
            iconos[ICONO_RHD] = new ImageIcon(getClass().getResource("/images/RDH_pequenha.gif"));
            iconos[ICONO_ATE] = new ImageIcon(getClass().getResource("/images/ATE_pequenha.gif"));
            iconos[ICONO_SUBMAQUINA_ERROR] = new ImageIcon(getClass().getResource("/images/M_pequenha_Error.gif"));
            iconos[ICONO_SUBMAQUINA_COLGADA] = new ImageIcon(getClass().getResource("/images/M_pequenha_Colgada.gif"));
            iconos[ICONO_SUBMAQUINA_ND] = new ImageIcon(getClass().getResource("/images/M_pequenha_ND.gif"));
            iconos[ICONO_SUBMAQUINA_EXPANDIR] = new ImageIcon(getClass().getResource("/images/M_pequenha_Expandir.gif"));
            iconos[ICONO_SUBMAQUINA_HALT] = new ImageIcon(getClass().getResource("/images/M_pequenha_Halt.gif"));
        }
        
        public Component getTreeCellRendererComponent(
                JTree tree,
                Object value,
                boolean sel,
                boolean expanded,
                boolean leaf,
                int row,
                boolean hasFocus) {
            
            super.getTreeCellRendererComponent(
                    tree, value, sel,
                    expanded, leaf, row,
                    hasFocus);
            
            if(leaf)
                setIcon(getNodeIcon(value));
            else if(((NodeTreeTrace)value).isRoot())
                setIcon(iconos[MyRenderer.ICONO_ATE]);
            else
                setIcon(iconos[MyRenderer.ICONO_ND]);
            
            
            return this;
        }
        
        public ImageIcon getNodeIcon(Object value){
            
            NodeTreeTrace node = (NodeTreeTrace) value;
            return iconos[node.getIconValue()];
        }
        
    }
    
    class MyRenderer2 extends DefaultTreeCellRenderer {
        private ImageIcon iconoEngranaje;
        
        public MyRenderer2() {
            
            
            iconoEngranaje = new ImageIcon(getClass().getResource("/images/engranaje.gif"));
            
        }
        
        public Component getTreeCellRendererComponent(
                JTree tree,
                Object value,
                boolean sel,
                boolean expanded,
                boolean leaf,
                int row,
                boolean hasFocus) {
            
            super.getTreeCellRendererComponent(
                    tree, value, sel,
                    expanded, leaf, row,
                    hasFocus);
            
            //if(leaf) setIcon(iconoEngranaje);
            setIcon(iconoEngranaje);
            
            return this;
        }
        
    }
    
    
    public JTV(String newLanguajeBundlePath) {
        
        languajeBundlePath = newLanguajeBundlePath;
        initComponents();
        this.setState(0);
        this.estadoJTV = JTV.ESTADO_INICIAL;
        flagContexto = new FlagContexto();
        numberOfNodes = new SharedInteger();
        cursor = new Cursor(0,0);
        Comando.setSaveComponents(jButton3,jMenuItem4);
        Comando.startDaemonUR(jButton13,jButton14,jMenuItem8,jMenuItem9);
        Clipboard.startDaemonClipboard(jButton15,jButton16,jButton19,jMenuItem10,jMenuItem11,jMenuItem13);
        setTree();
        setTree2();
        setTabPane();
        setTapesPanel(JTV.numeroCintas);
        fillTapesCombobox(newLanguajeBundlePath);
        fillSymbolsCombobox();
        fillVarsCombobox();
        fillParamsCombobox();
        setConfiguracion();
        setDicOfMachines();
        //setSubmachines();
        setMachinesPanel();
        setMenuListener();
        setFileFilter();
        fillPopupMenu();
        fillListaMaquinasRecientesMenu();
        pack();
        
    }
    
    private void fillTapesCombobox(String languajeBundlePath) {
        
        for(int i=1;i<=this.arrayOfTapes.length;i++)
            //jComboBox2.addItem(java.util.ResourceBundle.getBundle(languajeBundlePath).getString("Cinta") + " " + i);
            jComboBox2.addItem("Cinta "+i);
        
    }
    
    private void fillSymbolsCombobox() {
        
        jComboBox1.setFont(new Font("TIMESROMAN",Font.ITALIC,15));
        jComboBox1.setBackground(Color.white);
        
        jComboBox1.addItem("#");
        
        for(char i='a';i<='z';i++)
            jComboBox1.addItem(String.valueOf(i));
        
        for(char i='0';i<='9';i++)
            jComboBox1.addItem(String.valueOf(i));
        
    }
    
    
    private void fillVarsCombobox() {
        
        jComboBox3.setFont(new Font("TIMESROMAN",Font.ITALIC,15));
        jComboBox3.setBackground(Color.white);
        
        for(int i=Hellada.ALPHA;i<=Hellada.OMEGA;i++)
            jComboBox3.addItem(Hellada.getChar(i));
        
    }
    
    private void fillParamsCombobox() {
        
        jComboBox5.setFont(new Font("TIMESROMAN",Font.ITALIC,15));
        jComboBox5.setBackground(Color.white);
        for(char i='A';i<='Z';i++)
            jComboBox5.addItem(String.valueOf(i));
    }
    
    private void setMenuListener(){
        
        jMenu2.addMenuListener(new MyMenuListener());
    }
    
    private void setFileFilter(){
        
        ff = new javax.swing.filechooser.FileFilter(){
            
            public boolean accept(File f) {
                
                if (f.isDirectory()) {
                    return true;
                }
                
                String extension = Utils.getExtension(f);
                if (extension != null) {
                    if (extension.equals(Utils.jtv) ||
                            extension.equals(Utils.JTV)) {
                        return true;
                    } else {
                        return false;
                    }
                }
                
                return false;
            }
            
            public String getDescription(){
                
                return "Archivos de Máquinas de Turing generados por JTV";
            }
            
        };
        
        fc.setAcceptAllFileFilterUsed(false);
        fc.setFileFilter(ff);
        
        /////////////////////////////////////
        ff2 = new javax.swing.filechooser.FileFilter(){
            
            public boolean accept(File f) {
                
                if (f.isDirectory()) {
                    return true;
                }
                
                String extension = Utils.getExtension(f);
                if (extension != null) {
                    if (extension.equals(Utils.tex) ||
                            extension.equals(Utils.TEX)) {
                        return true;
                    } else {
                        return false;
                    }
                }
                
                return false;
            }
            
            public String getDescription(){
                
                return "Archivos Latex";
            }
            
        };
        
        fc2.setAcceptAllFileFilterUsed(false);
        fc2.setFileFilter(ff2);
        
        /////////////////////////////////////
        ff3 = new javax.swing.filechooser.FileFilter(){
            
            public boolean accept(File f) {
                
                if (f.isDirectory()) {
                    return true;
                }
                
                String extension = Utils.getExtension(f);
                if (extension != null) {
                    if (extension.equals(Utils.soc) ||
                            extension.equals(Utils.SOC)) {
                        return true;
                    } else {
                        return false;
                    }
                }
                
                return false;
            }
            
            public String getDescription(){
                
                return "Archivos de Repositorio SOC";
            }
            
        };
        
        fc3.setAcceptAllFileFilterUsed(false);
        fc3.setFileFilter(ff3);
        
    }
    
    private void hacerInicial(){
        
        if(Maquina.selectedMachine!=null && Maquina.selectedMachine.esEnlazable() && Maquina.selectedMachine.previa==null){
            if(((Vector2)currentMachineComponents).inicial!=null)
                ((Vector2)currentMachineComponents).inicial.setInicial(false);
            ComandoEMI comandoEMI = new ComandoEMI(Maquina.selectedMachine,((Vector2)currentMachineComponents));
            comandoEMI.setInverse(new ComandoEMI(((Vector2)currentMachineComponents).inicial,((Vector2)currentMachineComponents)));
            Comando.addComando2UR(comandoEMI);
            ((Vector2)currentMachineComponents).inicial = Maquina.selectedMachine;
            Maquina.selectedMachine.setInicial(true);
            drawingMachinesArea.repaint();
        }
    }
    
    private void cambiarCinta(){
        
        if(Maquina.selectedMachine!=null && Maquina.selectedMachine.esEnlazable()){
            int oldIndiceCinta = Maquina.selectedMachine.getIndiceCinta();
            Maquina.selectedMachine.setIndiceCinta(jComboBox2.getSelectedIndex());
            ComandoEIM comandoEIM = new ComandoEIM(Maquina.selectedMachine,null,Maquina.selectedMachine.getIndiceCinta());
            comandoEIM.setInverse(new ComandoEIM(Maquina.selectedMachine,null,oldIndiceCinta));
            Comando.addComando2UR(comandoEIM);
            drawingMachinesArea.repaint();
        }
    }
    
    private void fillPopupMenu(){
        JMenuItem menuItem;
        this.popup = new JPopupMenu();
        //this.popup.setFont(new Font("ARIAL",Font.PLAIN,5));
        menuItem = new JMenuItem("Hacer Inicial",new ImageIcon(getClass().getResource("/images/Start16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                
                /*if(Maquina.selectedMachine!=null && Maquina.selectedMachine.esEnlazable() && Maquina.selectedMachine.previa==null){
                    ((Vector2)currentMachineComponents).inicial.setInicial(false);
                    ComandoEMI comandoEMI = new ComandoEMI(Maquina.selectedMachine,((Vector2)currentMachineComponents));
                    comandoEMI.setInverse(new ComandoEMI(((Vector2)currentMachineComponents).inicial,((Vector2)currentMachineComponents)));
                    Comando.addComando2UR(comandoEMI);
                    ((Vector2)currentMachineComponents).inicial = Maquina.selectedMachine;
                    Maquina.selectedMachine.setInicial(true);
                    drawingMachinesArea.repaint();
                }*/
                hacerInicial();
            }
        });
        popup.add(menuItem);
        menuItem = new JMenuItem("Cambiar Cinta",new ImageIcon(getClass().getResource("/images/cambiarIndice16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                /*if(Maquina.selectedMachine!=null && Maquina.selectedMachine.esEnlazable()){
                    int oldIndiceCinta = Maquina.selectedMachine.getIndiceCinta();
                    Maquina.selectedMachine.setIndiceCinta(jComboBox2.getSelectedIndex());
                    ComandoEIM comandoEIM = new ComandoEIM(Maquina.selectedMachine,null,Maquina.selectedMachine.getIndiceCinta());
                    comandoEIM.setInverse(new ComandoEIM(Maquina.selectedMachine,null,oldIndiceCinta));
                    Comando.addComando2UR(comandoEIM);
                    drawingMachinesArea.repaint();
                }*/
                cambiarCinta();
            }
        });
        popup.add(menuItem);
        menuItem = new JMenuItem("Cortar",new ImageIcon(getClass().getResource("/images/Cut16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        //menuItem.addActionListener(this);
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton15ActionPerformed(evt);
            }
        });
        popup.add(menuItem);
        menuItem = new JMenuItem("Copiar",new ImageIcon(getClass().getResource("/images/Copy16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        //menuItem.addActionListener(this);
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton16ActionPerformed(evt);
            }
        });
        popup.add(menuItem);
        menuItem = new JMenuItem("Pegar",new ImageIcon(getClass().getResource("/images/Paste16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton17ActionPerformed(evt);
            }
        });
        popup.add(menuItem);
        menuItem = new JMenuItem("Eliminar",new ImageIcon(getClass().getResource("/images/Delete16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                
                if(Maquina.running) return;
                
                jButton19ActionPerformed(evt);
                if(currentMachineComponents.size()==0){
                    searchedMachine=null;
                    cursor.desactivar();
                    drawingMachinesArea.repaint();
                }
                
                /*if(Maquina.selectedMachine!=null){
                    Maquina.selectedMachine.deleteMachine(currentMachineComponents);
                    Maquina.selectedMachine=null;
                    if(currentMachineComponents.size()==0){
                        searchedMachine=null;
                        cursor.desactivar();
                    }
                    drawingMachinesArea.repaint();
                }*/
            }
        });
        popup.add(menuItem);
        
        java.awt.event.MouseListener popupListener = new PopupListener();
        this.drawingMachinesArea.addMouseListener(popupListener);
        
        //this.jMenu2.addM
        //Armo el popup del árbol de máquinas
        this.popup2 = new JPopupMenu();
        //this.popup.setFont(new Font("ARIAL",Font.PLAIN,5));
        menuItem = new JMenuItem("Agregar Nueva",new ImageIcon(getClass().getResource("/images/New16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                /*if(Maquina.selectedMachine!=null && Maquina.selectedMachine.esEnlazable() && Maquina.selectedMachine.previa==null){
                    ((Vector2)currentMachineComponents).inicial.setInicial(false);
                    ((Vector2)currentMachineComponents).inicial = Maquina.selectedMachine;
                    Maquina.selectedMachine.setInicial(true);
                    drawingMachinesArea.repaint();
                }*/
                //evt.get
                NodeTreeMachine selectedMachine = (NodeTreeMachine)jTree2.getLastSelectedPathComponent();
                if(selectedMachine==null){
                    System.out.println("NADA");
                    return;
                }
                
                //NodeTreeMachine parentMachine = (NodeTreeMachine)selectedMachine.getParent();
                Vector2 vector2 = new Vector2();
                DialogPropiedades dp = new DialogPropiedades(new javax.swing.JFrame(), true,vector2,dicOfMachines,false);
                dp.setVisible(true);
                if(dp.getReturnStatus()==DialogPropiedades.RET_OK){
                    vector2.setDependencia((String)selectedMachine.getUserObject());
                    NodeTreeMachine newChild = new NodeTreeMachine(vector2.getNombreLargo());
                    vector2.setNumeroCintas(arrayOfTapes.length);
                    newChild.vector2 = vector2;
                    newChild.maquina = null;
                    treeModel2.insertNodeInto(newChild,selectedMachine,selectedMachine.getChildCount());
                    dicOfMachines.put(vector2.getNombreLargo(),vector2);
                    //ACTUALIZO COMBOBOX DE SUBMAQUINAS
                    //if(!jComboBox4.isEnabled()) jComboBox4.setEnabled(true);
                    //jComboBox4.addItem(newChild.getUserObject());
                    TreePath tp = new TreePath(newChild.getPath());
                    jTree2.setSelectionPath(tp);
                    jTree2.expandPath(tp);
                }
                vector2=null;
            }
        });
        popup2.add(menuItem);
        
        menuItem = new JMenuItem("Agregar Existente",new ImageIcon(getClass().getResource("/images/Add16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                /*if(Maquina.selectedMachine!=null && Maquina.selectedMachine.esEnlazable() && Maquina.selectedMachine.previa==null){
                    ((Vector2)currentMachineComponents).inicial.setInicial(false);
                    ((Vector2)currentMachineComponents).inicial = Maquina.selectedMachine;
                    Maquina.selectedMachine.setInicial(true);
                    drawingMachinesArea.repaint();
                }*/
                NodeTreeMachine selectedMachine = (NodeTreeMachine)jTree2.getLastSelectedPathComponent();
                if(selectedMachine==null){
                    System.out.println("NADA");
                    return;
                }
                
                
                //final JFileChooser fc = new JFileChooser();
                /*FileFilter filter=null;
                File f=null;
                f.
                fc.addChoosableFileFilter(filter*/
                //In response to a button click:
                int returnVal = fc.showOpenDialog(jTree2);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    try{
                        File file = fc.getSelectedFile();
                        String fileName = file.getName();
                        if(!(fileName.endsWith(".jtv") || fileName.endsWith(".JTV"))){
                            file = new File(file.getPath()+".jtv");
                        }
                        String headerXML ="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n\n";
                        headerXML+="<!DOCTYPE jtv SYSTEM \""+JTV.pathJTV+"JTV.dtd\">\n\n";
                        
                        ByteArrayInputStream bais = new ByteArrayInputStream(headerXML.getBytes());
                        FileInputStream fis = new FileInputStream(file);
                        SequenceInputStream sis = new SequenceInputStream(bais, fis);
                        
                        javax.xml.parsers.DocumentBuilderFactory builderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
                        javax.xml.parsers.DocumentBuilder builder = builderFactory.newDocumentBuilder();
                        org.w3c.dom.Document document = builder.parse(new org.xml.sax.InputSource(sis));
                        JTVScanner scanner = new JTVScanner(document);
                        scanner.visitDocument();
                        //OBTENGO EL DICCIONARIO DE MAQUINAS DEL ARCHIVO ABIERTO
                        Hashtable dicOfMachinesParse = scanner.getDicOfMachines();
                        //OBTENGO LA MAQUINA PRINCIPAL
                        Vector2 principal = scanner.getPrincipal();
                        //SETEO SU DEPENDENCIA DE LA MAQUINA DONDE SE VA A INSERTAR
                        principal.setDependencia((String)selectedMachine.getUserObject());
                        //System.out.println("principal.getDependencia()="+principal.getDependencia());
                        //INSERTO EN EL ARBOL LA MAQUINA PRINCIPAL
                        NodeTreeMachine newChild = new NodeTreeMachine(principal.getNombreLargo());
                        newChild.vector2 = principal;
                        newChild.maquina = null;
                        treeModel2.insertNodeInto(newChild,selectedMachine,selectedMachine.getChildCount());
                        //INSERTO EL RESTO DE LAS MAQUINAS RECURSIVAMENTE EN EL ARBOL
                        Hashtable dicOfMachinesParse2 = (Hashtable)dicOfMachinesParse.clone();
                        
                        Enumeration en = dicOfMachinesParse.elements();
                        while(en.hasMoreElements()){
                            Vector2 vector2 = (Vector2)en.nextElement();
                            Enumeration en2 = vector2.elements();
                            while(en2.hasMoreElements()){
                                Maquina maquina = (Maquina)en2.nextElement();
                                if(maquina instanceof Submaquina && !((Submaquina)maquina).isMonocinta()){
                                    String nombreLargo = ((Submaquina)maquina).getNombreLargo();
                                    //((Submaquina)maquina).machineComponents = (Vector2)dicOfMachines.get(((Submaquina)maquina).getNombreLargo());
                                    ((Submaquina)maquina).machineComponents = (Vector2)dicOfMachinesParse.get(nombreLargo);
                                } else if(maquina instanceof Submaquina && ((Submaquina)maquina).isMonocinta()){
                                    String nombreLargo = ((Submaquina)maquina).getNombreLargo();
                                    //((Submaquina)maquina).machineComponents = (Vector2)dicOfMachines.get(((Submaquina)maquina).getNombreLargo());
                                    ((Submaquina)maquina).machineComponents = (Vector2)dicOfMachines.get(nombreLargo);
                                    //if(((Submaquina)maquina).machineComponents==null) System.out.println("machineComponents de "+nombreLargo +" es NULL");
                                }
                            }
                        }
                        
                        newChild.insertMachines(treeModel2,dicOfMachinesParse);
                        //INSERTO LAS MAQUINAS EN EL DICCIONARIO Y
                        //SE COMPRUEBAN NOMBRE REPETIDOS, CAMBIANDOLOS DE HABERLOS
                        en = null;
                        en = newChild.preorderEnumeration();
                        while(en.hasMoreElements()){
                            NodeTreeMachine node = (NodeTreeMachine)en.nextElement();
                            int contador=1;
                            String nombreLargo = node.vector2.getNombreLargo();
                            String nombreLargoOld = new String(nombreLargo);
                            while(dicOfMachines.containsKey(nombreLargo)){
                                nombreLargo = node.vector2.getNombreLargo()+"_"+contador;
                                //node.vector2.setNombreLargo(node.vector2.getNombreLargo()+"_"+contador);
                                contador++;
                            }
                            
                            node.vector2.setNombreLargo(nombreLargo);
                            dicOfMachines.put(node.vector2.getNombreLargo(),node.vector2);
                            
                        /*Vector calledMachines = Vector2.getCalledMachines(nombreLargoOld,dicOfMachinesParse2);
                        Enumeration en2 = calledMachines.elements();
                        while(en2.hasMoreElements()){
                            Vector2 calledMachine = (Vector2)en2.nextElement();
                            calledMachine.setDependencia(nombreLargo);
                        }*/
                            node.refreshUserObject();
                        }
                        
                        en = null;
                        en = newChild.preorderEnumeration();
                        while(en.hasMoreElements()){
                            NodeTreeMachine node = (NodeTreeMachine)en.nextElement();
                            if(!node.isRoot())
                                node.vector2.setDependencia((String)((NodeTreeMachine)node.getParent()).getUserObject());
                        }
                        
                        TreePath tp = new TreePath(newChild.getPath());
                        jTree2.setSelectionPath(tp);
                        jTree2.expandPath(tp);
                        
                        //FINALMENTE, LA MAQUINA PRINCIPAL DEL ARCHIVO ABIERTO DEJE DE SERLO
                        principal.setPrincipal(false);
                        //SE LIBERAN RECURSOS
                        dicOfMachinesParse.clear();
                        dicOfMachinesParse = null;
                        //drawingMachinesArea.repaint();
                        System.gc();
                    } catch(Exception ex){
                        JOptionPane.showMessageDialog(null, "Se produjo un error durante la apertura del archivo","JTV",JOptionPane.ERROR_MESSAGE);
                        ex.printStackTrace();
                    }
                }
            }
        });
        popup2.add(menuItem);
        
        menuItem = new JMenuItem("Cortar",new ImageIcon(getClass().getResource("/images/Cut16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        //menuItem.addActionListener(this);
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                System.out.println("cortar submáquina");
                
                copycutTreeMachine = (NodeTreeMachine)jTree2.getLastSelectedPathComponent();
                if(copycutTreeMachine==null){
                    System.out.println("NADA");
                    return;
                }
                NodeTreeMachine.copy = false;
                NodeTreeMachine parentMachine = (NodeTreeMachine)copycutTreeMachine.getParent();
                
                Enumeration en = parentMachine.vector2.elements();
                while(en.hasMoreElements()){
                    Maquina maquina = (Maquina)en.nextElement();
                    if(maquina instanceof Submaquina){
                        if(((Submaquina)maquina).machineComponents==copycutTreeMachine.vector2){
                            JOptionPane.showMessageDialog(null, "Esta máquina no se pudo cortar pues existen referencias a esta máquina desde la máquina padre","JTV",JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    }
                }
                
                
                
                NodeTreeMachine previousMachine = (NodeTreeMachine)copycutTreeMachine.getPreviousNode();
                currentMachineComponents = previousMachine.vector2;
                currentRepository = previousMachine.vector2.getNombreLargo();
                treeModel2.removeNodeFromParent(copycutTreeMachine);
                TreePath tp = new TreePath(previousMachine.getPath());
                jTree2.setSelectionPath(tp);
                jTree2.expandPath(tp);
                
            }
        });
        popup2.add(menuItem);
        menuItem = new JMenuItem("Copiar",new ImageIcon(getClass().getResource("/images/Copy16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        //menuItem.addActionListener(this);
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                System.out.println("copiar submaquina");
                
                copycutTreeMachine = (NodeTreeMachine)jTree2.getLastSelectedPathComponent();
                
                if(copycutTreeMachine==null){
                    System.out.println("NADA");
                    return;
                }
                
                NodeTreeMachine.copy = true;
                
                
                
                
            }
        });
        popup2.add(menuItem);
        menuItem = new JMenuItem("Pegar",new ImageIcon(getClass().getResource("/images/Paste16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                System.out.println("pegar submaquina");
                
                NodeTreeMachine selectedMachine = (NodeTreeMachine)jTree2.getLastSelectedPathComponent();
                if(selectedMachine==null){
                    System.out.println("NADA");
                    return;
                }
                
                if(!NodeTreeMachine.copy){
                    treeModel2.insertNodeInto(copycutTreeMachine,selectedMachine,selectedMachine.getChildCount());
                    copycutTreeMachine.vector2.setDependencia(selectedMachine.vector2.getNombreLargo());
                    TreePath tp = new TreePath(copycutTreeMachine.getPath());
                    jTree2.setSelectionPath(tp);
                    jTree2.expandPath(tp);
                }
                
                if(NodeTreeMachine.copy){
                    try{
                        //**********************
                        String xml = getXML(copycutTreeMachine);
                        String headerXML ="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n\n";
                        headerXML+="<!DOCTYPE jtv SYSTEM \""+JTV.pathJTV+"JTV.dtd\">\n\n";
                        xml = headerXML+xml;
                        
                        javax.xml.parsers.DocumentBuilderFactory builderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
                        javax.xml.parsers.DocumentBuilder builder = builderFactory.newDocumentBuilder();
                        org.w3c.dom.Document document = builder.parse(new org.xml.sax.InputSource(new StringReader(xml)));
                        JTVScanner scanner = new JTVScanner(document);
                        scanner.visitDocument();
                        //OBTENGO EL DICCIONARIO DE MAQUINAS DEL ARCHIVO ABIERTO
                        Hashtable dicOfMachinesParse = scanner.getDicOfMachines();
                        //OBTENGO LA MAQUINA PRINCIPAL
                        Vector2 principal = scanner.getPrincipal();
                        //SETEO SU DEPENDENCIA DE LA MAQUINA DONDE SE VA A INSERTAR
                        principal.setDependencia((String)selectedMachine.getUserObject());
                        System.out.println("principal.getDependencia()="+principal.getDependencia());
                        //INSERTO EN EL ARBOL LA MAQUINA PRINCIPAL
                        NodeTreeMachine newChild = new NodeTreeMachine(principal.getNombreLargo());
                        newChild.vector2 = principal;
                        newChild.maquina = null;
                        treeModel2.insertNodeInto(newChild,selectedMachine,selectedMachine.getChildCount());
                        //INSERTO EL RESTO DE LAS MAQUINAS RECURSIVAMENTE EN EL ARBOL
                        Hashtable dicOfMachinesParse2 = (Hashtable)dicOfMachinesParse.clone();
                        
                        Enumeration en = dicOfMachinesParse.elements();
                        while(en.hasMoreElements()){
                            Vector2 vector2 = (Vector2)en.nextElement();
                            Enumeration en2 = vector2.elements();
                            while(en2.hasMoreElements()){
                                Maquina maquina = (Maquina)en2.nextElement();
                                if(maquina instanceof Submaquina && !((Submaquina)maquina).isMonocinta()){
                                    String nombreLargo = ((Submaquina)maquina).getNombreLargo();
                                    //((Submaquina)maquina).machineComponents = (Vector2)dicOfMachines.get(((Submaquina)maquina).getNombreLargo());
                                    ((Submaquina)maquina).machineComponents = (Vector2)dicOfMachinesParse.get(nombreLargo);
                                } else if(maquina instanceof Submaquina && ((Submaquina)maquina).isMonocinta()){
                                    String nombreLargo = ((Submaquina)maquina).getNombreLargo();
                                    //((Submaquina)maquina).machineComponents = (Vector2)dicOfMachines.get(((Submaquina)maquina).getNombreLargo());
                                    ((Submaquina)maquina).machineComponents = (Vector2)dicOfMachines.get(nombreLargo);
                                    //if(((Submaquina)maquina).machineComponents==null) System.out.println("machineComponents de "+nombreLargo +" es NULL");
                                }
                            }
                        }
                        
                        newChild.insertMachines(treeModel2,dicOfMachinesParse);
                        //INSERTO LAS MAQUINAS EN EL DICCIONARIO Y
                        //SE COMPRUEBAN NOMBRE REPETIDOS, CAMBIANDOLOS DE HABERLOS
                        en = null;
                        en = newChild.preorderEnumeration();
                        while(en.hasMoreElements()){
                            NodeTreeMachine node = (NodeTreeMachine)en.nextElement();
                            int contador=1;
                            String nombreLargo = node.vector2.getNombreLargo();
                            String nombreLargoOld = new String(nombreLargo);
                            while(dicOfMachines.containsKey(nombreLargo)){
                                nombreLargo = node.vector2.getNombreLargo()+"_"+contador;
                                //node.vector2.setNombreLargo(node.vector2.getNombreLargo()+"_"+contador);
                                contador++;
                            }
                            
                            node.vector2.setNombreLargo(nombreLargo);
                            dicOfMachines.put(node.vector2.getNombreLargo(),node.vector2);
                            
                        /*Vector calledMachines = Vector2.getCalledMachines(nombreLargoOld,dicOfMachinesParse2);
                        Enumeration en2 = calledMachines.elements();
                        while(en2.hasMoreElements()){
                            Vector2 calledMachine = (Vector2)en2.nextElement();
                            calledMachine.setDependencia(nombreLargo);
                        }*/
                            node.refreshUserObject();
                        }
                        
                        en = null;
                        en = newChild.preorderEnumeration();
                        while(en.hasMoreElements()){
                            NodeTreeMachine node = (NodeTreeMachine)en.nextElement();
                            if(!node.isRoot())
                                node.vector2.setDependencia((String)((NodeTreeMachine)node.getParent()).getUserObject());
                        }
                        
                        TreePath tp = new TreePath(newChild.getPath());
                        jTree2.setSelectionPath(tp);
                        jTree2.expandPath(tp);
                        
                        //FINALMENTE, LA MAQUINA PRINCIPAL DEL ARCHIVO ABIERTO DEJE DE SERLO
                        principal.setPrincipal(false);
                        //SE LIBERAN RECURSOS
                        dicOfMachinesParse.clear();
                        dicOfMachinesParse = null;
                        xml=null;
                        //drawingMachinesArea.repaint();
                        System.gc();
                        //**********************
                    } catch(Exception ex){
                        
                        System.out.println("Excepción");
                    }
                }
                copycutTreeMachine=null;
            }
        });
        popup2.add(menuItem);
        menuItem = new JMenuItem("Eliminar",new ImageIcon(getClass().getResource("/images/Delete16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                
                NodeTreeMachine selectedMachine = (NodeTreeMachine)jTree2.getLastSelectedPathComponent();
                if(selectedMachine==null){
                    System.out.println("NADA");
                    return;
                }
                
                int retVal = JOptionPane.showConfirmDialog(null, "¿Seguro que desea eliminar esta máquina?","JTV",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                if(retVal==JOptionPane.NO_OPTION) return;
                
                NodeTreeMachine parentMachine = (NodeTreeMachine)selectedMachine.getParent();
                
                Enumeration en = parentMachine.vector2.elements();
                while(en.hasMoreElements()){
                    Maquina maquina = (Maquina)en.nextElement();
                    if(maquina instanceof Submaquina){
                        if(((Submaquina)maquina).machineComponents==selectedMachine.vector2){
                            JOptionPane.showMessageDialog(null, "Esta máquina no se pudo eliminar pues existen referencias a esta máquina desde la máquina padre","JTV",JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    }
                }
                
                en = selectedMachine.preorderEnumeration();
                while(en.hasMoreElements()){
                    NodeTreeMachine node = (NodeTreeMachine)en.nextElement();
                    dicOfMachines.remove(node.vector2.getNombreLargo());
                }
                NodeTreeMachine previousMachine = (NodeTreeMachine)selectedMachine.getPreviousNode();
                currentMachineComponents = previousMachine.vector2;
                currentRepository = previousMachine.vector2.getNombreLargo();
                treeModel2.removeNodeFromParent(selectedMachine);
                
                //if(!jComboBox4.isEnabled()) jComboBox4.setEnabled(true);
                //    jComboBox4.addItem(principal.getNombreLargo());
                
            }
        });
        popup2.add(menuItem);
        
        menuItem = new JMenuItem("Guardar Como...",new ImageIcon(getClass().getResource("/images/SaveAs16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                
                NodeTreeMachine selectedMachine = (NodeTreeMachine)jTree2.getLastSelectedPathComponent();
                if(selectedMachine==null){
                    System.out.println("NADA");
                    return;
                }
                
                
                //final JFileChooser fc = new JFileChooser();
                //In response to a button click:
                File file = null;
                int returnVal = 0; //fc.showSaveDialog(jTree2);
                while(true){
                    returnVal = fc.showSaveDialog(jTree2);
                    if (returnVal != JFileChooser.APPROVE_OPTION) return;
                    file = fc.getSelectedFile();
                    String fileName = file.getName();
                    if(!(fileName.endsWith(".jtv") || fileName.endsWith(".JTV"))){
                        file = new File(file.getPath()+".jtv");
                    }
                    if(file.exists()){
                        //int yesnoVal = JOptionPane.showMessageDialog(null, "Esta máquina ya existe. ¿Desea sobreescribirla?","JTV",JOptionPane.YES_NO_OPTION);
                        int yesnoVal = JOptionPane.showConfirmDialog(jTree2,"Esta máquina ya existe. ¿Desea sobreescribirla?.","JTV",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                        if(yesnoVal==JOptionPane.YES_OPTION) break;
                    } else break;
                }
                
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    //String xml = ((Vector2)currentMachineComponents).getXML();
                    String xml = getXML(selectedMachine);
                    try{
                        //File file = fc.getSelectedFile();
                        //Writer fileWriter = new OutputStreamWriter(new FileOutputStream(file), "8859_7");
                        FileWriter fileWriter = new FileWriter(file);
                        fileWriter.write(xml);
                        fileWriter.close();
                        xml=null;
                    } catch(Exception ex){
                        System.out.println("Excepción");
                    }
                }
                
            }
        });
        popup2.add(menuItem);
        
        menuItem = new JMenuItem("Propiedades",new ImageIcon(getClass().getResource("/images/Properties16.gif")));
        menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                
                NodeTreeMachine selectedMachine = (NodeTreeMachine)jTree2.getLastSelectedPathComponent();
                if(selectedMachine==null){
                    System.out.println("NADA");
                    return;
                }
                Vector2 vector2 = selectedMachine.vector2;
                System.out.println("Es PRINCIPAL 1="+vector2.isPrincipal());
                //NodeTreeMachine parentMachine = (NodeTreeMachine)selectedMachine.getParent();
                DialogPropiedades dp = new DialogPropiedades(new javax.swing.JFrame(), true,vector2,dicOfMachines,true);
                dp.setVisible(true);
                //int retVal = dp.getReturnStatus();
                if(dp.getReturnStatus()==DialogPropiedades.RET_OK){
                    
                    jButton3.setEnabled(true);
                    System.out.println("Es PRINCIPAL 2="+vector2.isPrincipal());
                    if(vector2.getNombreLargo().equals(dp.getNombreLargoOld())) return;
                    //node.refreshUserObject();
                    System.out.println("Es PRINCIPAL 3="+vector2.isPrincipal());
                    //DialogPropiedades.editingMode=true;
                    dicOfMachines.remove(dp.getNombreLargoOld());
                    //System.out.println("nombreLargoOld"+dp.getNombreLargoOld());
                    //System.out.println("vector2.getNombreLargo()"+vector2.getNombreLargo());
                    System.out.println("Es PRINCIPAL 4="+vector2.isPrincipal());
                    dicOfMachines.put(vector2.getNombreLargo(),vector2);
                    currentRepository = vector2.getNombreLargo();
                    System.out.println("Es PRINCIPAL 5"+vector2.isPrincipal());
                    //System.out.println("currentRepository="+currentRepository);
                    //DialogPropiedades.editingMode=false;
                    
                    
                    System.out.println("Es PRINCIPAL 6="+vector2.isPrincipal());
                    Enumeration en = rootTreeTrace2.preorderEnumeration();
                    while(en.hasMoreElements()){
                        NodeTreeMachine node = (NodeTreeMachine)en.nextElement();
                        node.refreshUserObject();
                    }
                    rootTreeTrace.setUserObject(currentRepository);
                    System.out.println("Es PRINCIPAL 7="+vector2.isPrincipal());
                    selectedMachine.refreshChildDependences();
                    System.out.println("Es PRINCIPAL 8="+vector2.isPrincipal());
                    jButton3.setEnabled(true);
                    
                }
                
            }
        });
        popup2.add(menuItem);
        
        java.awt.event.MouseListener popupListener2 = new PopupListener2();
        this.jTree2.addMouseListener(popupListener2);
        
    }
    
    private void fillListaMaquinasRecientesMenu(){
        
        JMenuItem menuItem;
        String maquinaReciente;
        Enumeration<String> en = JTV.listaMaquinasRecientes.getListaMaquinas();
        
        this.jMenu6.removeAll();
        
        while(en.hasMoreElements()){
            maquinaReciente = en.nextElement();
            menuItem = new JMenuItem(maquinaReciente); //,new ImageIcon(getClass().getResource("/images/engranaje.gif")));
            //menuItem.setFont(new Font("ARIAL",Font.PLAIN,12));
            menuItem.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    //System.out.println(((JMenuItem)evt.getSource()).getText());
                    String machine = ((JMenuItem)evt.getSource()).getText();
                    openMachine(machine);
                }
            });
            this.jMenu6.add(menuItem);
        }
        
    }
    
    private void setTabPane(){
        
        ImageIcon icon = new ImageIcon("images/middle.gif");
        
        
        scrollPane11 = new javax.swing.JScrollPane(jTree1);
        jTabbedPane1.addTab("ATE", icon, scrollPane11, "Arbol de Traza de Ejecución");
        jTabbedPane1.setSelectedIndex(0);
        
        scrollPanel2 = new javax.swing.JScrollPane(jTree2);
        jTabbedPane1.addTab("Máquinas", icon, scrollPanel2, "Arbol de Máquinas");
        
        
    }
    
    private void setConfiguracion(){
        
        try{
            
            File file = new File(java.net.URLDecoder.decode(System.getProperty("user.dir") + File.separator + "JTVConfig.xml", "UTF-8"));
            JTV.rootJTV = file.getParentFile();
            JTV.pathJTV = JTV.rootJTV.toURL().toExternalForm();
            String configXML ="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n\n";
            configXML+="<!DOCTYPE jtv-config SYSTEM \""+JTV.pathJTV+"JTVConfig.dtd\">\n\n";
            
            ByteArrayInputStream bais = new ByteArrayInputStream(configXML.getBytes());
            FileInputStream fis = new FileInputStream(file);
            SequenceInputStream sis = new SequenceInputStream(bais, fis);
            
            javax.xml.parsers.DocumentBuilderFactory builderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
            javax.xml.parsers.DocumentBuilder builder = builderFactory.newDocumentBuilder();
            org.w3c.dom.Document document = builder.parse(new org.xml.sax.InputSource(sis));
            JTVConfigScanner scanner = new JTVConfigScanner(document);
            scanner.visitDocument();
            System.gc();
        } catch(Exception ex){
            ex.printStackTrace();
        }
        changeIconBottonFromNotation();
        
    }
    
    private void setTree(){
        
        
        //DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
        //renderer.setLeafIcon(new ImageIcon(getClass().getResource("/images/L_pequenha.gif")));
        
        MyRenderer renderer = new MyRenderer();
        
        
        rootTreeTrace = new NodeTreeTrace("NUEVA",numberOfNodes,true,null,null,jTree1);
        rootTreeTrace.setIconValue(JTV.MyRenderer.ICONO_ATE);
        currentRepository = (String) rootTreeTrace.getUserObject();
        //rootTreeTrace2 = new NodeTreeTrace("Raíz 2",testTree,numberOfNodes,true,null,null,jTree1);
        rootTreeTrace.setRootTreeTrace(rootTreeTrace);
        treeModel = new DefaultTreeModel(rootTreeTrace);
        //treeSelectionModel = new DefaultTreeSelectionModel();
        rootTreeTrace.setTreeModel(treeModel);
        treeModel.addTreeModelListener(new MyTreeModelListener());
        playTreeTrace = rootTreeTrace;
        //jTree1 = new javax.swing.JTree(rootTreeTrace);
        jTree1 = new javax.swing.JTree(treeModel);
        //jTree1 = new JTree2(treeModel);
        rootTreeTrace.setJTree(jTree1);
        jTree1.getSelectionModel().setSelectionMode
                (TreeSelectionModel.SINGLE_TREE_SELECTION);
        jTree1.setShowsRootHandles(true);
        jTree1.setEditable(false);
        //JScrollPane treeVi = new JScrollPane(jTree1);
        jTree1.setScrollsOnExpand(true);
        jTree1.setCellRenderer(renderer);
        Dimension minimumSize = new Dimension(100, 50);
        jTree1.setMinimumSize(minimumSize);
        jTree1.putClientProperty("JTree.lineStyle", "Angled");
        
        java.awt.event.MouseListener ml = new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent e) {
                
                if(!Maquina.running) return;
                
                int selRow = jTree1.getRowForLocation(e.getX(), e.getY());
                TreePath selPath = jTree1.getPathForLocation(e.getX(), e.getY());
                
                if(e.getClickCount()==2){
                    
                    /*Aqui paso al detalle de la submáquina*/
                    if (selectedNode == null) return;
                    NodeTreeTrace rootNode = (NodeTreeTrace)selectedNode;
                    
                    if(rootNode.getIconValue()==JTV.MyRenderer.ICONO_EXPANDIR && rootNode.getNextSibling()==null && e.getButton()==e.BUTTON3){
                        jButton18ActionPerformed(null);
                        
                    } else if(rootNode.getIconValue()==JTV.MyRenderer.ICONO_SUBMAQUINA || rootNode.getIconValue()==JTV.MyRenderer.ICONO_SUBMAQUINA_EXPANDIR || rootNode.getIconValue()==JTV.MyRenderer.ICONO_SUBMAQUINA_ERROR || rootNode.getIconValue()==JTV.MyRenderer.ICONO_SUBMAQUINA_COLGADA || rootNode.getIconValue()==JTV.MyRenderer.ICONO_SUBMAQUINA_ND){
                        //else if(rootNode.getMachine() instanceof Submaquina){
                        currentRepository = (String)rootNode.contextoSubmaquina.rootTreeTrace.getUserObject();
                        
                        //ESTO ERA LO ORIGINAL
                        //for(int i=0;i<arrayOfTapes.length;i++)
                        //    rootNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes[i]=new Cinta(rootNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes0[i]);
                        //ESTO ES LO NUEVO
                        Maquina.displayIndex=rootNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes.length!=1;
                        for(int i=0;i<rootNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes.length;i++)
                            rootNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes[i]=new Cinta(rootNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes0[i]);
                        //int index=rootNode.getMachine().getIndiceCinta();
                        rootNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes[0].y0=0;
                        rootNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes[0].numero=1;
                        ////////////////////////////////
                        
                        
                        
                        
                        numberOfNodes = rootNode.contextoSubmaquina.rootTreeTrace.getNumOfNodes();
                        treePath = new TreePath(rootNode.contextoSubmaquina.rootTreeTrace.getPath());
                        /*TreePath tp = new TreePath(rootNode.contextoSubmaquina.rootTreeTrace.getPath());
                        jTree1.setSelectionPath(tp);
                        jTree1.expandPath(tp);
                        calculatePath((DefaultMutableTreeNode)tp.getLastPathComponent());*/
                        flagContexto.setContextChange(true);
                        treeModel.setRoot(rootNode.contextoSubmaquina.rootTreeTrace);
                        
                        //drawingMachinesArea.repaint();
                        //drawingTapesArea.repaint();
                        
                    } else if(rootNode.getIconValue()==JTV.MyRenderer.ICONO_WARNING||rootNode.getIconValue()==JTV.MyRenderer.ICONO_RECHAZA||rootNode.getIconValue()==JTV.MyRenderer.ICONO_STOP||(rootNode.getIconValue()==JTV.MyRenderer.ICONO_EXPANDIR && rootNode.getNextNode()==null) || rootNode.getIconValue()==JTV.MyRenderer.ICONO_ND){
                        
                        /*Aquí vuelvo desde la submáquina anidada a la máquina que la invocó*/
                        
                        //System.out.println("antes");
                        //if(rootNode.getNextNode()!=null) return;
                        //System.out.println("después");
                        
                        //System.out.println("antes");
                        if(((NodeTreeTrace)rootNode.getRoot()).parentRootTreeTrace==null) return;
                        //System.out.println("después");
                        
                        currentRepository = (String) ((NodeTreeTrace)((NodeTreeTrace)rootNode.getRoot()).parentRootTreeTrace.getRoot()).getUserObject();
                        
                        //ESTO ERA LO ORIGINAL
                        //Cinta arrayAux[] = ((NodeTreeTrace)rootNode.getRoot()).parentRootTreeTrace.arrayOfTapes0;
                        //for(int j=0;j<arrayOfTapes.length;j++)
                        //((NodeTreeTrace)rootNode.getRoot()).parentRootTreeTrace.arrayOfTapes[j] = new Cinta(arrayAux[j],true);
                        
                        
                        
                        
                        
                        treePath = new TreePath(((NodeTreeTrace)rootNode.getRoot()).parentTreePath);
                        //treeModel.setRoot((NodeTreeTrace)((NodeTreeTrace)((NodeTreeTrace)rootNode.getRoot()).parentRootTreeTrace.getRoot()));
                        numberOfNodes = (((NodeTreeTrace)((NodeTreeTrace)rootNode.getRoot()).parentRootTreeTrace.getRoot())).getNumOfNodes();
                        Maquina.playMachine = ((NodeTreeTrace)(treePath.getPath())[treePath.getPathCount()-1]).getMachine();
                        
                        
                        //ESTO ES LO NUEVO
                        Cinta arrayAux = ((NodeTreeTrace)rootNode.getRoot()).parentRootTreeTrace.arrayOfTapes0[0];
                        //for(int j=0;j<arrayOfTapes.length;j++)
                        int index=Maquina.playMachine.getIndiceCinta();
                        //System.out.println("index="+index);
                        if(((NodeTreeTrace)rootNode.getRoot()).estado==Maquina.ESTADO_ND)
                            ((NodeTreeTrace)rootNode.getRoot()).choosedNodeND=rootNode;
                        ((NodeTreeTrace)rootNode.getRoot()).parentRootTreeTrace.arrayOfTapes[0] = new Cinta(arrayAux,true);
                        //((NodeTreeTrace)rootNode.getRoot()).parentRootTreeTrace.arrayOfTapes[0].y0=20*index;
                        //((NodeTreeTrace)rootNode.getRoot()).parentRootTreeTrace.arrayOfTapes[0].numero=index+1;
                        Maquina.displayIndex=((NodeTreeTrace)rootNode.getRoot()).parentRootTreeTrace.arrayOfTapes.length!=1;
                        flagContexto.setContextChange(true);
                        treeModel.setRoot((NodeTreeTrace)((NodeTreeTrace)((NodeTreeTrace)rootNode.getRoot()).parentRootTreeTrace.getRoot()));
                        ///////////////////////////////////////
                        
                        //repaint();
                        /*Thread contextThread = new Thread(flagContexto);
                        contextThread.start();
                        //System.out.println("jTree1.setSelectionPath(treePath);");
                        jTree1.setSelectionPath(treePath);
                        jTree1.expandPath(treePath);
                        drawingMachinesArea.repaint();*/
                        drawingTapesArea.repaint();
                        
                    }
                }
            }
        };
        jTree1.addMouseListener(ml);
        
        
        jTree1.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent e) {
                
                if(!Maquina.running) return;
               /* if(NodeTreeTrace.runningValueChange.booleanValue()){
                    NodeTreeTrace.runningValueChange=Boolean.FALSE;
                    return;
                }*/
                
                selectedNode = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                
                if (selectedNode == null) return;
                
                
                synchronized(flagContexto){
                    
                    if(flagContexto.isContextChange()){
                        
                        Thread contextThread = new Thread(flagContexto);
                        contextThread.start();
                        //System.out.println("jTree1.setSelectionPath(treePath);");
                        jTree1.setSelectionPath(treePath);
                        jTree1.expandPath(treePath);
                        jTree1.scrollPathToVisible(treePath);
                        DefaultMutableTreeNode lastNode = (DefaultMutableTreeNode)treePath.getLastPathComponent();
                        
                        //Si se produjo en ND en la submáquina///////////////
                        if(((NodeTreeTrace)lastNode).contextoSubmaquina!=null && ((NodeTreeTrace)lastNode).contextoSubmaquina.rootTreeTrace!=null && ((NodeTreeTrace)lastNode).contextoSubmaquina.rootTreeTrace.estado==Maquina.ESTADO_ND){
                            calculatePath(lastNode);
                            while(lastNode.getNextNode()!=null)
                                treeModel.removeNodeFromParent(lastNode.getNextNode());
                            selectedNode = lastNode;
                            jButton18ActionPerformed(null);
                            return;
                        }
                        ////////////////////////////////////////////////////
                        
                        calculatePath(lastNode);
                        //System.out.println("paso 1");
                        if(lastNode.getNextNode()==null){
                            //System.out.println("paso 2");
                            NodeTreeTrace lastTrace = (NodeTreeTrace)lastNode;
                            if(lastTrace.contextoSubmaquina.rootTreeTrace.estado==Maquina.ESTADO_HALT ){
                                //System.out.println("paso 3");
                                selectedNode = lastTrace;
                                jButton18ActionPerformed(null);
                            }
                        }
                        //drawingMachinesArea.repaint();
                        //drawingTapesArea.repaint();
                        return;
                    }
                }
                
                calculatePath(selectedNode);
                
                /*if(selectedNode.isLeaf()){
                 
                 
                 
                    NodeTreeTrace rootNode = ((NodeTreeTrace)selectedNode).getMyRoot();
                 
                 
                    arrayOfTapes = rootNode.getArrayOfTapes();
                    for(int i=0;i<arrayOfTapes.length;i++)
                        arrayOfTapes[i].setValoresIniciales();
                 
                    currentDicMetavalores = rootNode.dicMetavalores;
                    currentDicMetavalores.setValoresIniciales();
                 
                    NodeTreeTrace auxNode = rootNode;
                    while(true){
                        int iconValue = ((NodeTreeTrace)auxNode).getIconValue();
                        if(!auxNode.isRoot() && iconValue != JTV.MyRenderer.ICONO_STOP && iconValue != JTV.MyRenderer.ICONO_WARNING && iconValue != JTV.MyRenderer.ICONO_EXPANDIR && iconValue != JTV.MyRenderer.ICONO_RECHAZA && iconValue != JTV.MyRenderer.ICONO_ND){
                            if(!(auxNode.getMachine() instanceof Submaquina)){
                                    auxNode.getMachine().accion(arrayOfTapes,currentDicMetavalores);
                            }
                            else{
                                Submaquina submaquina = (Submaquina)auxNode.getMachine();
                                int numeroCintas = ((Vector2)submaquina.machineComponents).getNumeroCintas();
                                Cinta[] arrayOfTapesSubmaquina = new Cinta[numeroCintas];
                                for(int i=1;i<numeroCintas;i++)
                                    arrayOfTapesSubmaquina[i] = new Cinta(38+Cinta.H,20*i,i+1);
                                arrayOfTapesSubmaquina[0] = arrayOfTapes[submaquina.getIndiceCinta()];
                                auxNode.contextoSubmaquina.accion(arrayOfTapesSubmaquina);
                 
                            }
                        }
                        if(auxNode==selectedNode) break;
                        auxNode = (NodeTreeTrace)auxNode.getNextNode();
                   }
                }
                else{
                 
                    arrayOfTapes = ((NodeTreeTrace)selectedNode).getArrayOfTapes();
                    for(int i=0;i<arrayOfTapes.length;i++)
                        arrayOfTapes[i].setValoresIniciales();
                 
                    currentDicMetavalores = ((NodeTreeTrace)selectedNode).dicMetavalores;
                    currentDicMetavalores.setValoresIniciales();
                }
                 
                 
                Maquina.playMachine = ((NodeTreeTrace)selectedNode).getMachine();
                if(Maquina.playMachine!=null)
                    Maquina.playMachine.setScrollBars(jScrollPane1);
                drawingMachinesArea.repaint();
                 
                drawingTapesArea.repaint();*/
                
                //**************************DESCOMENTAR***********************
                //System.out.println("INDICE 0="+arrayOfTapes[0].getIndiceCabezal());
                //System.out.println("CINTA 0="+arrayOfTapes[0].getCaracteres().toString());
                
            }
        });
        
        
    }
    
    private void calculatePath(DefaultMutableTreeNode selectedNode){
        
        if(selectedNode.isLeaf()){
            
            NodeTreeTrace rootNode = ((NodeTreeTrace)selectedNode).getMyRoot();
            //if(rootNode==null) return;
            
            arrayOfTapes = rootNode.getArrayOfTapes();
            for(int i=0;i<arrayOfTapes.length;i++)
                arrayOfTapes[i].setValoresIniciales();
            
            currentDicMetavalores = rootNode.dicMetavalores;
            //currentDicMetavalores.limpiar();
            currentDicMetavalores.setValoresIniciales();
            
            NodeTreeTrace auxNode = rootNode;
            while(true){
                int iconValue = ((NodeTreeTrace)auxNode).getIconValue();
                if(!auxNode.isRoot() && iconValue != JTV.MyRenderer.ICONO_STOP && iconValue != JTV.MyRenderer.ICONO_WARNING && iconValue != JTV.MyRenderer.ICONO_EXPANDIR && iconValue != JTV.MyRenderer.ICONO_RECHAZA && iconValue != JTV.MyRenderer.ICONO_ND){
                    if(!(auxNode.getMachine() instanceof Submaquina)){
                        //if(auxNode.getMachine() instanceof Escritora)
                        //    arrayOfTapes[auxNode.getMachine().getIndiceCinta()].escribir(auxNode.simboloEscrito);
                        //else
                        auxNode.getMachine().accion(arrayOfTapes,currentDicMetavalores);
                    } else{
                        Submaquina submaquina = (Submaquina)auxNode.getMachine();
                        int numeroCintas = ((Vector2)submaquina.machineComponents).getNumeroCintas();
                                /*Cinta[] arrayOfTapesSubmaquina = new Cinta[numeroCintas];
                                for(int i=1;i<numeroCintas;i++)
                                    arrayOfTapesSubmaquina[i] = new Cinta(38+Cinta.H,20*i,i+1);
                                arrayOfTapesSubmaquina[0] = arrayOfTapes[submaquina.getIndiceCinta()];
                                 
                                auxNode.contextoSubmaquina.accion(arrayOfTapesSubmaquina);*/
                        
                        auxNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes[0] = arrayOfTapes[submaquina.getIndiceCinta()];
                        //auxNode.contextoSubmaquina.accion(auxNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes);
                        
                        for(int i=1;i<auxNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes.length;i++)
                            auxNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes[i]=new Cinta(auxNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes0[i]);
                        auxNode.contextoSubmaquina.accion(auxNode.contextoSubmaquina.rootTreeTrace.arrayOfTapes);
                        
                        if(auxNode.contextoSubmaquina.rootTreeTrace.estado==Maquina.ESTADO_HALT){
                            auxNode.setIconValue(JTV.MyRenderer.ICONO_SUBMAQUINA);
                        } else if(auxNode.contextoSubmaquina.rootTreeTrace.estado==Maquina.ESTADO_COLGADA){
                            auxNode.setIconValue(JTV.MyRenderer.ICONO_SUBMAQUINA_COLGADA);
                        } else if(auxNode.contextoSubmaquina.rootTreeTrace.estado==Maquina.ESTADO_RECHAZA){
                            auxNode.setIconValue(JTV.MyRenderer.ICONO_SUBMAQUINA_ERROR);
                        } else if(auxNode.contextoSubmaquina.rootTreeTrace.estado==Maquina.ESTADO_ND){
                            auxNode.setIconValue(JTV.MyRenderer.ICONO_SUBMAQUINA_ND);
                        } else if(auxNode.contextoSubmaquina.rootTreeTrace.estado==Maquina.ESTADO_EXPANDIBLE){
                            auxNode.setIconValue(JTV.MyRenderer.ICONO_SUBMAQUINA_EXPANDIR);
                        }
                    }
                }
                if(auxNode==selectedNode) break;
                auxNode = (NodeTreeTrace)auxNode.getNextNode();
            }
        } else{
            
            arrayOfTapes = ((NodeTreeTrace)selectedNode).getArrayOfTapes();
            for(int i=0;i<arrayOfTapes.length;i++)
                arrayOfTapes[i].setValoresIniciales();
            
            currentDicMetavalores = ((NodeTreeTrace)selectedNode).dicMetavalores;
            //currentDicMetavalores.limpiar();
            currentDicMetavalores.setValoresIniciales();
        }
        
        
        Maquina.playMachine = ((NodeTreeTrace)selectedNode).getMachine();
        if(Maquina.playMachine!=null)
            Maquina.playMachine.setScrollBars(jScrollPane1);
        drawingMachinesArea.repaint();
        
        drawingTapesArea.repaint();
        
        
    }
    
    private void setTree2(){
        
        
        //DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
        //renderer.setLeafIcon(new ImageIcon(getClass().getResource("/images/L_pequenha.gif")));
        
        MyRenderer2 renderer = new MyRenderer2();
        
        //rootTreeTrace2 = new NodeTreeTrace(testTree,numberOfNodes,true,null,null,jTree2);
        //rootTreeTrace2.setRootTreeTrace(rootTreeTrace2);
        rootTreeTrace2 = new NodeTreeMachine("NUEVA");
        treeModel2 = new DefaultTreeModel(rootTreeTrace2);
        rootTreeTrace2.setTreeModel(treeModel2);
        treeModel2.addTreeModelListener(new MyTreeModelListener2());
        jTree2 = new javax.swing.JTree(treeModel2);
        //rootTreeTrace2.setJTree(jTree2);
        
        
        
        jTree2.getSelectionModel().setSelectionMode
                (TreeSelectionModel.SINGLE_TREE_SELECTION);
        jTree2.setShowsRootHandles(true);
        jTree2.setEditable(false);
        //JScrollPane treeVi = new JScrollPane(jTree1);
        jTree2.setScrollsOnExpand(true);
        jTree2.setCellRenderer(renderer);
        Dimension minimumSize = new Dimension(100, 50);
        jTree2.setMinimumSize(minimumSize);
        jTree2.putClientProperty("JTree.lineStyle", "Angled");
        //jSplitPane1.setLeftComponent(jTree1);
        //jSplitPane1.setLeftComponent(jScrollPane3);
        jTree2.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent e) {
                //DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                selectedNode2 = (DefaultMutableTreeNode) jTree2.getLastSelectedPathComponent();
                //NodeTreeTrace node = (NodeTreeTrace) jTree1.getLastSelectedPathComponent();
                //System.out.println("NODO DE MAQUINA");
                //if (node == null) return;
                if (selectedNode2 == null) return;
                
                /*Object obj[] = selectedNode2.getUserObjectPath();
                for(int n = 0;n<obj.length;n++){
                    System.out.println("obj[n]="+obj[n]);
                }*/
                
                /*Enumeration en2 = NodeTreeTrace.getCompletePathVector(selectedNode2).elements();
                while(en2.hasMoreElements()){
                    DefaultMutableTreeNode children = (DefaultMutableTreeNode)en2.nextElement();
                    System.out.println("userObject"+children.getUserObject());
                }*/
                
                
                NodeTreeMachine nodeTreeMachine = (NodeTreeMachine)selectedNode2;
                Vector2 vector2 = nodeTreeMachine.vector2;
                //if(vector2!=null){
                    /*System.out.println("-------------------------------------");
                    System.out.println(vector2.getNombreLargo());
                    System.out.println(vector2.getNombreCorto());
                    System.out.println(vector2.getDependencia());
                    System.out.println(vector2.isPrincipal());
                    System.out.println("-------------------------------------");*/
                //}
                
                //drawingMachine = ((NodeTreeTrace)selectedNode2).maquina;
                currentRepository = (String) selectedNode2.getUserObject();
                currentMachineComponents = getRepository(currentRepository);
                rootTreeTrace.setUserObject(currentRepository);
                //ACTUALIZO COMBOBOX DE SUBMAQUINAS
                jComboBox4.setEnabled(true);
                jComboBox4.removeAllItems();
                Enumeration en = selectedNode2.children();
                while(en.hasMoreElements()){
                    NodeTreeMachine node = (NodeTreeMachine)en.nextElement();
                    jComboBox4.addItem(node.getUserObject());
                }
                if(jComboBox4.getItemCount()==0) jComboBox4.setEnabled(false);
                //ACTUALIZO ARREGLO DE CINTAS Y COMBOBOX
                refreshTapes(vector2.getNumeroCintas());
                Comando.reset();
                Clipboard.reset();
                refreshSubmaquinas = true;
                drawingTapesArea.repaint();
                drawingMachinesArea.repaint();
                
            }
        });
        
        
    }
    
    public void setDicOfMachines(){
        
         /*this.dicOfMachines = new Hashtable();
         Vector2 principal = new Vector2();
         principal.setNombreLargo("PRINCIPAL");
         principal.setNombreCorto("PRI");
         principal.setDescripcion("Es la máquina principal");
         principal.setNumeroCintas(4);
         principal.setPrincipal(true);
         principal.setMonocinta(false);
         this.dicOfMachines.put("PRINCIPAL",principal);
         Vector2 sumadora = new Vector2();
         sumadora.setNombreLargo("SUMADORA");
         sumadora.setNombreCorto("SUM");
         sumadora.setDescripcion("Es la máquina sumadora");
         sumadora.setNumeroCintas(4);
         sumadora.setDependencia("PRINCIPAL");
         sumadora.setPrincipal(false);
         sumadora.setMonocinta(false);
         this.dicOfMachines.put("SUMADORA",sumadora);
         this.jComboBox4.addItem("SUMADORA");
         Vector2 monus = new Vector2();
         monus.setNombreLargo("MONUS");
         monus.setNombreCorto("MON");
         monus.setDescripcion("Es la máquina monus");
         monus.setNumeroCintas(3);
         monus.setDependencia("PRINCIPAL");
         monus.setPrincipal(false);
         monus.setMonocinta(false);
         this.dicOfMachines.put("MONUS",monus);
         this.jComboBox4.addItem("MONUS"); */
        
        this.dicOfMachines = new Hashtable();
        Vector2 principal = new Vector2();
        principal.setNombreLargo("NUEVA");
        principal.setNombreCorto("NUEV");
        principal.setDescripcion("");
        principal.setNumeroCintas(JTV.numeroCintas); //Temporal
        principal.setPrincipal(true);
        principal.setMonocinta(false);
        this.dicOfMachines.put("NUEVA",principal);
        currentRepository = "NUEVA";
        currentMachineComponents = principal;
        /*Aquí se agregan las submáquinas predefinidas*/
        
        //for(int i=0;i<JTV.MAXIMO_NUMERO_CINTAS;i++){
        
        Vector2 buscadora_L = new Vector2();
        buscadora_L.setNombreLargo("BUSCADORA_L"); // + i);
        buscadora_L.setNombreCorto("");
        buscadora_L.setNumeroCintas(1);
        this.dicOfMachines.put("BUSCADORA_L",buscadora_L);
        build_BUSCADORA_L();
        
        Vector2 buscadora_R = new Vector2();
        buscadora_R.setNombreLargo("BUSCADORA_R"); // + i);
        buscadora_R.setNombreCorto("");
        buscadora_R.setNumeroCintas(1);
        this.dicOfMachines.put("BUSCADORA_R",buscadora_R);
        build_BUSCADORA_R();
        
        Vector2 buscadora_L_NOT = new Vector2();
        buscadora_L_NOT.setNombreLargo("BUSCADORA_L_NOT");  // + i);
        buscadora_L_NOT.setNombreCorto("");
        buscadora_L_NOT.setNumeroCintas(1);
        this.dicOfMachines.put("BUSCADORA_L_NOT",buscadora_L_NOT);
        build_BUSCADORA_L_NOT();
        
        Vector2 buscadora_R_NOT = new Vector2();
        buscadora_R_NOT.setNombreLargo("BUSCADORA_R_NOT"); // + i);
        buscadora_R_NOT.setNombreCorto("");
        buscadora_R_NOT.setNumeroCintas(1);
        this.dicOfMachines.put("BUSCADORA_R_NOT",buscadora_R_NOT);
        build_BUSCADORA_R_NOT();
        
        Vector2 shift_L = new Vector2();
        shift_L.setNombreLargo("SHIFT_L"); // + i);
        shift_L.setNombreCorto("");
        shift_L.setNumeroCintas(1);
        this.dicOfMachines.put("SHIFT_L",shift_L);
        build_SHIFT_L();
        
        Vector2 shift_R = new Vector2();
        shift_R.setNombreLargo("SHIFT_R"); // + i);
        shift_R.setNombreCorto("");
        shift_R.setNumeroCintas(1);
        this.dicOfMachines.put("SHIFT_R",shift_R);
        build_SHIFT_R();
        //}
        
    }
    
    private void addMachineIntoDic(Maquina maquina,String repositorio){
        
        ((Vector)dicOfMachines.get(repositorio)).add(maquina);
        JTV.modifiedMachine = true;
        
    }
    
    private void removeMachineFromDic(Maquina maquina,String repositorio){
        
        ((Vector)dicOfMachines.get(repositorio)).remove(maquina);
    }
    
    private Vector getRepository(String repositorio){
        
        
        return (Vector)dicOfMachines.get(repositorio);
        
    }
    
    public void build_BUSCADORA_L(){
        
        int indexCinta = 0;
        L maquinaL = new L(200,200,indexCinta,null,null);
        EnlaceCompuesto enlaceCompuesto = new EnlaceCompuesto(maquinaL);
        AutoEnlace autoEnlace = new AutoEnlace(0,0,indexCinta,maquinaL,AutoEnlace.ESTE);
        enlaceCompuesto.insertar(autoEnlace);
        maquinaL.setProxMaquina(enlaceCompuesto);
        autoEnlace.condicionEnlace.agregaOperandoDerecho("A",indexCinta);
        autoEnlace.condicionEnlace.agregaOperandoNot(Boolean.TRUE,indexCinta);
        //autoEnlace.condicionEnlace.setNot(true);
        this.addMachineIntoDic(maquinaL,"BUSCADORA_L");
        this.addMachineIntoDic(autoEnlace,"BUSCADORA_L");
        
    }
    
    public void build_BUSCADORA_L_NOT(){
        
        int indexCinta=0;
        L maquinaL = new L(200,200,indexCinta,null,null);
        EnlaceCompuesto enlaceCompuesto = new EnlaceCompuesto(maquinaL);
        AutoEnlace autoEnlace = new AutoEnlace(0,0,indexCinta,maquinaL,AutoEnlace.ESTE);
        enlaceCompuesto.insertar(autoEnlace);
        maquinaL.setProxMaquina(enlaceCompuesto);
        autoEnlace.condicionEnlace.agregaOperandoDerecho("A",indexCinta);
        autoEnlace.condicionEnlace.agregaOperandoNot(Boolean.FALSE,indexCinta);
        //autoEnlace.condicionEnlace.setNot(false);
        this.addMachineIntoDic(maquinaL,"BUSCADORA_L_NOT");
        this.addMachineIntoDic(autoEnlace,"BUSCADORA_L_NOT");
        
    }
    
    
    public void build_BUSCADORA_R(){
        
        int indexCinta=0;
        R maquinaR = new R(200,200,indexCinta,null,null);
        EnlaceCompuesto enlaceCompuesto = new EnlaceCompuesto(maquinaR);
        AutoEnlace autoEnlace = new AutoEnlace(0,0,indexCinta,maquinaR,AutoEnlace.ESTE);
        enlaceCompuesto.insertar(autoEnlace);
        maquinaR.setProxMaquina(enlaceCompuesto);
        autoEnlace.condicionEnlace.agregaOperandoDerecho("A",indexCinta);
        autoEnlace.condicionEnlace.agregaOperandoNot(Boolean.TRUE,indexCinta);
        //autoEnlace.condicionEnlace.setNot(true);
        this.addMachineIntoDic(maquinaR,"BUSCADORA_R");
        this.addMachineIntoDic(autoEnlace,"BUSCADORA_R");
    }
    
    public void build_BUSCADORA_R_NOT(){
        
        int indexCinta=0;
        R maquinaR = new R(200,200,indexCinta,null,null);
        EnlaceCompuesto enlaceCompuesto = new EnlaceCompuesto(maquinaR);
        AutoEnlace autoEnlace = new AutoEnlace(0,0,indexCinta,maquinaR,AutoEnlace.ESTE);
        enlaceCompuesto.insertar(autoEnlace);
        maquinaR.setProxMaquina(enlaceCompuesto);
        autoEnlace.condicionEnlace.agregaOperandoDerecho("A",indexCinta);
        autoEnlace.condicionEnlace.agregaOperandoNot(Boolean.FALSE,indexCinta);
        //autoEnlace.condicionEnlace.setNot(false);
        this.addMachineIntoDic(maquinaR,"BUSCADORA_R_NOT");
        this.addMachineIntoDic(autoEnlace,"BUSCADORA_R_NOT");
    }
    
    public void build_SHIFT_L(){
        
        int indexCinta=0;
        Submaquina buscadoraLBlanco = new Submaquina(150,200,indexCinta,null,null);
        buscadoraLBlanco.setNombre("L");
        buscadoraLBlanco.setNombreLargo("BUSCADORA_L");
        buscadoraLBlanco.setNombreCorto("");
        Parametro parametro = new Parametro("A");
        parametro.setValor(Simbolo.getSimbolo("#"));
        buscadoraLBlanco.parametros.put("A",parametro);
        buscadoraLBlanco.machineComponents = getRepository(buscadoraLBlanco.getNombreLargo());
        this.addMachineIntoDic(buscadoraLBlanco,"SHIFT_L");
        
        R maquinaR1 = new R(200,200,indexCinta,null,null);
        this.addMachineIntoDic(maquinaR1,"SHIFT_L");
        
        L maquinaL1 = new L(350,200,indexCinta,null,null);
        //this.addMachineIntoDic(maquinaL1,"SHIFT_L_"+indexCinta);
        
        Escritora sigma = new Escritora(350,200,indexCinta,null,null,Hellada.getChar(Hellada.SIGMA));
        this.addMachineIntoDic(sigma,"SHIFT_L");
        //maquinaL1.insertMachine(sigma,false,getRepository("SHIFT_L_"+indexCinta));
        
        R maquinaR2 = new R(350,200,indexCinta,null,null);
        sigma.insertMachine(maquinaL1,true,getRepository("SHIFT_L"));
        sigma.insertMachine(maquinaR2,false,getRepository("SHIFT_L"));
        
        L maquinaL2 = new L(200,300,indexCinta,null,null);
        this.addMachineIntoDic(maquinaL2,"SHIFT_L");
        
        Escritora blanco = new Escritora(200,300,indexCinta,null,null,"#");
        maquinaL2.insertMachine(blanco,false,getRepository("SHIFT_L"));
        
        EnlaceCompuesto enlaceCompuesto1 = new EnlaceCompuesto(buscadoraLBlanco);
        buscadoraLBlanco.setProxMaquina(enlaceCompuesto1);
        Enlace enlace1 = new Enlace(0,0,0,buscadoraLBlanco,maquinaR1);
        enlace1.condicionEnlace.agregaOperandoNot(Boolean.FALSE,indexCinta);
        //enlace1.condicionEnlace.setNot(false);
        enlaceCompuesto1.insertar(enlace1);
        this.addMachineIntoDic(enlace1,"SHIFT_L");
        
        EnlaceCompuesto enlaceCompuesto2 = new EnlaceCompuesto(maquinaR1);
        maquinaR1.setProxMaquina(enlaceCompuesto2);
        Enlace enlace2 = new Enlace(0,0,0,maquinaR1,maquinaL1);
        enlace2.condicionEnlace.agregaOperandoIzquierdo(Hellada.getChar(Hellada.SIGMA),indexCinta);
        enlace2.condicionEnlace.agregaOperandoDerecho("#",indexCinta);
        enlace2.condicionEnlace.agregaOperandoNot(Boolean.TRUE,indexCinta);
        //enlace2.condicionEnlace.setNot(true);
        enlaceCompuesto2.insertar(enlace2);
        this.addMachineIntoDic(enlace2,"SHIFT_L");
        
        EnlaceCompuesto enlaceCompuesto3 = new EnlaceCompuesto(maquinaR2);
        maquinaR2.setProxMaquina(enlaceCompuesto3);
        Enlace enlace3 = new Enlace(0,0,0,maquinaR2,maquinaR1);
        enlace3.agregaPunto(420,190);
        enlace3.agregaPunto(420,150);
        enlace3.agregaPunto(200,150);
        //enlace3.condicionEnlace.agregaOperandoNot(Boolean.FALSE,indexCinta);
        enlaceCompuesto3.insertar(enlace3);
        this.addMachineIntoDic(enlace3,"SHIFT_L");
        
        //EnlaceCompuesto enlaceCompuesto4 = new EnlaceCompuesto(maquinaR1);
        Enlace enlace4 = new Enlace(0,0,0,maquinaR1,maquinaL2);
        enlace4.condicionEnlace.agregaOperandoDerecho("#",indexCinta);
        enlace4.condicionEnlace.agregaOperandoNot(Boolean.FALSE,indexCinta);
        enlaceCompuesto2.insertar(enlace4);
        this.addMachineIntoDic(enlace4,"SHIFT_L");
    }
    
    public void build_SHIFT_R(){
        
         /*Submaquina buscadoraLBlanco = new Submaquina(150,200,indexCinta,null,null);
         buscadoraLBlanco.setNombre("L");
         buscadoraLBlanco.setNombreLargo("BUSCADORA_L_" + indexCinta);
         buscadoraLBlanco.setNombreCorto("");
         Parametro parametro = new Parametro("A");
         parametro.setValor(Simbolo.getSimbolo("#"));
         buscadoraLBlanco.parametros.put("A",parametro);
         buscadoraLBlanco.machineComponents = getRepository(buscadoraLBlanco.getNombreLargo());
         this.addMachineIntoDic(buscadoraLBlanco,"SHIFT_L_"+indexCinta);*/
        int indexCinta=0;
        L maquinaL0 = new L(200,200,indexCinta,null,null);
        this.addMachineIntoDic(maquinaL0,"SHIFT_R");
        
        Escritora blanco0 = new Escritora(370,200,indexCinta,null,null,"#");
        
        R maquinaR0 = new R(370,200,indexCinta,null,null);
        
        Escritora sigma = new Escritora(370,200,indexCinta,null,null,Hellada.getChar(Hellada.SIGMA));
        
        L maquinaL1 = new L(370,200,indexCinta,null,null);
        
        this.addMachineIntoDic(maquinaL1,"SHIFT_R");
        
        maquinaL1.insertMachine(blanco0,true,getRepository("SHIFT_R"));
        maquinaL1.insertMachine(maquinaR0,true,getRepository("SHIFT_R"));
        maquinaL1.insertMachine(sigma,true,getRepository("SHIFT_R"));
        
        Submaquina buscadoraRBlanco1 = new Submaquina(200,300,indexCinta,null,null);
        buscadoraRBlanco1.setNombre("R");
        buscadoraRBlanco1.setNombreLargo("BUSCADORA_R");
        buscadoraRBlanco1.setNombreCorto("");
        Parametro parametro1 = new Parametro("A");
        parametro1.setValor(Simbolo.getSimbolo("#"));
        buscadoraRBlanco1.parametros.put("A",parametro1);
        buscadoraRBlanco1.machineComponents = getRepository(buscadoraRBlanco1.getNombreLargo());
        this.addMachineIntoDic(buscadoraRBlanco1,"SHIFT_R");
        
        Submaquina buscadoraRBlanco2 = new Submaquina(200,300,indexCinta,null,null);
        buscadoraRBlanco2.setNombre("R");
        buscadoraRBlanco2.setNombreLargo("BUSCADORA_R");
        buscadoraRBlanco2.setNombreCorto("");
        Parametro parametro2 = new Parametro("A");
        parametro2.setValor(Simbolo.getSimbolo("#"));
        buscadoraRBlanco2.parametros.put("A",parametro2);
        buscadoraRBlanco2.machineComponents = getRepository(buscadoraRBlanco2.getNombreLargo());
        buscadoraRBlanco1.insertMachine(buscadoraRBlanco2,false,getRepository("SHIFT_R"));
        
        
        
         /*EnlaceCompuesto enlaceCompuesto1 = new EnlaceCompuesto(buscadoraLBlanco);
         buscadoraLBlanco.setProxMaquina(enlaceCompuesto1);
         Enlace enlace1 = new Enlace(0,0,0,buscadoraLBlanco,maquinaR1);
         enlace1.condicionEnlace.setNot(false);
         enlaceCompuesto1.insertar(enlace1);
         this.addMachineIntoDic(enlace1,"SHIFT_R_"+indexCinta);*/
        
        EnlaceCompuesto enlaceCompuesto2 = new EnlaceCompuesto(maquinaL0);
        maquinaL0.setProxMaquina(enlaceCompuesto2);
        Enlace enlace2 = new Enlace(0,0,0,maquinaL0,blanco0);
        enlace2.condicionEnlace.agregaOperandoIzquierdo(Hellada.getChar(Hellada.SIGMA),indexCinta);
        enlace2.condicionEnlace.agregaOperandoDerecho("#",indexCinta);
        enlace2.condicionEnlace.agregaOperandoNot(Boolean.TRUE,indexCinta);
        //enlace2.condicionEnlace.setNot(true);
        enlaceCompuesto2.insertar(enlace2);
        this.addMachineIntoDic(enlace2,"SHIFT_R");
        
        EnlaceCompuesto enlaceCompuesto3 = new EnlaceCompuesto(maquinaL1);
        maquinaL1.setProxMaquina(enlaceCompuesto3);
        Enlace enlace3 = new Enlace(0,0,0,maquinaL1,maquinaL0);
        enlace3.agregaPunto(420,190);
        enlace3.agregaPunto(420,150);
        enlace3.agregaPunto(200,150);
        enlaceCompuesto3.insertar(enlace3);
        this.addMachineIntoDic(enlace3,"SHIFT_R");
        
        //EnlaceCompuesto enlaceCompuesto4 = new EnlaceCompuesto(maquinaR1);
        Enlace enlace4 = new Enlace(0,0,0,maquinaL0,buscadoraRBlanco1);
        enlace4.condicionEnlace.agregaOperandoDerecho("#",indexCinta);
        enlace4.condicionEnlace.agregaOperandoNot(Boolean.FALSE,indexCinta);
        enlaceCompuesto2.insertar(enlace4);
        this.addMachineIntoDic(enlace4,"SHIFT_R");
    }
    
    
    public void setTapesPanel(int _numOfTapes){
        
        int numOfTapes = _numOfTapes;
        arrayOfTapes = new Cinta[numOfTapes];
        
        for(int i=0;i<numOfTapes;i++)
            arrayOfTapes[i] = new Cinta(38+Cinta.H,Cinta.SEPARACION*i,i+1);
        
        
        
        //arrayOfTapes[0].cargar("aabcbcba");
         /*for(int p=0;p<10;p++)
            arrayOfTapes[0].mover_R();
         for(int p=0;p<3;p++)
            arrayOfTapes[0].mover_L();
          */
        drawingTapesArea = new JPanel() {
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                for(int i=0;i<arrayOfTapes.length;i++)
                    try{
                        arrayOfTapes[i].findCabezal();
                        arrayOfTapes[i].dibujar(g);
                    } catch(NonSetException ex){
                        
                    }
                
            }
            
        };
        
        java.awt.event.MouseListener ml = new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent e) {
                if(Maquina.running) return;
                //System.out.println((e.getX()-arrayOfTapes[0].x0)/Cinta.H);
                for(int i=0;i<arrayOfTapes.length;i++)
                    if(arrayOfTapes[i].x0<=e.getX() && e.getX()<=(arrayOfTapes[i].x0+(2*Cinta.VECINDAD+1)*Cinta.H) && arrayOfTapes[i].y0<=e.getY() && e.getY()<=arrayOfTapes[i].y0+Cinta.H){
                    int index = (e.getX()-arrayOfTapes[0].x0)/Cinta.H;//+(arrayOfTapes[i].getIndiceCabezal()/(2*Cinta.VECINDAD+1))*(2*Cinta.VECINDAD+1);
                    //System.out.println("index="+index);
                    //System.out.println("pageBrowse="+arrayOfTapes[i].getPageBrowse());
                    index+=(arrayOfTapes[i].getPageBrowse()*(2*Cinta.VECINDAD+1));
                    //System.out.println("incremento="+arrayOfTapes[i].getPageBrowse()*(2*Cinta.VECINDAD+1));
                    arrayOfTapes[i].setIndiceCabezal(index);
                    arrayOfTapes[i].setIndiceCabezal0(index);
                    //System.out.println("indexCinta="+arrayOfTapes[i].getIndiceCabezal());
                    //System.out.println("indice="+arrayOfTapes[i].getPageBrowse()*2*(Cinta.VECINDAD+1));
                    
                    if(writeTape!=null) writeTape.writeMode = false;
                    writeTape = arrayOfTapes[i];
                    writeTape.writeMode = true;
                    //System.out.println("Cinta "+(i+1));
                    //System.out.println("Posición"+(e.getX()-arrayOfTapes[0].x0)/Cinta.H);
                    break;
                    }
                
                
                drawingTapesArea.repaint();
                //System.out.println(((2*Cinta.VECINDAD+1)*Cinta.H-arrayOfTapes[0].x0)/(e.getX()-arrayOfTapes[0].x0));
                
            }
            
            public void mouseEntered(java.awt.event.MouseEvent e) {
                
                //System.out.println("mouseEntered tapes");
                drawingTapesArea.requestFocus();
                
            }
            
            public void mouseExited(java.awt.event.MouseEvent e) {
                if(Maquina.running) return;
                //System.out.println("mouseExited tapes");
                drawingTapesArea.transferFocus();
                if(writeTape!=null){
                    writeTape.writeMode = false;
                    writeTape = null;
                }
                drawingTapesArea.repaint();
            }
        };
        
        
        java.awt.event.MouseMotionListener mml = new java.awt.event.MouseMotionAdapter() {
            
            public void mouseMoved(java.awt.event.MouseEvent e) {
                
                //if(Maquina.running) return;
                //System.out.println((e.getX()-arrayOfTapes[0].x0)/Cinta.H);
                for(int i=0;i<arrayOfTapes.length;i++)
                    if(arrayOfTapes[i].x0<=e.getX() && e.getX()<=(arrayOfTapes[i].x0+(2*Cinta.VECINDAD+1)*Cinta.H) && arrayOfTapes[i].y0<=e.getY() && e.getY()<=arrayOfTapes[i].y0+Cinta.H){
                    int index = (e.getX()-arrayOfTapes[0].x0)/Cinta.H;//+(arrayOfTapes[i].getIndiceCabezal()/(2*Cinta.VECINDAD+1))*(2*Cinta.VECINDAD+1);
                    //System.out.println("index="+index);
                    //System.out.println("pageBrowse="+arrayOfTapes[i].getPageBrowse());
                    index+=(arrayOfTapes[i].getPageBrowse()*(2*Cinta.VECINDAD+1));
                    //System.out.println("incremento="+arrayOfTapes[i].getPageBrowse()*(2*Cinta.VECINDAD+1));
                    drawingTapesArea.setToolTipText((i+1)+"["+index+"]");
                    break;
                    } else
                        drawingTapesArea.setToolTipText(null);
            }
            
            public void mouseDragged(java.awt.event.MouseEvent e) {
                
                //System.out.println("mouseDragged tapes");
                
            }
            
            
        };
        
         /*jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                keyPressedHandler(evt);
            }
        });*/
        
        java.awt.event.KeyListener kl = new java.awt.event.KeyAdapter() {
            
            public void keyPressed(java.awt.event.KeyEvent e) {
                
                if(Maquina.running) return;
                if(writeTape==null) return;
                char c = e.getKeyChar();
                if(e.getKeyCode()==e.VK_LEFT){
                    writeTape.decrCabezal();
                    drawingTapesArea.repaint();
                    return;
                }
                if(e.getKeyCode()==e.VK_RIGHT){
                    writeTape.incrCabezal();
                    drawingTapesArea.repaint();
                    return;
                }
                if(e.getKeyCode()==e.VK_DELETE){
                    writeTape.cargar(Simbolo.getSimbolo('#'));
                    drawingTapesArea.repaint();
                    return;
                }
                if(!CondicionEnlace.isNombreSimbolo(String.valueOf(c))) return;
                writeTape.cargar(Simbolo.getSimbolo(c));
                drawingTapesArea.repaint();
            }
            
             /*public void keyTyped(java.awt.event.KeyEvent e) {
              
                 System.out.println("keyTyped tapes");
              
             }*/
        };
        
        java.awt.event.FocusListener fl = new java.awt.event.FocusAdapter() {
            
            public void focusGained(java.awt.event.FocusEvent e) {
                //System.out.println("Focus gained");
            }
            
            public void focusLost(java.awt.event.FocusEvent e) {
                //System.out.println("Focus lost");
            }
            
        };
        
        drawingTapesArea.addMouseListener(ml);
        drawingTapesArea.addMouseMotionListener(mml);
        drawingTapesArea.addKeyListener(kl);
        drawingTapesArea.addFocusListener(fl);
        
        
        
        
        
        drawingTapesArea.setBackground(Color.white);
        drawingTapesArea.setAutoscrolls(true);
//        drawingTapesArea.scrollRectToVisible(new Rectangle(0,0,830,200));
//        drawingTapesArea.setPreferredSize(new Dimension(830,200));
        drawingTapesArea.scrollRectToVisible(new Rectangle(0,0,1550,200));
        drawingTapesArea.setPreferredSize(new Dimension(1550,200));
        drawingTapesArea.revalidate();
        drawingTapesArea.updateUI();
        
        this.jScrollPane2 = new javax.swing.JScrollPane(drawingTapesArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//        this.jScrollPane2.setPreferredSize(new Dimension(600,50));
        //this.jScrollPane2.setPreferredSize(new Dimension(1500,50));
        this.jScrollPane2.setAutoscrolls(true);
        
        
        this.jPanel5.remove(0);
        //this.jPanel5.add(this.drawingTapesArea);
        this.jPanel5.add(this.jScrollPane2);
        this.rootTreeTrace.setTape(arrayOfTapes[0]);
        this.playTreeTrace.setTape(arrayOfTapes[0]);
        this.rootTreeTrace.setArrayOfTapes(arrayOfTapes);
        this.playTreeTrace.setArrayOfTapes(arrayOfTapes);
        
    }
    
    
    public void setMachinesPanel(){
        
        
        this.rootTreeTrace.setMachine(mainMachine);
        this.playTreeTrace.setMachine(mainMachine);
        
        
        drawingMachinesArea = new DrawingMachinesArea() {
            protected void paintComponent(Graphics g) {
                
                if(DialogPropiedades.editingMode) return;
                super.paintComponent(g);
                
                
                if((estadoJTV==JTV.ESTADO_ENLACE || estadoJTV==JTV.ESTADO_ENLACE_CONDICIONAL) && maquinaI!=null){
                    g.setColor(Color.magenta);
                    g.drawLine(pressedX,pressedY,movedX,movedY);
                    for(int i=0;i<puntosEnlace.size()-1;i++){
                        Point p0=(Point)puntosEnlace.get(i);
                        Point p1=(Point)puntosEnlace.get(i+1);
                        g.drawLine((int)p0.getX(),(int)p0.getY(),(int)p1.getX(),(int)p1.getY());
                    }
                    g.setColor(Color.black);
                }
                
                if(estadoJTV==JTV.ESTADO_PUNTERO && JTV.draggedType==JTV.DRAGGED_CLIPBOARD){
                    
                    
                    Clipboard.x0 = firstPressedX;
                    Clipboard.y0 = firstPressedY;
                    Clipboard.x1 = pressedX;
                    Clipboard.y1 = pressedY;
                    
                    Clipboard.drawClipboard(g);
                }
                
                currentMachineComponents = getRepository(currentRepository);
                
                if(refreshSubmaquinas){
                    ((Vector2)currentMachineComponents).refreshSubmaquinas();
                    refreshSubmaquinas = false;
                }
                
                for(int i=0;i<currentMachineComponents.size();i++)
                    ((Maquina)currentMachineComponents.get(i)).dibujar(g);
                cursor.dibujar(g);
                
                
            }
        };
        
        
        java.awt.event.MouseListener ml = new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent e) {
                boolean ans;
                if(Maquina.running) return;
                //if(searchedMachine==null) return;
                
                String out=null;
                switch(estadoJTV){
                    case JTV.ESTADO_INICIAL: out=null; break;
                    case JTV.ESTADO_AUTOENLACE:
                        if(searchedMachine!=null && searchedMachine.proxima instanceof EnlaceCompuesto){
                            if(((EnlaceCompuesto)searchedMachine.proxima).hasAutoenlace()){
                                JOptionPane.showMessageDialog(null, "No se permite la inserción de más de un autoenlace sobre una máquina","JTV",JOptionPane.WARNING_MESSAGE);
                                return;
                            }
                            AutoEnlace autoEnlace = new AutoEnlace(0,0,0,searchedMachine,AutoEnlace.ESTE);
                            int returnStatus = autoEnlace.showDialog(arrayOfTapes.length,false);
                            if(returnStatus==DialogAutoenlace.RET_CANCEL) return;
                            ((EnlaceCompuesto)searchedMachine.proxima).insertar(autoEnlace);
                            ComandoIE comandoIE = new ComandoIE(autoEnlace,(Vector2)currentMachineComponents);
                            Comando.addComando2UR(comandoIE);
                            addMachineIntoDic(autoEnlace,currentRepository);
                            drawingMachinesArea.repaint();
                        } else if(searchedMachine!=null && searchedMachine.proxima==null && searchedMachine.esEnlazable()){
                            AutoEnlace autoEnlace = new AutoEnlace(0,0,0,searchedMachine,AutoEnlace.ESTE);
                            int returnStatus = autoEnlace.showDialog(arrayOfTapes.length,false);
                            if(returnStatus==DialogAutoenlace.RET_CANCEL) return;
                            if(searchedMachine.proxima==null){
                                EnlaceCompuesto enlaceCompuesto = new EnlaceCompuesto(searchedMachine); //added
                                searchedMachine.setProxMaquina(enlaceCompuesto);
                                enlaceCompuesto.insertar(autoEnlace);
                                ComandoIE comandoIE = new ComandoIE(autoEnlace,(Vector2)currentMachineComponents);
                                Comando.addComando2UR(comandoIE);
                                addMachineIntoDic(autoEnlace,currentRepository);
                                drawingMachinesArea.repaint();
                            }
                        }
                        //out="flechaVuelta";
                        break;
                    case JTV.ESTADO_BLANCO:
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            insertMachine = new Escritora(searchedMachine.x0,searchedMachine.y0,jComboBox2.getSelectedIndex(),null,null,"#");
                            searchedMachine.insertMachine(insertMachine,leftInsert,currentMachineComponents);
                            
                            Comando.addComando2UR(new ComandoEM(insertMachine,(Vector2)currentMachineComponents));
                            Comando.addComando2UR(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            
                            drawingMachinesArea.repaint();
                            
                        } else{
                            insertMachine = new Escritora(e.getX(),e.getY(),jComboBox2.getSelectedIndex(),null,null,"#");
                            addMachineIntoDic(insertMachine,currentRepository);
                            
                            Comando.addComando2UR(new ComandoEM(insertMachine,(Vector2)currentMachineComponents));
                            Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                            
                            drawingMachinesArea.repaint();
                        }
                        out="Blank";
                        break;
                    case JTV.ESTADO_CONCENTRADOR:
                        insertMachine = new Concentrador(e.getX(),e.getY(),0,null,null);
                        
                        Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                        addMachineIntoDic(insertMachine,currentRepository);
                        drawingMachinesArea.repaint();
                        break;
                    case JTV.ESTADO_COPIADORA: out="C"; break;
                    case JTV.ESTADO_ENLACE:case JTV.ESTADO_ENLACE_CONDICIONAL:
                        if(e.getButton()==e.BUTTON3){
                            maquinaI = maquinaF = null;
                            puntosEnlace.clear();
                            drawingMachinesArea.repaint();
                            return;
                        }
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            if(maquinaI==null){
                                maquinaI=searchedMachine;
                                pressedX=e.getX();
                                pressedY=e.getY();
                                puntosEnlace.add(new Point(pressedX,pressedY));
                            } else if(maquinaF==null){
                                maquinaF=searchedMachine;
                                if(maquinaI.proxima instanceof EnlaceCompuesto){
                                    Enumeration ne = ((EnlaceCompuesto)maquinaI.proxima).getEnlaces();
                                    while(ne.hasMoreElements()){
                                        Enlace enlace = (Enlace) ne.nextElement();
                                        if(enlace.proxima==maquinaF){
                                            maquinaI = maquinaF = null;
                                            puntosEnlace.clear();
                                            drawingMachinesArea.repaint();
                                            JOptionPane.showMessageDialog(new JPanel(),"Ya existe una transición entre estas Máquinas.","JTV",JOptionPane.ERROR_MESSAGE);
                                            //System.out.println("ENLACE REPETIDO");
                                            return;
                                        }
                                    }
                                    Enlace enlace = new Enlace(0,0,0,maquinaI,maquinaF);
                                    if(estadoJTV==JTV.ESTADO_ENLACE_CONDICIONAL){
                                        int returnStatus = enlace.showDialog(arrayOfTapes.length,false);
                                        if(returnStatus==DialogEnlace.RET_CANCEL){
                                            maquinaI = maquinaF = null;
                                            puntosEnlace.clear();
                                            drawingMachinesArea.repaint();
                                            return;
                                        }
                                    }
                                    Enumeration en = puntosEnlace.elements();
                                    boolean firstNo = true;
                                    while(en.hasMoreElements()){
                                        Point p=(Point) en.nextElement();
                                        if(firstNo){firstNo=false; continue;}
                                        enlace.agregaPunto((int)p.getX(),(int)p.getY());
                                    }
                                    /*Enumeration en = puntosEnlace.elements();
                                    while(en.hasMoreElements()){
                                      Point p=(Point) en.nextElement();
                                      enlace.agregaPunto((int)p.getX(),(int)p.getY());
                                    }*/
                                    ((EnlaceCompuesto)maquinaI.proxima).insertar(enlace);
                                    ComandoIE comandoIE = new ComandoIE(enlace,(Vector2)currentMachineComponents);
                                    Comando.addComando2UR(comandoIE);
                                    addMachineIntoDic(enlace,currentRepository);
                                } else if(maquinaI.proxima==null){
                                    EnlaceCompuesto enlaceCompuesto = new EnlaceCompuesto(maquinaI); //added
                                    maquinaI.setProxMaquina(enlaceCompuesto);
                                    Enlace enlace = new Enlace(0,0,0,maquinaI,maquinaF);
                                    if(estadoJTV==JTV.ESTADO_ENLACE_CONDICIONAL){
                                        int returnStatus = enlace.showDialog(arrayOfTapes.length,false);
                                        if(returnStatus==DialogEnlace.RET_CANCEL){
                                            maquinaI = maquinaF = null;
                                            puntosEnlace.clear();
                                            drawingMachinesArea.repaint();
                                            return;
                                        }
                                    }
                                    Enumeration en = puntosEnlace.elements();
                                    boolean firstNo = true;
                                    while(en.hasMoreElements()){
                                        Point p=(Point) en.nextElement();
                                        if(firstNo){firstNo=false; continue;}
                                        enlace.agregaPunto((int)p.getX(),(int)p.getY());
                                    }
                                    enlaceCompuesto.insertar(enlace);
                                    ComandoIE comandoIE = new ComandoIE(enlace,(Vector2)currentMachineComponents);
                                    Comando.addComando2UR(comandoIE);
                                    addMachineIntoDic(enlace,currentRepository);
                                } else{
                                    JOptionPane.showMessageDialog(new JPanel(),"No se puede insertar una Transición que parta de una máquina que está entre al comienzo o al medio de un grupo de máquinas.","JTV",JOptionPane.ERROR_MESSAGE);
                                }
                                maquinaI = maquinaF = null;
                                puntosEnlace.clear();
                                drawingMachinesArea.repaint();
                            }
                        } else{
                            if(maquinaI==null) return;
                            pressedX=e.getX();
                            pressedY=e.getY();
                            puntosEnlace.add(new Point(pressedX,pressedY));
                        }
                        //this.drawingMachinesArea.repaint();
                        out="flecha";
                        break;
                        //case JTV.ESTADO_ENLACE_CONDICIONAL: out="flechasigma"; break;
                    case JTV.ESTADO_L:
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            insertMachine = new L(searchedMachine.x0,searchedMachine.y0,jComboBox2.getSelectedIndex(),null,null);
                            searchedMachine.insertMachine(insertMachine,leftInsert,currentMachineComponents);
                            
                            //Comando.addComando2UR(new ComandoEM(insertMachine,(Vector2)currentMachineComponents));
                            //if(!leftInsert)
                            //    Comando.addComando2URInverse(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            //else
                            Comando.addComando2UR(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            
                            drawingMachinesArea.repaint();
                            
                        } else{
                            insertMachine = new L(e.getX(),e.getY(),jComboBox2.getSelectedIndex(),null,null);
                            addMachineIntoDic(insertMachine,currentRepository);
                            
                            //Comando.addComando2UR(new ComandoEM(insertMachine,(Vector2)currentMachineComponents));
                            Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                            drawingMachinesArea.repaint();
                        }
                        
                        out="L";
                        break;
                    case JTV.ESTADO_L_NO_SIGMA:
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            insertMachine = new Submaquina(searchedMachine.x0,searchedMachine.y0,jComboBox2.getSelectedIndex(),null,null);
                            //this.submaquina1 = new Submaquina(130,100,0,null,null);
                            ((Submaquina)insertMachine).setNombre("L");
                            ((Submaquina)insertMachine).setNombreLargo("BUSCADORA_L_NOT");
                            ((Submaquina)insertMachine).setNombreCorto("");
                            ((Submaquina)insertMachine).setNot(true);
                            ((Submaquina)insertMachine).setMonocinta(true);
                            Parametro parametro = new Parametro("A");
                            parametro.setValor(Simbolo.getSimbolo((String)jComboBox1.getSelectedItem()));
                            ((Submaquina)insertMachine).parametros.put("A",parametro);
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            searchedMachine.insertMachine(insertMachine,leftInsert,currentMachineComponents);
                            Comando.addComando2UR(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            drawingMachinesArea.repaint();
                        } else{
                            insertMachine = new Submaquina(e.getX(),e.getY(),jComboBox2.getSelectedIndex(),null,null);
                            ((Submaquina)insertMachine).setNombre("L");
                            ((Submaquina)insertMachine).setNombreLargo("BUSCADORA_L_NOT");
                            ((Submaquina)insertMachine).setNombreCorto("");
                            ((Submaquina)insertMachine).setNot(true);
                            ((Submaquina)insertMachine).setMonocinta(true);
                            Parametro parametro = new Parametro("A");
                            parametro.setValor(Simbolo.getSimbolo((String)jComboBox1.getSelectedItem()));
                            ((Submaquina)insertMachine).parametros.put("A",parametro);
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                            addMachineIntoDic(insertMachine,currentRepository);
                            drawingMachinesArea.repaint();
                        }
                        out="L!sigma"; break;
                    case JTV.ESTADO_L_SIGMA:
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            insertMachine = new Submaquina(searchedMachine.x0,searchedMachine.y0,jComboBox2.getSelectedIndex(),null,null);
                            //this.submaquina1 = new Submaquina(130,100,0,null,null);
                            ((Submaquina)insertMachine).setNombre("L");
                            ((Submaquina)insertMachine).setNombreLargo("BUSCADORA_L");
                            ((Submaquina)insertMachine).setNombreCorto("");
                            ((Submaquina)insertMachine).setMonocinta(true);
                            Parametro parametro = new Parametro("A");
                            parametro.setValor(Simbolo.getSimbolo((String)jComboBox1.getSelectedItem()));
                            ((Submaquina)insertMachine).parametros.put("A",parametro);
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            searchedMachine.insertMachine(insertMachine,leftInsert,currentMachineComponents);
                            Comando.addComando2UR(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            drawingMachinesArea.repaint();
                        } else{
                            insertMachine = new Submaquina(e.getX(),e.getY(),jComboBox2.getSelectedIndex(),null,null);
                            ((Submaquina)insertMachine).setNombre("L");
                            ((Submaquina)insertMachine).setNombreLargo("BUSCADORA_L");
                            ((Submaquina)insertMachine).setNombreCorto("");
                            ((Submaquina)insertMachine).setMonocinta(true);
                            Parametro parametro = new Parametro("A");
                            parametro.setValor(Simbolo.getSimbolo((String)jComboBox1.getSelectedItem()));
                            ((Submaquina)insertMachine).parametros.put("A",parametro);
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                            addMachineIntoDic(insertMachine,currentRepository);
                            drawingMachinesArea.repaint();
                        }
                        out="Lsigma"; break;
                    case JTV.ESTADO_PUNTERO:
                        Maquina.selectedMachine = searchedMachine;
                        if(e.getClickCount()==1){
                            
                            if(Maquina.selectedMachine instanceof Enlace)
                                searchedPoint = ((Enlace)Maquina.selectedMachine).getNearestPoint(e.getX(),e.getY());
                            else
                                searchedPoint = null;
                            Clipboard.sendMessage(Maquina.selectedMachine!=null);
                            if(Maquina.selectedMachine!=null)
                                Clipboard.setEnabledCutCopy(!(Maquina.selectedMachine instanceof Enlace));
                            pressedX = firstPressedX = e.getX();
                            pressedY = firstPressedY = e.getY();
                            drawingMachinesArea.repaint();
                            JTV.draggedType = JTV.DRAGGED_NOTHING;
                        } else{
                            if(Maquina.selectedMachine!=null) Maquina.selectedMachine.showDialog(arrayOfTapes.length,true);
                            drawingMachinesArea.repaint();
                        }
                        break;
                    case JTV.ESTADO_R:
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            insertMachine = new R(searchedMachine.x0,searchedMachine.y0,jComboBox2.getSelectedIndex(),null,null);
                            searchedMachine.insertMachine(insertMachine,leftInsert,currentMachineComponents);
                            Comando.addComando2UR(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            drawingMachinesArea.repaint();
                            
                        } else{
                            insertMachine = new R(e.getX(),e.getY(),jComboBox2.getSelectedIndex(),null,null);
                            addMachineIntoDic(insertMachine,currentRepository);
                            
                            Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                            
                            drawingMachinesArea.repaint();
                        }
                        
                        break;
                    case JTV.ESTADO_R_NO_SIGMA:
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            insertMachine = new Submaquina(searchedMachine.x0,searchedMachine.y0,jComboBox2.getSelectedIndex(),null,null);
                            //this.submaquina1 = new Submaquina(130,100,0,null,null);
                            ((Submaquina)insertMachine).setNombre("R");
                            ((Submaquina)insertMachine).setNombreLargo("BUSCADORA_R_NOT");
                            ((Submaquina)insertMachine).setNombreCorto("");
                            ((Submaquina)insertMachine).setNot(true);
                            ((Submaquina)insertMachine).setMonocinta(true);
                            Parametro parametro = new Parametro("A");
                            parametro.setValor(Simbolo.getSimbolo((String)jComboBox1.getSelectedItem()));
                            ((Submaquina)insertMachine).parametros.put("A",parametro);
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            searchedMachine.insertMachine(insertMachine,leftInsert,currentMachineComponents);
                            Comando.addComando2UR(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            drawingMachinesArea.repaint();
                        } else{
                            insertMachine = new Submaquina(e.getX(),e.getY(),jComboBox2.getSelectedIndex(),null,null);
                            ((Submaquina)insertMachine).setNombre("R");
                            ((Submaquina)insertMachine).setNombreLargo("BUSCADORA_R_NOT");
                            ((Submaquina)insertMachine).setNombreCorto("");
                            ((Submaquina)insertMachine).setNot(true);
                            ((Submaquina)insertMachine).setMonocinta(true);
                            Parametro parametro = new Parametro("A");
                            parametro.setValor(Simbolo.getSimbolo((String)jComboBox1.getSelectedItem()));
                            ((Submaquina)insertMachine).parametros.put("A",parametro);
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                            addMachineIntoDic(insertMachine,currentRepository);
                            drawingMachinesArea.repaint();
                        }
                        out="R!sigma"; break;
                    case JTV.ESTADO_R_SIGMA:
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            insertMachine = new Submaquina(searchedMachine.x0,searchedMachine.y0,jComboBox2.getSelectedIndex(),null,null);
                            //this.submaquina1 = new Submaquina(130,100,0,null,null);
                            ((Submaquina)insertMachine).setNombre("R");
                            ((Submaquina)insertMachine).setNombreLargo("BUSCADORA_R");
                            ((Submaquina)insertMachine).setNombreCorto("");
                            ((Submaquina)insertMachine).setMonocinta(true);
                            Parametro parametro = new Parametro("A");
                            parametro.setValor(Simbolo.getSimbolo((String)jComboBox1.getSelectedItem()));
                            ((Submaquina)insertMachine).parametros.put("A",parametro);
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            searchedMachine.insertMachine(insertMachine,leftInsert,currentMachineComponents);
                            Comando.addComando2UR(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            drawingMachinesArea.repaint();
                        } else{
                            insertMachine = new Submaquina(e.getX(),e.getY(),jComboBox2.getSelectedIndex(),null,null);
                            ((Submaquina)insertMachine).setNombre("R");
                            ((Submaquina)insertMachine).setNombreLargo("BUSCADORA_R");
                            ((Submaquina)insertMachine).setNombreCorto("");
                            ((Submaquina)insertMachine).setMonocinta(true);
                            Parametro parametro = new Parametro("A");
                            parametro.setValor(Simbolo.getSimbolo((String)jComboBox1.getSelectedItem()));
                            ((Submaquina)insertMachine).parametros.put("A",parametro);
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                            addMachineIntoDic(insertMachine,currentRepository);
                            drawingMachinesArea.repaint();
                        }
                        out="Rsigma"; break;
                    case JTV.ESTADO_SIGMA:case JTV.ESTADO_PARAMETRO:
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            insertMachine = new Escritora(searchedMachine.x0,searchedMachine.y0,jComboBox2.getSelectedIndex(),null,null,JTV.estadoJTV==JTV.ESTADO_SIGMA?(String)jComboBox3.getSelectedItem():(String)jComboBox5.getSelectedItem());
                            searchedMachine.insertMachine(insertMachine,leftInsert,currentMachineComponents);
                            Comando.addComando2UR(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            drawingMachinesArea.repaint();
                        } else{
                            insertMachine = new Escritora(e.getX(),e.getY(),jComboBox2.getSelectedIndex(),null,null,JTV.estadoJTV==JTV.ESTADO_SIGMA?(String)jComboBox3.getSelectedItem():(String)jComboBox5.getSelectedItem());
                            Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                            addMachineIntoDic(insertMachine,currentRepository);
                            drawingMachinesArea.repaint();
                        }
                        out="sigma";
                        break;
                    case JTV.ESTADO_SIMBOLO:
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            insertMachine = new Escritora(searchedMachine.x0,searchedMachine.y0,jComboBox2.getSelectedIndex(),null,null,(String)jComboBox1.getSelectedItem());
                            searchedMachine.insertMachine(insertMachine,leftInsert,currentMachineComponents);
                            Comando.addComando2UR(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            drawingMachinesArea.repaint();
                            /*if(ans){
                                addMachineIntoDic(insertMachine,currentRepository);
                                drawingMachinesArea.repaint();
                            }*/
                        } else{
                            insertMachine = new Escritora(e.getX(),e.getY(),jComboBox2.getSelectedIndex(),null,null,(String)jComboBox1.getSelectedItem());
                            Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                            addMachineIntoDic(insertMachine,currentRepository);
                            drawingMachinesArea.repaint();
                        }
                        out="a"; break;
                    case JTV.ESTADO_SL:
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            insertMachine = new Submaquina(searchedMachine.x0,searchedMachine.y0,jComboBox2.getSelectedIndex(),null,null);
                            //this.submaquina1 = new Submaquina(130,100,0,null,null);
                            ((Submaquina)insertMachine).setNombre("S");
                            ((Submaquina)insertMachine).setNombreLargo("SHIFT_L");
                            ((Submaquina)insertMachine).setNombreCorto("");
                            ((Submaquina)insertMachine).setMonocinta(true);
                            Parametro parametro = new Parametro("L");
                            ((Submaquina)insertMachine).parametros.put("L",parametro);
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            searchedMachine.insertMachine(insertMachine,leftInsert,currentMachineComponents);
                            Comando.addComando2UR(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            drawingMachinesArea.repaint();
                        } else{
                            insertMachine = new Submaquina(e.getX(),e.getY(),jComboBox2.getSelectedIndex(),null,null);
                            ((Submaquina)insertMachine).setNombre("S");
                            ((Submaquina)insertMachine).setNombreLargo("SHIFT_L");
                            ((Submaquina)insertMachine).setNombreCorto("");
                            ((Submaquina)insertMachine).setMonocinta(true);
                            Parametro parametro = new Parametro("L");
                            ((Submaquina)insertMachine).parametros.put("L",parametro);
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                            addMachineIntoDic(insertMachine,currentRepository);
                            drawingMachinesArea.repaint();
                        }
                        out="SL"; break;
                    case JTV.ESTADO_SR:
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            insertMachine = new Submaquina(searchedMachine.x0,searchedMachine.y0,jComboBox2.getSelectedIndex(),null,null);
                            //this.submaquina1 = new Submaquina(130,100,0,null,null);
                            ((Submaquina)insertMachine).setNombre("S");
                            ((Submaquina)insertMachine).setNombreLargo("SHIFT_R");
                            ((Submaquina)insertMachine).setNombreCorto("");
                            ((Submaquina)insertMachine).setMonocinta(true);
                            Parametro parametro = new Parametro("R");
                            ((Submaquina)insertMachine).parametros.put("R",parametro);
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            searchedMachine.insertMachine(insertMachine,leftInsert,currentMachineComponents);
                            Comando.addComando2UR(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            drawingMachinesArea.repaint();
                        } else{
                            insertMachine = new Submaquina(e.getX(),e.getY(),jComboBox2.getSelectedIndex(),null,null);
                            ((Submaquina)insertMachine).setNombre("S");
                            ((Submaquina)insertMachine).setNombreLargo("SHIFT_R");
                            ((Submaquina)insertMachine).setNombreCorto("");
                            ((Submaquina)insertMachine).setMonocinta(true);
                            Parametro parametro = new Parametro("R");
                            ((Submaquina)insertMachine).parametros.put("R",parametro);
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                            addMachineIntoDic(insertMachine,currentRepository);
                            drawingMachinesArea.repaint();
                        }
                        out="SR"; break;
                    case JTV.ESTADO_SUBMAQUINA:
                        if(searchedMachine!=null && searchedMachine.esEnlazable()){
                            insertMachine = new Submaquina(searchedMachine.x0,searchedMachine.y0,jComboBox2.getSelectedIndex(),null,null);
                            //this.submaquina1 = new Submaquina(130,100,0,null,null);
                            ((Submaquina)insertMachine).setNombreLargo((String)jComboBox4.getSelectedItem());
                            String nombreLargo = ((Submaquina)insertMachine).getNombreLargo();
                            ((Submaquina)insertMachine).setNombreCorto(nombreLargo.substring(0,Math.min(nombreLargo.length(),4)));
                            //((Submaquina)insertMachine).setNombreCorto(((Submaquina)insertMachine).getNombreLargo().substring(0,3));
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            ((Submaquina)insertMachine).refreshParametros(false);
                            searchedMachine.insertMachine(insertMachine,leftInsert,currentMachineComponents);
                            Comando.addComando2UR(new ComandoIMG(searchedMachine,(Vector2)currentMachineComponents,insertMachine,leftInsert));
                            drawingMachinesArea.repaint();
                        } else{
                            insertMachine = new Submaquina(e.getX(),e.getY(),jComboBox2.getSelectedIndex(),null,null);
                            ((Submaquina)insertMachine).setNombreLargo((String)jComboBox4.getSelectedItem());
                            String nombreLargo = ((Submaquina)insertMachine).getNombreLargo();
                            ((Submaquina)insertMachine).setNombreCorto(nombreLargo.substring(0,Math.min(nombreLargo.length(),4)));
                            //((Submaquina)insertMachine).setNombreCorto(((Submaquina)insertMachine).getNombreLargo().substring(0,3));
                            ((Submaquina)insertMachine).machineComponents = getRepository(((Submaquina)insertMachine).getNombreLargo());
                            ((Submaquina)insertMachine).refreshParametros(false);
                            Comando.addComando2UR(new ComandoIML(insertMachine,(Vector2)currentMachineComponents));
                            addMachineIntoDic(insertMachine,currentRepository);
                            drawingMachinesArea.repaint();
                        }
                        
                        out="M"; break;
                }
                
                
            }
            
            public void mouseExited(java.awt.event.MouseEvent e) {
                
                //JTV.searchedMachine=null;
                drawingMachinesArea.repaint();
            }
            
            public void mouseReleased(java.awt.event.MouseEvent e) {
                
                if(JTV.draggedType==JTV.DRAGGED_MACHINE && searchedMachine!=null){
                    ComandoMM comandoMM = new ComandoMM(searchedMachine,null,e.getX()-firstPressedX,e.getY()-firstPressedY);
                    comandoMM.setInverse(new ComandoMM(searchedMachine,null,-e.getX()+firstPressedX,-e.getY()+firstPressedY));
                    Comando.addComando2UR(comandoMM);
                    searchedMachine=null;
                } else if(JTV.draggedType==JTV.DRAGGED_POINT && searchedPoint!=null){
                    ComandoEVE comandoEVE = new ComandoEVE(searchedPoint,null,e.getX(),e.getY());
                    comandoEVE.setInverse(new ComandoEVE(searchedPoint,null,firstPressedX,firstPressedY));
                    Comando.addComando2UR(comandoEVE);
                    searchedPoint=null;
                } else if(JTV.draggedType==JTV.DRAGGED_CLIPBOARD){
                    //Clipboard.setEnabled(true);
                    if(!Clipboard.isValidClipboard()) {
                        Clipboard.setEnabled(false);
                        drawingMachinesArea.repaint();
                        return;
                    }
                    
                    Clipboard.sendMessage(true);
                    Clipboard.setState(Clipboard.STATE_NOTHING);
                    //System.out.println("sendMessage(true)");
                } else{
                    
                    Clipboard.sendMessage(Maquina.selectedMachine!=null);
                    if(Maquina.selectedMachine!=null)
                        Clipboard.setEnabledCutCopy(!(Maquina.selectedMachine instanceof Enlace));
                }
                
                //JTV.draggedType = JTV.DRAGGED_NOTHING;
            }
            
        };
        
        java.awt.event.MouseMotionListener mml = new java.awt.event.MouseMotionAdapter() {
            
            public void mouseMoved(java.awt.event.MouseEvent e) {
                
                if(Maquina.running) return;
                
                movedX = e.getX();
                movedY = e.getY();
                
                if(currentMachineComponents==null){
                    //System.out.println("currentMachineComponents==null");
                    return;
                }
                
                if(currentMachineComponents.size()==0){
                    //System.out.println("currentMachineComponents==null");
                    return;
                }
                
                
                for(int i=0;i<currentMachineComponents.size();i++){
                    if(((Maquina)currentMachineComponents.get(i)).boundRectangle!=null){
                        //if(((Maquina)currentMachineComponents.get(i)).boundRectangle.contains(e.getX(),e.getY())){
                        if(((Maquina)currentMachineComponents.get(i)).leftRectangle.contains(e.getX(),e.getY())){
                            searchedMachine = (Maquina)currentMachineComponents.get(i);
                            cursor.x = (int)searchedMachine.leftRectangle.getMinX()-2;
                            cursor.y = (int)searchedMachine.leftRectangle.getMinY()-2;
                            cursor.activar();
                            drawingMachinesArea.repaint(); //cursor.x,cursor.y,2,30);
                            
                            //System.out.println("left");
                            if(searchedMachine instanceof Submaquina){
                                drawingMachinesArea.setToolTipText(((Vector2)((Submaquina)searchedMachine).machineComponents).getNombreLargo());
                            }
                            leftInsert = true;
                            
                            return;
                        } else if(((Maquina)currentMachineComponents.get(i)).rightRectangle.contains(e.getX(),e.getY())){
                            searchedMachine = (Maquina)currentMachineComponents.get(i);
                            cursor.x = (int)searchedMachine.rightRectangle.getMaxX()+2;
                            cursor.y = (int)searchedMachine.rightRectangle.getMinY()-2;
                            cursor.activar();
                            drawingMachinesArea.repaint(); //cursor.x,cursor.y,2,30);
                            if(searchedMachine instanceof Submaquina){
                                drawingMachinesArea.setToolTipText(((Vector2)((Submaquina)searchedMachine).machineComponents).getNombreLargo());
                            }
                            leftInsert = false;
                            
                            //System.out.println("right");
                            return;
                        } else{
                            searchedMachine = null;
                            drawingMachinesArea.setToolTipText(null);
                            cursor.desactivar();
                            repaint();
                        }
                    } else{
                        //if(((Enlace)currentMachineComponents.get(i)).isMouseClicked(e.getX(),e.getY())){
                        if(((Maquina)currentMachineComponents.get(i)).isMouseClicked(e.getX(),e.getY())){
                            //searchedMachine = (Enlace)currentMachineComponents.get(i);
                            searchedMachine = (Maquina) currentMachineComponents.get(i);
                            drawingMachinesArea.setToolTipText(null);
                            //System.out.println("Enlace");
                            ///AGREGADO TEMPORALMENTE//////////////
                            //Operandos operandos = new Operandos(((Enlace)currentMachineComponents.get(i)));
                            //operandos.fillOperandos();
                            //operandos.print();
                            //System.out.println(operandos.getLatex(7));
                            //////////
                            return;
                        }
                        drawingMachinesArea.setToolTipText(null);
                        searchedMachine = null;
                        cursor.desactivar();
                        repaint();
                        //return;
                    }
                }
                
            }
            
            
            public void mouseDragged(java.awt.event.MouseEvent e) {
                
                if(Maquina.running) return;
                
                //if(estadoJTV!=JTV.ESTADO_PUNTERO || searchedMachine==null) return;
                
                if(estadoJTV==JTV.ESTADO_PUNTERO && searchedMachine!=null){
                    if(!(searchedMachine instanceof Enlace)) {
                        searchedMachine.mover(e.getX()-pressedX,e.getY()-pressedY);
                        JTV.draggedType = JTV.DRAGGED_MACHINE;
                        JTV.modifiedMachine = true;
                    } else if(searchedPoint!=null){
                        searchedPoint.setLocation(e.getX(),e.getY());
                        JTV.draggedType = JTV.DRAGGED_POINT;
                        JTV.modifiedMachine = true;
                    }
                } else if(estadoJTV==JTV.ESTADO_PUNTERO && searchedMachine==null){
                    JTV.draggedType = JTV.DRAGGED_CLIPBOARD;
                    Clipboard.setEnabled(true);
                    //System.out.println("DRAGGED_CLIPBOARD");
                }
                pressedX = e.getX();
                pressedY = e.getY();
                cursor.desactivar();
                drawingMachinesArea.repaint();
                
                
            }
            
        };
        
        drawingMachinesArea.addMouseListener(ml);
        drawingMachinesArea.addMouseMotionListener(mml);
        
        drawingMachinesArea.setBackground(Color.white);
        drawingMachinesArea.setAutoscrolls(true);
//        drawingMachinesArea.scrollRectToVisible(new Rectangle(0,0,1500,1500));
//        drawingMachinesArea.setPreferredSize(new Dimension(1500,1500));
        drawingMachinesArea.scrollRectToVisible(new Rectangle(0,0,1500,1159));
        drawingMachinesArea.setPreferredSize(new Dimension(1500,1159));
        drawingMachinesArea.revalidate();
        drawingMachinesArea.updateUI();
        
        this.jScrollPane1 = new javax.swing.JScrollPane(drawingMachinesArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        
        
        this.jScrollPane1.setAutoscrolls(true);
        this.jSplitPane1.setRightComponent(this.jScrollPane1);
        
        
        rootTreeTrace2.setUserObject("NUEVA");
        
        this.currentRepository = "NUEVA";
        rootTreeTrace2.vector2 = (Vector2)this.getRepository("NUEVA");
        this.jComboBox4.setEnabled(false);
        
    }
    
    class PopupListener extends java.awt.event.MouseAdapter {
        public void mousePressed(java.awt.event.MouseEvent e) {
            maybeShowPopup(e);
        }
        
        public void mouseReleased(java.awt.event.MouseEvent e) {
            maybeShowPopup(e);
            //drawingMachinesArea.repaint();
        }
        
        private void maybeShowPopup(java.awt.event.MouseEvent e) {
            if (e.isPopupTrigger()) {
                if(Maquina.running) return;
                
                if(estadoJTV!=JTV.ESTADO_PUNTERO) return;
                popup.getComponent(1).setEnabled(true);
                if(Maquina.selectedMachine==null){
                    for(int i=0;i<popup.getComponentCount();i++){
                        popup.getComponent(i).setEnabled(false);
                    }
                    popup.getComponent(4).setEnabled(true);
                    popup.show(e.getComponent(),e.getX(), e.getY());
                    drawingMachinesArea.repaint();
                    return;
                } else{
                    for(int i=0;i<popup.getComponentCount();i++){
                        popup.getComponent(i).setEnabled(true);
                    }
                    popup.getComponent(4).setEnabled(false);
                    //popup.getComponentAtIndex(0).setEnabled(true);
                    if((!Maquina.selectedMachine.esEnlazable())||Maquina.selectedMachine instanceof Concentrador){
                        popup.getComponent(0).setEnabled(false);
                        popup.getComponent(1).setEnabled(false);
                    }
                    if(Maquina.selectedMachine instanceof Enlace){
                        popup.getComponent(2).setEnabled(false);
                        popup.getComponent(3).setEnabled(false);
                    }
                    if(Maquina.selectedMachine.previa!=null)
                        popup.getComponent(0).setEnabled(false);
                    //if(Maquina.selectedMachine instanceof Concentrador)
                    //popup.getComponentAtIndex(1).setEnabled(false);
                    popup.show(e.getComponent(),e.getX(), e.getY());
                    drawingMachinesArea.repaint();
                }
                
            }
        }
    }
    
    class PopupListener2 extends java.awt.event.MouseAdapter {
        public void mousePressed(java.awt.event.MouseEvent e) {
            maybeShowPopup(e);
        }
        
        public void mouseReleased(java.awt.event.MouseEvent e) {
            maybeShowPopup(e);
        }
        
        private void maybeShowPopup(java.awt.event.MouseEvent e) {
            if (e.isPopupTrigger()) {
                
                popup2.getComponent(2).setEnabled(!((Vector2)currentMachineComponents).isPrincipal());
                popup2.getComponent(4).setEnabled(copycutTreeMachine!=null);
                popup2.getComponent(5).setEnabled(!((Vector2)currentMachineComponents).isPrincipal());
                
                popup2.show(e.getComponent(),
                        e.getX(), e.getY());
                // drawingMachinesArea.repaint();
                
            }
        }
    }
    
    class MyMenuListener implements javax.swing.event.MenuListener{
        
        private void maybeShowMenu(javax.swing.event.MenuEvent menuEvent){
            
            JMenu popup = (JMenu)menuEvent.getSource();
            
            if(estadoJTV!=JTV.ESTADO_PUNTERO){
                for(int i=2;i<popup.getMenuComponentCount();i++)
                    popup.getMenuComponent(i).setEnabled(false);
                popup.getMenuComponent(6).setEnabled(true);
                return;
            }
            popup.getMenuComponent(3).setEnabled(true);
            if(Maquina.selectedMachine==null){
                /*for(int i=2;i<popup.getMenuComponentCount();i++){
                   popup.getMenuComponent(i).setEnabled(false);
                }*/
                popup.getMenuComponent(2).setEnabled(false);
                popup.getMenuComponent(3).setEnabled(false);
                popup.getMenuComponent(4).setEnabled(jButton15.isEnabled());
                popup.getMenuComponent(5).setEnabled(jButton16.isEnabled());
                popup.getMenuComponent(6).setEnabled(true);
                popup.getMenuComponent(7).setEnabled(jButton19.isEnabled());
                return;
            } else{
                for(int i=2;i<popup.getMenuComponentCount();i++){
                    popup.getMenuComponent(i).setEnabled(true);
                }
                popup.getMenuComponent(6).setEnabled(false);
                //popup.getComponentAtIndex(0).setEnabled(true);
                if((!Maquina.selectedMachine.esEnlazable())||Maquina.selectedMachine instanceof Concentrador){
                    popup.getMenuComponent(2).setEnabled(false);
                    popup.getMenuComponent(3).setEnabled(false);
                }
                if(Maquina.selectedMachine instanceof Enlace){
                    popup.getMenuComponent(4).setEnabled(false);
                    popup.getMenuComponent(5).setEnabled(false);
                }
                if(Maquina.selectedMachine.previa!=null)
                    popup.getMenuComponent(2).setEnabled(false);
            }
        }
        
        public void menuSelected(javax.swing.event.MenuEvent menuEvent) {
            
            maybeShowMenu(menuEvent);
            
        }
        
        
        public void menuDeselected(javax.swing.event.MenuEvent menuEvent) {
            
            //maybeShowMenu(menuEvent);
            
        }
        
        
        public void menuCanceled(javax.swing.event.MenuEvent menuEvent) {
            
            
            
        }
        
        
        
    }
    
    class MyTreeModelListener implements TreeModelListener {
        public void treeNodesChanged(TreeModelEvent e) {
            DefaultMutableTreeNode node;
            node = (DefaultMutableTreeNode)
            (e.getTreePath().getLastPathComponent());
            
            /*
             * If the event lists children, then the changed
             * node is the child of the node we've already
             * gotten.  Otherwise, the changed node and the
             * specified node are the same.
             */
            try {
                int index = e.getChildIndices()[0];
                node = (DefaultMutableTreeNode)
                (node.getChildAt(index));
            } catch (NullPointerException exc) {}
            
            //System.out.println("The user has finished editing the node.");
            //System.out.println("New value: " + node.getUserObject());
        }
        public void treeNodesInserted(TreeModelEvent e) {
        }
        public void treeNodesRemoved(TreeModelEvent e) {
        }
        public void treeStructureChanged(TreeModelEvent e) {
            synchronized(flagContexto){
                if(flagContexto.isContextChange()){
                    //Thread contextThread = new Thread(flagContexto);
                    //contextThread.start();
                    ////System.out.println("jTree1.setSelectionPath(treePath);");
                    jTree1.setSelectionPath(treePath);
                    jTree1.expandPath(treePath);
                    drawingMachinesArea.repaint();
                    drawingTapesArea.repaint();
                    //System.out.println("CHANGE!!!");
                }
            }
        }
    }
    
    class MyTreeModelListener2 implements TreeModelListener {
        public void treeNodesChanged(TreeModelEvent e) {
            
            //if(!jButton3.isEnabled()) jButton3.setEnabled(true);
        }
        public void treeNodesInserted(TreeModelEvent e) {
            if(!jButton3.isEnabled()) jButton3.setEnabled(true);
        }
        public void treeNodesRemoved(TreeModelEvent e) {
            if(!jButton3.isEnabled()) jButton3.setEnabled(true);
        }
        public void treeStructureChanged(TreeModelEvent e) {
            
        }
    }
    
    private String getIconFilenameFromState(){
        String out=null;
        switch(this.estadoJTV){
            case JTV.ESTADO_INICIAL: out=null; break;
            case JTV.ESTADO_AUTOENLACE: out="flechaVuelta"; break;
            case JTV.ESTADO_BLANCO: out="Blank"; break;
            case JTV.ESTADO_CONCENTRADOR: out="ball"; break;
            case JTV.ESTADO_COPIADORA: out="C"; break;
            case JTV.ESTADO_ENLACE:
                out="flecha";
                //if(this.showDialogEnlace) out+="sigma";
                break;
            case JTV.ESTADO_ENLACE_CONDICIONAL: out="flechasigma"; break;
            case JTV.ESTADO_L: out=Maquina.oldNotation?"L":"LDH"; break;
            case JTV.ESTADO_L_NO_SIGMA: out=Maquina.oldNotation?"L!sigma":"LDH!sigma"; break;
            case JTV.ESTADO_L_SIGMA: out=Maquina.oldNotation?"Lsigma":"LDHsigma"; break;
            case JTV.ESTADO_PUNTERO: out="puntero"; break;
            case JTV.ESTADO_R: out=Maquina.oldNotation?"R":"RDH"; break;
            case JTV.ESTADO_R_NO_SIGMA: out=Maquina.oldNotation?"R!sigma":"RDH!sigma"; break;
            case JTV.ESTADO_R_SIGMA: out=Maquina.oldNotation?"Rsigma":"RDHsigma"; break;
            case JTV.ESTADO_SIGMA: out="sigma"; break;
            case JTV.ESTADO_SIMBOLO: out="a"; break;
            case JTV.ESTADO_SL: out="SL"; break;
            case JTV.ESTADO_SR: out="SR"; break;
            case JTV.ESTADO_SUBMAQUINA: out="M"; break;
            case JTV.ESTADO_PARAMETRO: out="A_"; break;
        }
        
        return out;
    }
    
    public void changeIconBottonFromNotation(){
        
        this.jButton6.setIcon(new ImageIcon(getClass().getResource(jButton6==lastPressedButton?(Maquina.oldNotation?"/images/L_push.gif":"/images/LDH_push.gif"):(Maquina.oldNotation?"/images/L.gif":"/images/LDH.gif"))));
        this.jButton7.setIcon(new ImageIcon(getClass().getResource(jButton7==lastPressedButton?(Maquina.oldNotation?"/images/Lsigma_push.gif":"/images/LDHsigma_push.gif"):(Maquina.oldNotation?"/images/Lsigma.gif":"/images/LDHsigma.gif"))));
        this.jButton8.setIcon(new ImageIcon(getClass().getResource(jButton8==lastPressedButton?(Maquina.oldNotation?"/images/L!sigma_push.gif":"/images/LDH!sigma_push.gif"):(Maquina.oldNotation?"/images/L!sigma.gif":"/images/LDH!sigma.gif"))));
        this.jButton12.setIcon(new ImageIcon(getClass().getResource(jButton12==lastPressedButton?(Maquina.oldNotation?"/images/R_push.gif":"/images/RDH_push.gif"):(Maquina.oldNotation?"/images/R.gif":"/images/RDH.gif"))));
        this.jButton23.setIcon(new ImageIcon(getClass().getResource(jButton23==lastPressedButton?(Maquina.oldNotation?"/images/Rsigma_push.gif":"/images/RDHsigma_push.gif"):(Maquina.oldNotation?"/images/Rsigma.gif":"/images/RDHsigma.gif"))));
        this.jButton24.setIcon(new ImageIcon(getClass().getResource(jButton24==lastPressedButton?(Maquina.oldNotation?"/images/R!sigma_push.gif":"/images/RDH!sigma_push.gif"):(Maquina.oldNotation?"/images/R!sigma.gif":"/images/RDH!sigma.gif"))));
        
    }
    
    private void changePressedButton(JButton pressedButton,int newState){
        
        if(Maquina.running) return;
        
        if(getIconFilenameFromState()!=null){
            String lastIconFilename = "/images/"+getIconFilenameFromState()+".gif";
            this.lastPressedButton.setIcon(new ImageIcon(getClass().getResource(lastIconFilename)));
        }
        this.estadoJTV=newState;
        String iconFilename = "/images/"+getIconFilenameFromState()+"_push.gif";
        pressedButton.setIcon(new ImageIcon(getClass().getResource(iconFilename)));
        lastPressedButton = pressedButton;
        
        this.drawingMachinesArea.repaint();
    }
    
    
    private void enableTapesComponents(boolean enable){
        
        
        this.jButton33.setEnabled(enable);
        this.jButton34.setEnabled(enable);
        this.jButton35.setEnabled(enable);
        this.jButton39.setEnabled(enable);
        this.jTextField1.setEnabled(enable);
        
    }
    
    private void enableUpperCombobox(boolean enable){
        
        this.jComboBox1.setEnabled(enable);
        this.jComboBox3.setEnabled(enable);
        this.jComboBox5.setEnabled(enable);
        this.jComboBox4.setEnabled(enable);
        
    }
    
    private void enableUpperButtons(boolean enable){
        
        this.jButton1.setEnabled(enable);
        this.jButton2.setEnabled(enable);
        this.jButton3.setEnabled(enable);
        this.jButton4.setEnabled(enable);
        this.jButton13.setEnabled(enable);
        this.jButton14.setEnabled(enable);
        this.jButton15.setEnabled(enable);
        this.jButton16.setEnabled(enable);
        this.jButton17.setEnabled(enable);
        this.jButton19.setEnabled(enable);
        this.jButton20.setEnabled(enable);
        //this.jButton20.d
        
    }
    
    private void enableMenus(boolean enable){
        
        this.jMenu1.setEnabled(enable);
        this.jMenu2.setEnabled(enable);
        this.jMenu4.setEnabled(enable);
    }
    
    
    private void enableMachinesToobars(boolean enable){
        
        Component[] t1 = this.jToolBar2.getComponents();
        for(int i=0;i<t1.length;i++)
            t1[i].setEnabled(enable);
        t1=null;
        t1 = this.jToolBar3.getComponents();
        for(int i=0;i<t1.length;i++)
            t1[i].setEnabled(enable);
        t1=null;
        t1 = this.jToolBar5.getComponents();
        for(int i=0;i<t1.length;i++)
            t1[i].setEnabled(enable);
        t1=null;
    }
    
    private void refreshTapes(int numOfTapes){
        
        if(numOfTapes==arrayOfTapes.length) return;
        int dif=numOfTapes-arrayOfTapes.length;
        if(dif>0)
            for(int i=0;i<dif;i++) addTape();
        else
            for(int i=0;i<-dif;i++) removeTape();
        
        //Maquina.displayIndex=(arrayOfTapes.length!=1);
        Maquina.displayIndex=((Vector2)this.currentMachineComponents).getNumeroCintas()!=1;
        this.rootTreeTrace.setArrayOfTapes(arrayOfTapes);
        
    }
    
    public void addTape(){
        
        int i;
        Cinta[] newArrayOfTapes = new Cinta[arrayOfTapes.length+1];
        for(i=0;i<arrayOfTapes.length;i++)
            newArrayOfTapes[i] = arrayOfTapes[i];
        
        newArrayOfTapes[i] = new Cinta(38+Cinta.H,Cinta.SEPARACION*i,i+1);
        this.jComboBox2.addItem("Cinta "+(i+1));
        arrayOfTapes = newArrayOfTapes;
        newArrayOfTapes = null;
        
        //for(int i=0;i<numOfTapes;i++)
        //arrayOfTapes[i] = new Cinta(38+Cinta.H,20*i,i+1);
        
    }
    
    public void removeTape(){
        
        int i;
        if(arrayOfTapes.length==0) return;
        Cinta[] newArrayOfTapes = new Cinta[arrayOfTapes.length-1];
        for(i=0;i<newArrayOfTapes.length;i++)
            newArrayOfTapes[i] = arrayOfTapes[i];
        this.jComboBox2.removeItemAt(this.jComboBox2.getItemCount()-1);
        arrayOfTapes[i] = null;
        arrayOfTapes = newArrayOfTapes;
        newArrayOfTapes = null;
        
    }
    
    
    public boolean isMachineModified(){
        
        return this.jButton3.isEnabled();
    }
    
    
    private boolean testInput(String input){
        
        char[] chars = input.toCharArray();
        for(int i=0;i<chars.length;i++){
            if(!(('a'<=chars[i] && chars[i]<='z')||('0'<=chars[i] && chars[i]<='9')||chars[i]=='#')) return false;
        }
        chars = null;
        return true;
        
    }
    
    
    private void openMachine(String pathMachine){
        
        
        int retVal=JOptionPane.NO_OPTION;
        
        if(this.isMachineModified())
            retVal = JOptionPane.showConfirmDialog(this,"Esta máquina ha sido cambiada. ¿Desea guardarla?.","JTV",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);
        
        if(retVal==JOptionPane.CANCEL_OPTION) return;
        
        if(retVal==JOptionPane.YES_OPTION){
            
            retVal=JOptionPane.NO_OPTION;
            
            int returnVal2 = 0; //fc.showSaveDialog(this);
            while(true){
                returnVal2 = fc.showSaveDialog(this);
                if (returnVal2 != JFileChooser.APPROVE_OPTION) return;
                fileMachine = fc.getSelectedFile();
                checkFileMachineExtension();
                if(fileMachine.exists()){
                    int yesnoVal = JOptionPane.showConfirmDialog(this,"Esta máquina ya existe. ¿Desea sobreescribirla?.","JTV",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                    if(yesnoVal==JOptionPane.YES_OPTION) break;
                } else break;
            }
            
            
            fileMachine = fc.getSelectedFile();
            
            
            
            try{
                FileWriter fileWriter = new FileWriter(fileMachine);
                fileWriter.write(getXML());
                fileWriter.close();
                this.jMenuItem4.setEnabled(false);
                this.jButton3.setEnabled(false);
            } catch(Exception ex){
                ex.printStackTrace();
                this.fileMachine = null;
            }
            
        }
        
        
        if(retVal==JOptionPane.NO_OPTION){
            
            
            int returnVal;
            
            if(pathMachine==null)
                returnVal = fc.showOpenDialog(this);
            else
                returnVal = JFileChooser.APPROVE_OPTION;
            
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try{
                    File file;
                    
                    if(pathMachine==null)
                        file = fc.getSelectedFile();
                    else 
                        file = new File(pathMachine);
                    
                    String fileName = file.getName();
                    if(!(fileName.endsWith(".jtv") || fileName.endsWith(".JTV"))){
                        file = new File(file.getPath()+".jtv");
                    }
                    String headerXML ="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n\n";
                    headerXML+="<!DOCTYPE jtv SYSTEM \""+JTV.pathJTV+"JTV.dtd\">\n\n";
                    
                    ByteArrayInputStream bais = new ByteArrayInputStream(headerXML.getBytes());
                    FileInputStream fis = new FileInputStream(file);
                    SequenceInputStream sis = new SequenceInputStream(bais, fis);
                    
                    javax.xml.parsers.DocumentBuilderFactory builderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
                    javax.xml.parsers.DocumentBuilder builder = builderFactory.newDocumentBuilder();
                    org.w3c.dom.Document document = builder.parse(new org.xml.sax.InputSource(sis));
                    JTVScanner scanner = new JTVScanner(document);
                    scanner.visitDocument();
                    //OBTENGO EL DICCIONARIO DE MAQUINAS DEL ARCHIVO ABIERTO
                    Hashtable dicOfMachinesParse = scanner.getDicOfMachines();
                    //OBTENGO LA MAQUINA PRINCIPAL
                    Vector2 principal = scanner.getPrincipal();
                    //SETEO SU DEPENDENCIA DE LA MAQUINA DONDE SE VA A INSERTAR
                    //principal.setDependencia(null);
                    //System.out.println("principal.getDependencia()="+principal.getDependencia());
                    //INSERTO EN EL ARBOL LA MAQUINA PRINCIPAL
                    
                    //Remuevo las maquinas del archivo antiguo
                    Enumeration en = rootTreeTrace2.preorderEnumeration();
                    while(en.hasMoreElements())
                        dicOfMachines.remove((String)((NodeTreeMachine)en.nextElement()).getUserObject());
                    rootTreeTrace2.removeAllChildren();
                    
                    en = null;
                    en = dicOfMachinesParse.elements();
                    while(en.hasMoreElements()){
                        Vector2 vector2 = (Vector2)en.nextElement();
                        dicOfMachines.put(vector2.getNombreLargo(),vector2);
                    }
                    //NodeTreeMachine newChild = new NodeTreeMachine(principal.getNombreLargo());
                    rootTreeTrace2.setUserObject(principal.getNombreLargo());
                    rootTreeTrace.setUserObject(principal.getNombreLargo());
                    this.currentRepository = principal.getNombreLargo();
                    this.currentMachineComponents = getRepository(currentRepository);
                    this.refreshTapes(principal.getNumeroCintas());
                    Maquina.displayIndex=principal.getNumeroCintas()!=1;
                    //dicOfMachinesParse.remove(currentRepository);
                    rootTreeTrace2.vector2 = principal;
                    rootTreeTrace2.maquina = null;
                    //treeModel2.insertNodeInto(,selectedMachine,selectedMachine.getChildCount());
                    //INSERTO EL RESTO DE LAS MAQUINAS RECURSIVAMENTE EN EL ARBOL
                    //Hashtable dicOfMachinesParse2 = (Hashtable)dicOfMachinesParse.clone();
                    
                    en = null;
                    en = dicOfMachinesParse.elements();
                    while(en.hasMoreElements()){
                        Vector2 vector2 = (Vector2)en.nextElement();
                        
                        Enumeration en2 = vector2.elements();
                        while(en2.hasMoreElements()){
                            Maquina maquina = (Maquina)en2.nextElement();
                            if(maquina instanceof Submaquina && !((Submaquina)maquina).isMonocinta()){
                                String nombreLargo = ((Submaquina)maquina).getNombreLargo();
                                //((Submaquina)maquina).machineComponents = (Vector2)dicOfMachines.get(((Submaquina)maquina).getNombreLargo());
                                ((Submaquina)maquina).machineComponents = (Vector2)dicOfMachinesParse.get(nombreLargo);
                                //if(((Submaquina)maquina).machineComponents==null) System.out.println("machineComponents de "+nombreLargo +" es NULL");
                            } else if(maquina instanceof Submaquina && ((Submaquina)maquina).isMonocinta()){
                                String nombreLargo = ((Submaquina)maquina).getNombreLargo();
                                //((Submaquina)maquina).machineComponents = (Vector2)dicOfMachines.get(((Submaquina)maquina).getNombreLargo());
                                ((Submaquina)maquina).machineComponents = (Vector2)dicOfMachines.get(nombreLargo);
                                //if(((Submaquina)maquina).machineComponents==null) System.out.println("machineComponents de "+nombreLargo +" es NULL");
                            }
                            
                        }
                    }
                    
                    rootTreeTrace2.insertMachines(treeModel2,dicOfMachinesParse);
                    
                    //ACTUALIZO COMBOBOX DE SUBMAQUINAS
                    jComboBox4.setEnabled(true);
                    jComboBox4.removeAllItems();
                    en = null;
                    en = rootTreeTrace2.children();
                    while(en.hasMoreElements()){
                        NodeTreeMachine node = (NodeTreeMachine)en.nextElement();
                        jComboBox4.addItem(node.getUserObject());
                    }
                    if(jComboBox4.getItemCount()==0) jComboBox4.setEnabled(false);
                    
                    //INSERTO LAS MAQUINAS EN EL DICCIONARIO
                    
                    en = null;
                    en = rootTreeTrace2.preorderEnumeration();
                    while(en.hasMoreElements()){
                        NodeTreeMachine node = (NodeTreeMachine)en.nextElement();
                        
                        node.refreshUserObject();
                    }
                    
                    //SE LIBERAN RECURSOS
                    treeModel.reload();
                    treeModel2.reload();
                    this.drawingMachinesArea.repaint();
                    this.drawingTapesArea.repaint();
                    dicOfMachinesParse.clear();
                    dicOfMachinesParse = null;
                    this.fileMachine = file;
                    this.setTitle("JTV ["+file.getPath()+"]");
                    this.jMenuItem4.setEnabled(false);
                    this.jButton3.setEnabled(false);
                    
                    if(JTV.listaMaquinasRecientes.add(file.getPath())) fillListaMaquinasRecientesMenu();
                    System.gc();
                } catch(Exception ex){
                    JOptionPane.showMessageDialog(null, "Se produjo un error durante la apertura del archivo","JTV",JOptionPane.ERROR_MESSAGE);
                    ex.printStackTrace();
                }
            }
        }
        
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the FormEditor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPopupMenu1 = new javax.swing.JPopupMenu();
        jMenuItem29 = new javax.swing.JMenuItem();
        jMenuItem30 = new javax.swing.JMenuItem();
        jMenuItem31 = new javax.swing.JMenuItem();
        jMenuItem32 = new javax.swing.JMenuItem();
        jMenuItem33 = new javax.swing.JMenuItem();
        jMenuItem34 = new javax.swing.JMenuItem();
        jMenuItem35 = new javax.swing.JMenuItem();
        jPanel1 = new javax.swing.JPanel();
        jToolBar4 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JSeparator();
        jButton13 = new javax.swing.JButton();
        jButton14 = new javax.swing.JButton();
        jButton15 = new javax.swing.JButton();
        jButton16 = new javax.swing.JButton();
        jButton17 = new javax.swing.JButton();
        jButton19 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jButton20 = new javax.swing.JButton();
        jButton18 = new javax.swing.JButton();
        jButton21 = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        jComboBox1 = new javax.swing.JComboBox();
        jComboBox3 = new javax.swing.JComboBox();
        jComboBox5 = new javax.swing.JComboBox();
        jComboBox4 = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jToolBar2 = new javax.swing.JToolBar();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jButton9 = new javax.swing.JButton();
        jButton26 = new javax.swing.JButton();
        jToolBar3 = new javax.swing.JToolBar();
        jButton11 = new javax.swing.JButton();
        jButton12 = new javax.swing.JButton();
        jButton23 = new javax.swing.JButton();
        jButton24 = new javax.swing.JButton();
        jButton25 = new javax.swing.JButton();
        jButton32 = new javax.swing.JButton();
        jToolBar5 = new javax.swing.JToolBar();
        jButton27 = new javax.swing.JButton();
        jButton28 = new javax.swing.JButton();
        jButton29 = new javax.swing.JButton();
        jButton30 = new javax.swing.JButton();
        jButton31 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        jButton33 = new javax.swing.JButton();
        jButton34 = new javax.swing.JButton();
        jButton35 = new javax.swing.JButton();
        jButton39 = new javax.swing.JButton();
        jComboBox2 = new javax.swing.JComboBox();
        jTextField1 = new javax.swing.JTextField();
        jToolBar6 = new javax.swing.JToolBar();
        jButton36 = new javax.swing.JButton();
        jButton37 = new javax.swing.JButton();
        jButton38 = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jLabel1 = new javax.swing.JLabel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenuItem6 = new javax.swing.JMenuItem();
        jMenu6 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem7 = new javax.swing.JMenuItem();
        jMenuItem17 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem8 = new javax.swing.JMenuItem();
        jMenuItem9 = new javax.swing.JMenuItem();
        jMenuItem14 = new javax.swing.JMenuItem();
        jMenuItem18 = new javax.swing.JMenuItem();
        jMenuItem10 = new javax.swing.JMenuItem();
        jMenuItem11 = new javax.swing.JMenuItem();
        jMenuItem12 = new javax.swing.JMenuItem();
        jMenuItem13 = new javax.swing.JMenuItem();
        jMenu4 = new javax.swing.JMenu();
        jMenuItem15 = new javax.swing.JMenuItem();
        jMenuItem16 = new javax.swing.JMenuItem();
        jMenu5 = new javax.swing.JMenu();
        jMenuItem26 = new javax.swing.JMenuItem();
        jMenuItem27 = new javax.swing.JMenuItem();

        jPopupMenu1.add(jMenuItem29);

        jPopupMenu1.add(jMenuItem30);

        jPopupMenu1.add(jMenuItem31);

        jPopupMenu1.add(jMenuItem32);

        jPopupMenu1.add(jMenuItem33);

        jPopupMenu1.add(jMenuItem34);

        jPopupMenu1.add(jMenuItem35);

        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.X_AXIS));

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                formMousePressed(evt);
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        jPanel1.setLayout(new java.awt.BorderLayout());

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/New24.gif")));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jToolBar4.add(jButton1);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Open24.gif")));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jToolBar4.add(jButton2);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Save24.gif")));
        jButton3.setEnabled(false);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jButton3.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jButton3PropertyChange(evt);
            }
        });

        jToolBar4.add(jButton3);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Print24.gif")));
        jButton4.setToolTipText("Imprimir");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jToolBar4.add(jButton4);

        jSeparator3.setMaximumSize(new java.awt.Dimension(100, 100));
        jSeparator3.setPreferredSize(new java.awt.Dimension(10, 10));
        jToolBar4.add(jSeparator3);

        jButton13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Undo24.gif")));
        jButton13.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton13ActionPerformed(evt);
            }
        });

        jToolBar4.add(jButton13);

        jButton14.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Redo24.gif")));
        jButton14.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton14ActionPerformed(evt);
            }
        });

        jToolBar4.add(jButton14);

        jButton15.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Cut24.gif")));
        jButton15.setAutoscrolls(true);
        jButton15.setEnabled(false);
        jButton15.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton15ActionPerformed(evt);
            }
        });

        jToolBar4.add(jButton15);

        jButton16.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Copy24.gif")));
        jButton16.setEnabled(false);
        jButton16.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton16ActionPerformed(evt);
            }
        });

        jToolBar4.add(jButton16);

        jButton17.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Paste24.gif")));
        jButton17.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton17ActionPerformed(evt);
            }
        });

        jToolBar4.add(jButton17);

        jButton19.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Delete24.gif")));
        jButton19.setToolTipText("Eliminar");
        jButton19.setEnabled(false);
        jButton19.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton19ActionPerformed(evt);
            }
        });

        jToolBar4.add(jButton19);

        jSeparator1.setMaximumSize(new java.awt.Dimension(100, 100));
        jSeparator1.setPreferredSize(new java.awt.Dimension(10, 10));
        jToolBar4.add(jSeparator1);

        jButton20.setFont(new java.awt.Font("Times New Roman", 2, 19));
        jButton20.setText("A=");
        jButton20.setToolTipText("Asignaci\u00f3n de Par\u00e1metros");
        jButton20.setMaximumSize(new java.awt.Dimension(36, 36));
        jButton20.setMinimumSize(new java.awt.Dimension(36, 36));
        jButton20.setPreferredSize(new java.awt.Dimension(36, 36));
        jButton20.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton20ActionPerformed(evt);
            }
        });

        jToolBar4.add(jButton20);

        jButton18.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Play24.gif")));
        jButton18.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton18ActionPerformed(evt);
            }
        });

        jToolBar4.add(jButton18);

        jButton21.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Stop24.gif")));
        jButton21.setEnabled(false);
        jButton21.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton21ActionPerformed(evt);
            }
        });

        jToolBar4.add(jButton21);

        jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
        jToolBar4.add(jSeparator2);

        jComboBox1.setToolTipText("Elecci\u00f3n de S\u00edmbolos ");
        jComboBox1.setMaximumSize(new java.awt.Dimension(40, 36));
        jComboBox1.setMinimumSize(new java.awt.Dimension(40, 36));
        jComboBox1.setPreferredSize(new java.awt.Dimension(40, 36));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jToolBar4.add(jComboBox1);

        jComboBox3.setToolTipText("Elecci\u00f3n de Variables");
        jComboBox3.setMaximumSize(new java.awt.Dimension(40, 36));
        jComboBox3.setMinimumSize(new java.awt.Dimension(40, 36));
        jComboBox3.setPreferredSize(new java.awt.Dimension(40, 36));
        jToolBar4.add(jComboBox3);

        jComboBox5.setToolTipText("Elecci\u00f3n de Par\u00e1metros");
        jComboBox5.setMaximumSize(new java.awt.Dimension(40, 36));
        jComboBox5.setMinimumSize(new java.awt.Dimension(40, 36));
        jComboBox5.setPreferredSize(new java.awt.Dimension(40, 36));
        jToolBar4.add(jComboBox5);

        jComboBox4.setToolTipText("Elecci\u00f3n de Subm\u00e1quinas");
        jToolBar4.add(jComboBox4);

        jPanel1.add(jToolBar4, java.awt.BorderLayout.NORTH);

        jPanel2.setLayout(new java.awt.GridLayout(1, 3));

        jToolBar2.setFloatable(false);
        jToolBar2.setOrientation(1);
        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/a.gif")));
        jButton5.setToolTipText("M\u00e1quina Escritora de S\u00edmbolos");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jToolBar2.add(jButton5);

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/L.gif")));
        jButton6.setToolTipText("M\u00e1quina L");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jToolBar2.add(jButton6);

        jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Lsigma.gif")));
        jButton7.setToolTipText("M\u00e1quina Buscadora Izquierda");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jToolBar2.add(jButton7);

        jButton8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/L!sigma.gif")));
        jButton8.setToolTipText("M\u00e1quina Buscadora Izquierda Inversa");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        jToolBar2.add(jButton8);

        jButton9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/SL.gif")));
        jButton9.setToolTipText("M\u00e1quina Left-Shifting");
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });

        jToolBar2.add(jButton9);

        jButton26.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/M.gif")));
        jButton26.setToolTipText("Subm\u00e1quina");
        jButton26.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton26ActionPerformed(evt);
            }
        });

        jToolBar2.add(jButton26);

        jPanel2.add(jToolBar2);

        jToolBar3.setFloatable(false);
        jToolBar3.setOrientation(1);
        jButton11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/sigma.gif")));
        jButton11.setToolTipText("M\u00e1quina Escritora de Variables");
        jButton11.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton11ActionPerformed(evt);
            }
        });

        jToolBar3.add(jButton11);

        jButton12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/R.gif")));
        jButton12.setToolTipText("M\u00e1quina R");
        jButton12.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton12ActionPerformed(evt);
            }
        });

        jToolBar3.add(jButton12);

        jButton23.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Rsigma.gif")));
        jButton23.setToolTipText("M\u00e1quina Buscadora Derecha");
        jButton23.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton23ActionPerformed(evt);
            }
        });

        jToolBar3.add(jButton23);

        jButton24.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/R!sigma.gif")));
        jButton24.setToolTipText("M\u00e1quina Buscadora Derecha Inversa");
        jButton24.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton24ActionPerformed(evt);
            }
        });

        jToolBar3.add(jButton24);

        jButton25.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/SR.gif")));
        jButton25.setToolTipText("M\u00e1quina Right-Shifting");
        jButton25.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton25ActionPerformed(evt);
            }
        });

        jToolBar3.add(jButton25);

        jButton32.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/puntero.gif")));
        jButton32.setToolTipText("Puntero");
        jButton32.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton32ActionPerformed(evt);
            }
        });

        jToolBar3.add(jButton32);

        jPanel2.add(jToolBar3);

        jToolBar5.setFloatable(false);
        jToolBar5.setOrientation(1);
        jButton27.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/A_.gif")));
        jButton27.setToolTipText("M\u00e1quina Escritora de Par\u00e1metros");
        jButton27.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton27ActionPerformed(evt);
            }
        });

        jToolBar5.add(jButton27);

        jButton28.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ball.gif")));
        jButton28.setToolTipText("Concentrador");
        jButton28.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton28ActionPerformed(evt);
            }
        });

        jToolBar5.add(jButton28);

        jButton29.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/flechaVuelta.gif")));
        jButton29.setToolTipText("Auto Transici\u00f3n");
        jButton29.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton29ActionPerformed(evt);
            }
        });

        jToolBar5.add(jButton29);

        jButton30.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/flecha.gif")));
        jButton30.setToolTipText("Transici\u00f3n Incondicional");
        jButton30.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton30ActionPerformed(evt);
            }
        });

        jToolBar5.add(jButton30);

        jButton31.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/flechasigma.gif")));
        jButton31.setToolTipText("Transici\u00f3n Condicional");
        jButton31.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton31ActionPerformed(evt);
            }
        });

        jToolBar5.add(jButton31);

        jPanel2.add(jToolBar5);

        jPanel1.add(jPanel2, java.awt.BorderLayout.EAST);

        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.X_AXIS));

        jButton33.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/agregaCinta.gif")));
        jButton33.setToolTipText("Agregar Cinta");
        jButton33.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton33ActionPerformed(evt);
            }
        });

        jToolBar1.add(jButton33);

        jButton34.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/eliminaCinta.gif")));
        jButton34.setToolTipText("Eliminar Cinta");
        jButton34.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton34ActionPerformed(evt);
            }
        });

        jToolBar1.add(jButton34);

        jButton35.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/borraTodasCintas.gif")));
        jButton35.setToolTipText("Limpiar todas las Cintas");
        jButton35.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton35ActionPerformed(evt);
            }
        });

        jToolBar1.add(jButton35);

        jButton39.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/borraCinta.gif")));
        jButton39.setToolTipText("Limpiar Cinta");
        jButton39.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton39ActionPerformed(evt);
            }
        });

        jToolBar1.add(jButton39);

        jComboBox2.setToolTipText("Elecci\u00f3n de Cinta");
        jToolBar1.add(jComboBox2);

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                keyPressedHandler(evt);
            }
        });

        jToolBar1.add(jTextField1);

        jButton36.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/izquierdaFinal.gif")));
        jButton36.setToolTipText("Retroceder una p\u00e1gina");
        jButton36.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton36ActionPerformed(evt);
            }
        });

        jToolBar6.add(jButton36);

        jButton37.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/centrar.gif")));
        jButton37.setToolTipText("Mostrar el cabezal");
        jButton37.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton37ActionPerformed(evt);
            }
        });

        jToolBar6.add(jButton37);

        jButton38.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/derechaFinal.gif")));
        jButton38.setToolTipText("Avanzar una p\u00e1gina");
        jButton38.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton38ActionPerformed(evt);
            }
        });

        jToolBar6.add(jButton38);

        jToolBar1.add(jToolBar6);

        jPanel4.add(jToolBar1);

        jPanel3.add(jPanel4, java.awt.BorderLayout.NORTH);

        jPanel5.setLayout(new javax.swing.BoxLayout(jPanel5, javax.swing.BoxLayout.X_AXIS));

        jPanel5.setMinimumSize(new java.awt.Dimension(100, 100));
        jPanel5.setPreferredSize(new java.awt.Dimension(100, 100));
        jPanel5.add(jScrollPane2);

        jPanel3.add(jPanel5, java.awt.BorderLayout.CENTER);

        jPanel3.add(jLabel1, java.awt.BorderLayout.SOUTH);

        jPanel1.add(jPanel3, java.awt.BorderLayout.SOUTH);

        jSplitPane1.setLeftComponent(jTabbedPane1);

        jScrollPane1.setMaximumSize(new java.awt.Dimension(40000, 40000));
        jSplitPane1.setRightComponent(jScrollPane1);

        jPanel1.add(jSplitPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1);

        jMenu1.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Archivo"));
        jMenuItem1.setText("Nueva");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });

        jMenu1.add(jMenuItem1);

        jMenuItem3.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Abrir..."));
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });

        jMenu1.add(jMenuItem3);

        jMenuItem4.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Guardar"));
        jMenuItem4.setEnabled(false);
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });

        jMenu1.add(jMenuItem4);

        jMenuItem5.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Guardar_Como..."));
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem5ActionPerformed(evt);
            }
        });

        jMenu1.add(jMenuItem5);

        jMenuItem6.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Imprimir"));
        jMenuItem6.setActionCommand(java.util.ResourceBundle.getBundle("language/esp").getString("Imprimir"));
        jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem6ActionPerformed(evt);
            }
        });

        jMenu1.add(jMenuItem6);

        jMenu6.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Maquinas_Recientes"));
        jMenu1.add(jMenu6);

        jMenu3.setText("Exportar a...");
        jMenu3.setEnabled(false);
        jMenuItem7.setText("Latex");
        jMenuItem7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem7ActionPerformed(evt);
            }
        });

        jMenu3.add(jMenuItem7);

        jMenuItem17.setText("Repositorio SOC");
        jMenuItem17.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem17ActionPerformed(evt);
            }
        });

        jMenu3.add(jMenuItem17);

        jMenu1.add(jMenu3);

        jMenuItem2.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Salir"));
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenuItem2.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jMenuItem2StateChanged(evt);
            }
        });
        jMenuItem2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenuItem2MouseClicked(evt);
            }
        });

        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        jMenu2.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Edición"));
        jMenu2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu2ActionPerformed(evt);
            }
        });

        jMenuItem8.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Deshacer"));
        jMenuItem8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem8ActionPerformed(evt);
            }
        });

        jMenu2.add(jMenuItem8);

        jMenuItem9.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Rehacer"));
        jMenuItem9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem9ActionPerformed(evt);
            }
        });

        jMenu2.add(jMenuItem9);

        jMenuItem14.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Hacer_Inicial"));
        jMenuItem14.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem14ActionPerformed(evt);
            }
        });

        jMenu2.add(jMenuItem14);

        jMenuItem18.setText("Cambiar Cinta");
        jMenuItem18.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem18ActionPerformed(evt);
            }
        });

        jMenu2.add(jMenuItem18);

        jMenuItem10.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Cortar"));
        jMenuItem10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem10ActionPerformed(evt);
            }
        });

        jMenu2.add(jMenuItem10);

        jMenuItem11.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Copiar"));
        jMenuItem11.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem11ActionPerformed(evt);
            }
        });

        jMenu2.add(jMenuItem11);

        jMenuItem12.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Pegar"));
        jMenuItem12.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem12ActionPerformed(evt);
            }
        });

        jMenu2.add(jMenuItem12);

        jMenuItem13.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Eliminar"));
        jMenuItem13.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem13ActionPerformed(evt);
            }
        });

        jMenu2.add(jMenuItem13);

        jMenuBar1.add(jMenu2);

        jMenu4.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Configuración"));
        jMenuItem15.setText("Tama\u00f1o de R\u00e1faga");
        jMenuItem15.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem15ActionPerformed(evt);
            }
        });

        jMenu4.add(jMenuItem15);

        jMenuItem16.setText("Cambio de Notaci\u00f3n");
        jMenuItem16.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem16ActionPerformed(evt);
            }
        });

        jMenu4.add(jMenuItem16);

        jMenuBar1.add(jMenu4);

        jMenu5.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Ayuda"));
        jMenuItem26.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Contenidos"));
        jMenuItem26.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem26ActionPerformed(evt);
            }
        });

        jMenu5.add(jMenuItem26);

        jMenuItem27.setText(java.util.ResourceBundle.getBundle("language/esp").getString("Acerca_de_JTV..."));
        jMenuItem27.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem27ActionPerformed(evt);
            }
        });

        jMenu5.add(jMenuItem27);

        jMenuBar1.add(jMenu5);

        setJMenuBar(jMenuBar1);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-441)/2, (screenSize.height-334)/2, 441, 334);
    }
    // </editor-fold>//GEN-END:initComponents
    
    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed
// TODO add your handling code here:
    }//GEN-LAST:event_jMenu2ActionPerformed
    
    private void jMenuItem17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem17ActionPerformed
        // Add your handling code here:
        JTV.flagLatex = false;
        while(true){
            int returnVal = fc3.showSaveDialog(this);
            if (returnVal != JFileChooser.APPROVE_OPTION) return;
            fileSOC = fc3.getSelectedFile();
            checkFileMachineExtension3();
            if(fileSOC.exists()){
                //int yesnoVal = JOptionPane.showMessageDialog(null, "Esta máquina ya existe. ¿Desea sobreescribirla?","JTV",JOptionPane.YES_NO_OPTION);
                int yesnoVal = JOptionPane.showConfirmDialog(this,"Esta archivo ya existe. ¿Desea sobreescribirlo?.","JTV",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                if(yesnoVal==JOptionPane.YES_OPTION) break;
            } else break;
        }
        
        try{
            FileWriter fileWriter = new FileWriter(fileSOC);
            fileWriter.write(getLatex());
            fileWriter.close();
        } catch(NonSetException ex){
            JOptionPane.showMessageDialog(null, "Exportación Abortada por parámetros de submáquinas sin valor","JTV",JOptionPane.ERROR_MESSAGE);
            return;
        } catch(IOException ex){
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jMenuItem17ActionPerformed
    
    private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed
        // Add your handling code here:
        JTV.flagLatex = true;
        while(true){
            int returnVal = fc2.showSaveDialog(this);
            if (returnVal != JFileChooser.APPROVE_OPTION) return;
            fileLatex = fc2.getSelectedFile();
            checkFileMachineExtension2();
            if(fileLatex.exists()){
                //int yesnoVal = JOptionPane.showMessageDialog(null, "Esta máquina ya existe. ¿Desea sobreescribirla?","JTV",JOptionPane.YES_NO_OPTION);
                int yesnoVal = JOptionPane.showConfirmDialog(this,"Esta archivo ya existe. ¿Desea sobreescribirlo?.","JTV",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                if(yesnoVal==JOptionPane.YES_OPTION) break;
            } else break;
        }
        
        try{
            FileWriter fileWriter = new FileWriter(fileLatex);
            fileWriter.write(getLatex());
            fileWriter.close();
        } catch(NonSetException ex){
            JOptionPane.showMessageDialog(null, "Exportación Abortada por parámetros de submáquinas sin valor","JTV",JOptionPane.ERROR_MESSAGE);
            return;
        } catch(IOException ex){
            ex.printStackTrace();
        }
        
    }//GEN-LAST:event_jMenuItem7ActionPerformed
    
    public String getLatex() throws NonSetException{
        
        Vector2 principal = transform2Atomics();//this.rootTreeTrace2.vector2;
        
        int maxCintas = principal.getNumeroCintas();
        String nombreMaquina = principal.getNombreLargo();
        String latexMaquina = principal.getLatex();
        int indexStartState = principal.inicial.getIndexState();
        String stringEstados = "";
        if(JTV.flagLatex){
            Enumeration enEstados = StateParser.getStates(latexMaquina).elements();
            int lineCounter = 1;
            while(enEstados.hasMoreElements()){
                stringEstados+="q_{"+enEstados.nextElement()+"},"+(lineCounter%14==0?"\\\\\n":"");
                lineCounter++;
            }
        }
        String latex = "";
        if(JTV.flagLatex){
            latex+="\\documentclass[12pt]{report}\n";
            latex+="\\usepackage[spanish]{babel}\n";
            latex+="\\begin{document}\n";
            latex+="La MT \\textit{"+nombreMaquina+"} de "+maxCintas+" cinta"+(maxCintas>1?"s":"")+", queda definida formalmente\n";
            latex+="como sigue:\n";
            latex+="\\begin{itemize}\n";
            //latex+="\\item $K = \\{q_{0},q_{1},q_{2}\\ldots\\}$\n";
            latex+="\\item $K = \\{"+stringEstados+"\\}$\n";
            latex+="\\item $\\Sigma = \\{a,\\ldots,z\\}\\cup\\{0,\\ldots,9\\}\\cup\\{*\\}\\cup\\{\\#\\}$\n";
            latex+="\\item $s = q_{"+indexStartState+"}$\n";
            latex+="\\item $\\delta$ definida por:\n";
            latex+="\\end{itemize}\n";
            latex+="\\begin{eqnarray*}\n";
            latex+=latexMaquina;
            latex+="\\end{eqnarray*}\n";
            latex+="\\end{document}\n";
        } else{
            latex+=""+maxCintas+"\n";
            latex+="@"+indexStartState+"\n";
            latex+=latexMaquina;
        }
        
        return latex;
        
    }
    
    public void changeTarget(Maquina oldTarget,Maquina newTarget,Vector2 vector2){
        
        Enumeration en = vector2.elements();
        while(en.hasMoreElements()){
            Maquina enlace = (Maquina)en.nextElement();
            if(enlace instanceof Enlace && enlace.proxima==oldTarget)
                enlace.proxima = newTarget;
        }
    }
    
    public Vector2 transform2Atomics() throws NonSetException{
        
        Vector2 principal=null;
        try{
            /////////////////OBTENGO UNA COPIA DE TODO EN XML
            String xml = this.getAllXML();
            String headerXML ="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n\n";
            headerXML+="<!DOCTYPE jtv SYSTEM \""+JTV.pathJTV+"JTV.dtd\">\n\n";
            xml = headerXML+xml;
            
            javax.xml.parsers.DocumentBuilderFactory builderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
            javax.xml.parsers.DocumentBuilder builder = builderFactory.newDocumentBuilder();
            org.w3c.dom.Document document = builder.parse(new org.xml.sax.InputSource(new StringReader(xml)));
            JTVScanner scanner = new JTVScanner(document);
            scanner.visitDocument();
            //OBTENGO EL DICCIONARIO DE MAQUINAS DEL ARCHIVO ABIERTO
            Hashtable dicOfMachinesParse = scanner.getDicOfMachines();
            //OBTENGO LA MAQUINA PRINCIPAL
            principal = scanner.getPrincipal();
            /////////////////
            while(true){
                //if(!submachineFound) break;
                //System.out.println("Ciclo 1");
                boolean submachineFound = false;
                Enumeration en = ((Vector)principal.clone()).elements();
                //Enumeration en = ((Vector)principal).elements();
                while(en.hasMoreElements()){
                    Object obj = en.nextElement();
                    //System.out.println(obj.getClass().getName());
                    if((obj instanceof Submaquina)||(obj instanceof Concentrador))
                        submachineFound = true;
                }
                if(!submachineFound) break;
                en = null;
                en = ((Vector)principal.clone()).elements();
                //en = ((Vector)principal).elements();
                while(en.hasMoreElements()){
                    //System.out.println("    Ciclo 2");
                    Maquina maquina = (Maquina)en.nextElement();
                    if(maquina instanceof Submaquina){
                        //String xml2 = ((Vector2)((Submaquina)maquina).machineComponents).getXML();
                        Vector2 repositorioSubmaquina = (Vector2)dicOfMachinesParse.get(((Submaquina)maquina).getNombreLargo());
                        repositorioSubmaquina.setPrincipal(true);
                        String xml2 = repositorioSubmaquina.getXML();
                        repositorioSubmaquina.setPrincipal(false);
                        String headerXML2 ="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n\n";
                        headerXML2+="<!DOCTYPE jtv SYSTEM \""+JTV.pathJTV+"JTV.dtd\">\n\n";
                        headerXML2+="<jtv>\n";
                        xml2 = headerXML2+xml2;
                        xml2+="</jtv>\n";
                        //System.out.println(xml2);
                        javax.xml.parsers.DocumentBuilderFactory builderFactory2 = javax.xml.parsers.DocumentBuilderFactory.newInstance();
                        javax.xml.parsers.DocumentBuilder builder2 = builderFactory2.newDocumentBuilder();
                        org.w3c.dom.Document document2 = builder2.parse(new org.xml.sax.InputSource(new StringReader(xml2)));
                        JTVScanner scanner2 = new JTVScanner(document2);
                        scanner2.visitDocument();
                        //OBTENGO EL DICCIONARIO DE MAQUINAS DEL ARCHIVO ABIERTO
                        Hashtable dicOfMachinesParse2 = scanner2.getDicOfMachines();
                        //OBTENGO LA MAQUINA PRINCIPAL
                        Enumeration en2 = dicOfMachinesParse2.elements();
                        //System.out.println("dicOfMachinesParse2.size()="+dicOfMachinesParse2.size());
                        //Vector2 principal2=null;
                        //while(en2.hasMoreElements()){
                        //    principal2 = (Vector2)en2.nextElement();
                        //System.out.println("dependencia:"+principal2.getDependencia()+"-nombre largo:"+((Submaquina)maquina).getNombreLargo());
                        //if(principal2.getDependencia().equals(((Submaquina)maquina).getNombreLargo())) break;
                        //}
                        Vector2 principal2 = scanner2.getPrincipal();
                        if(principal2.getNumeroCintas()>principal.getNumeroCintas())
                            principal.setNumeroCintas(principal2.getNumeroCintas());
                        en2 = null;
                        en2 = principal2.elements();
                        R maquinaR = new R(0,0,0,null,null);
                        L maquinaL = new L(0,0,0,null,null);
                        //maquinaR.previa = maquina.previa;
                        maquinaR.proxima = maquinaL;
                        maquinaL.previa = maquinaR;
                        maquinaL.proxima = maquina.proxima;
                        if(maquina.proxima!=null) maquina.proxima.previa = maquinaL;
                        if(maquina.proxima instanceof EnlaceCompuesto){
                            Enumeration en3 = ((EnlaceCompuesto)maquina.proxima).getEnlaces();
                            while(en3.hasMoreElements()){
                                Enlace enlace = (Enlace)en3.nextElement();
                                enlace.previa = maquinaL;
                            }
                        }
                        principal.add(maquinaR);
                        //System.out.println("    Agregando R");
                        principal.add(maquinaL);
                        
                        //System.out.println("    Agregando L");
                        while(en2.hasMoreElements()){
                            Maquina maquina2 = (Maquina)en2.nextElement();
                            //System.out.println("    Agregando "+maquina2.getClass().getName());
                            if(maquina2.proxima==null){
                                EnlaceCompuesto enlaceCompuesto1 = new EnlaceCompuesto(maquina2);
                                maquina2.setProxMaquina(enlaceCompuesto1);
                                Enlace enlace1 = new Enlace(0,0,0,maquina2,maquinaR);
                                enlaceCompuesto1.insertar(enlace1);
                                principal.add(enlace1);
                                //maquina2.proxima = maquinaR;
                            }
                            if(maquina2.isInicial()){
                                changeTarget(maquina,maquina2,principal);
                                if(maquina.previa!=null) maquina.previa.proxima = maquina2;
                                maquina2.previa = maquina.previa;
                                if(!maquina.isInicial())
                                    maquina2.setInicial(false);
                                else
                                    principal.inicial = maquina2;
                            }
                            if(maquina2.proxima instanceof EnlaceCompuesto){
                                ((EnlaceCompuesto)maquina2.proxima).setNextState(maquinaR.getIndexState());
                            }
                            try{
                                if(maquina2 instanceof Escritora){
                                    ((Escritora)maquina2).reemplazaParametro(((Submaquina)maquina).parametros);
                                }
                                if(maquina2 instanceof Enlace){
                                    ((Enlace)maquina2).reemplazaParametro(((Submaquina)maquina).parametros);
                                }
                            } catch(NonSetException ex){
                                JOptionPane.showMessageDialog(null, "Exportación Abortada por parámetros de submáquinas sin valor","JTV",JOptionPane.ERROR_MESSAGE);
                                return null;
                            }
                            
                            principal.add(maquina2);
                        }
                        if(!principal.remove(maquina))
                            System.out.println("        NO REMOVI");
                    } else if(maquina instanceof Concentrador){
                        
                        R maquinaR = new R(0,0,0,null,null);
                        L maquinaL = new L(0,0,0,null,null);
                        //maquinaR.previa = maquina.previa;
                        maquinaR.proxima = maquinaL;
                        maquinaL.previa = maquinaR;
                        maquinaL.proxima = maquina.proxima;
                        //if(maquina.proxima!=null) maquina.proxima.previa = maquinaL;
                        principal.add(maquinaR);
                        principal.add(maquinaL);
                        changeTarget(maquina,maquinaR,principal);
                        
                        if(maquina.proxima instanceof EnlaceCompuesto){
                            Enumeration en3 = ((EnlaceCompuesto)maquina.proxima).getEnlaces();
                            while(en3.hasMoreElements()){
                                Enlace enlace = (Enlace)en3.nextElement();
                                enlace.previa = maquinaL;
                            }
                        }
                        if(!principal.remove(maquina))
                            System.out.println("        NO REMOVI");
                        
                    }
                }
            }
        } catch(Exception ex){
            ex.printStackTrace();
            //System.out.println("Excepción");
        }
        
        return principal;
        
    }
    private void jButton3PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jButton3PropertyChange
        // Add your handling code here:
        if(evt.getPropertyName().equals("enabled")){
            if(jButton3.isEnabled())
                setTitle(getTitle() + "*");
            else
                setTitle(getTitle().substring(0,getTitle().length()-1));
        }
    }//GEN-LAST:event_jButton3PropertyChange
    
    private void jMenuItem14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem14ActionPerformed
        // Add your handling code here:
        hacerInicial();
    }//GEN-LAST:event_jMenuItem14ActionPerformed
    
    private void jMenuItem18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem18ActionPerformed
        // Add your handling code here:
        cambiarCinta();
    }//GEN-LAST:event_jMenuItem18ActionPerformed
    
    private void jMenuItem13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem13ActionPerformed
        // Add your handling code here:
        jButton19ActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem13ActionPerformed
    
    private void jMenuItem12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem12ActionPerformed
        // Add your handling code here:
        jButton17ActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem12ActionPerformed
    
    private void jMenuItem11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem11ActionPerformed
        // Add your handling code here:
        jButton16ActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem11ActionPerformed
    
    private void jMenuItem10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem10ActionPerformed
        // Add your handling code here:
        jButton15ActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem10ActionPerformed
    
    private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem9ActionPerformed
        // Add your handling code here:
        jButton14ActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem9ActionPerformed
    
    private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem8ActionPerformed
        // Add your handling code here:
        jButton13ActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem8ActionPerformed
    
    private void jMenuItem26ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem26ActionPerformed
        // Add your handling code here:
        com.xlreader.shared.io.S_ToBrowserDefault.s_displayURL("http://www.dcc.uchile.cl/jtv");
        //com.xlreader.shared.io.S_ToBrowserDefault.s_displayURL(java.net.URLEncoder.encode(JTV.pathJTV+"docs/index.html"));
        //com.xlreader.shared.io.S_ToBrowserDefault.s_displayURL(getClass().getResource("/docs/index.html").toExternalForm());
        
    }//GEN-LAST:event_jMenuItem26ActionPerformed
    
    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        // Add your handling code here:
        boolean dialog = false;
        if(this.fileMachine==null){
            //final JFileChooser fc = new JFileChooser();
            /*int returnVal = fc.showSaveDialog(this);
            if (returnVal != JFileChooser.APPROVE_OPTION) return;
            fileMachine = fc.getSelectedFile();*/
            dialog=true;
            while(true){
                int returnVal = fc.showSaveDialog(this);
                if (returnVal != JFileChooser.APPROVE_OPTION) return;
                fileMachine = fc.getSelectedFile();
                checkFileMachineExtension();
                if(fileMachine.exists()){
                    //int yesnoVal = JOptionPane.showMessageDialog(null, "Esta máquina ya existe. ¿Desea sobreescribirla?","JTV",JOptionPane.YES_NO_OPTION);
                    int yesnoVal = JOptionPane.showConfirmDialog(this,"Esta máquina ya existe. ¿Desea sobreescribirla?.","JTV",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                    if(yesnoVal==JOptionPane.YES_OPTION) break;
                } else break;
            }
        }
        
        
        
        try{
            this.saveMachine(fileMachine,dialog);
            
            this.jButton3.setEnabled(false);
            this.jMenuItem4.setEnabled(false);
        } catch(Exception ex){
            JOptionPane.showMessageDialog(null, "Se produjo un error durante el almacenamiento de la máquina.","JTV",JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
            this.fileMachine = null;
        }
        
    }//GEN-LAST:event_jMenuItem4ActionPerformed
    
    private void jButton17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton17ActionPerformed
        // Add your handling code here:
        if(Maquina.running) return;
        
        Clipboard.paste(currentMachineComponents,this.dicOfMachines,pressedX,pressedY);
        
        drawingMachinesArea.repaint();
    }//GEN-LAST:event_jButton17ActionPerformed
    
    private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton16ActionPerformed
        // Add your handling code here:
        if(Maquina.running) return;
        
        if(Maquina.selectedMachine!=null){
            Clipboard.clipboardMachine = Maquina.selectedMachine;
            Clipboard.setState(Clipboard.STATE_COPY);
            Clipboard.sendMessage(false);
        } else{
            Clipboard.copy(currentMachineComponents);
        }
    }//GEN-LAST:event_jButton16ActionPerformed
    
    private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton15ActionPerformed
        // Add your handling code here:
        if(Maquina.running) return;
        
        //Clipboard.cut(currentMachineComponents);
        
        //drawingMachinesArea.repaint();
        
        if(Maquina.selectedMachine!=null){
            ComandoEM comandoEM = new ComandoEM(Maquina.selectedMachine,(Vector2)currentMachineComponents);
            Comando.addComando2UR(comandoEM);
            if(!(Maquina.selectedMachine instanceof Enlace)){
                if(Maquina.selectedMachine.previa!=null){
                    ComandoIMG comandoIMG = new ComandoIMG(Maquina.selectedMachine.previa,(Vector2)currentMachineComponents,Maquina.selectedMachine,false);
                    comandoEM.setInverse(comandoIMG);
                } else if(Maquina.selectedMachine.proxima!=null && !(Maquina.selectedMachine.proxima instanceof EnlaceCompuesto)){
                    ComandoIMG comandoIMG = new ComandoIMG(Maquina.selectedMachine.proxima,(Vector2)currentMachineComponents,Maquina.selectedMachine,true);
                    comandoEM.setInverse(comandoIMG);
                } else{
                    ComandoIML comandoIML = new ComandoIML(Maquina.selectedMachine,(Vector2)currentMachineComponents);
                    comandoEM.setInverse(comandoIML);
                }
                Comando.flagDelete=true;
                Maquina.selectedMachine.deleteMachine(this.currentMachineComponents);
                Comando.flagDelete=false;
            } else{
                ComandoIE comandoIE = new ComandoIE(Maquina.selectedMachine,(Vector2)currentMachineComponents);
                comandoEM.setInverse(comandoIE);
                Maquina.selectedMachine.deleteMachine(this.currentMachineComponents);
                
            }
            Clipboard.clipboardMachine = Maquina.selectedMachine;
            Clipboard.setState(Clipboard.STATE_CUT);
            Clipboard.sendMessage(false);
        } else{
            //Clipboard.delete(currentMachineComponents);
            Clipboard.cut(currentMachineComponents);
        }
        Maquina.selectedMachine=null;
        this.drawingMachinesArea.repaint();
    }//GEN-LAST:event_jButton15ActionPerformed
    
    private void jButton34ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton34ActionPerformed
        // Add your handling code here:
        if(Maquina.running) return;
        
        if(arrayOfTapes.length==1) return;
        
        Enumeration en = this.currentMachineComponents.elements();
        int maxIndice=0;
        while(en.hasMoreElements()){
            Maquina maquina = (Maquina)en.nextElement();
            int indice = maquina.getMaxIndiceCinta();
            if(indice>maxIndice) maxIndice = indice;
        }
        
        if(arrayOfTapes.length-1==maxIndice){
            JOptionPane.showMessageDialog(null, "No puede eliminar la Cinta "+arrayOfTapes.length+ " pues existen referencias a ella en el diseño","JTV",JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        
        this.removeTape();
        this.rootTreeTrace.setArrayOfTapes(arrayOfTapes);
        ((Vector2)this.currentMachineComponents).decrNumeroCintas();
        
        
        Maquina.displayIndex=((Vector2)this.currentMachineComponents).getNumeroCintas()!=1;
        
        ComandoEC comandoEC = new ComandoEC(this,(Vector2)this.currentMachineComponents);
        comandoEC.setInverse(new ComandoAC(this,(Vector2)this.currentMachineComponents));
        Comando.addComando2UR(comandoEC);
        this.drawingMachinesArea.repaint();
        this.drawingTapesArea.repaint();
        
    }//GEN-LAST:event_jButton34ActionPerformed
    
    private void jButton33ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton33ActionPerformed
        // Add your handling code here:
        if(Maquina.running) return;
        
        if(arrayOfTapes.length==JTV.MAXIMO_NUMERO_CINTAS){
            JOptionPane.showMessageDialog(null, "No puede agregar más Cintas, el máximo permitido es "+JTV.MAXIMO_NUMERO_CINTAS,"JTV",JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        this.addTape();
        this.rootTreeTrace.setArrayOfTapes(arrayOfTapes);
        
        ((Vector2)this.currentMachineComponents).incrNumeroCintas();
        
        
        Maquina.displayIndex=((Vector2)this.currentMachineComponents).getNumeroCintas()!=1;
        
        ComandoAC comandoAC = new ComandoAC(this,(Vector2)this.currentMachineComponents);
        comandoAC.setInverse(new ComandoEC(this,(Vector2)this.currentMachineComponents));
        Comando.addComando2UR(comandoAC);
        this.drawingMachinesArea.repaint();
        this.drawingTapesArea.repaint();
    }//GEN-LAST:event_jButton33ActionPerformed
    
    private void jButton37ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton37ActionPerformed
        // Add your handling code here:
        try{
            this.arrayOfTapes[this.jComboBox2.getSelectedIndex()].findCabezal();
            this.arrayOfTapes[this.jComboBox2.getSelectedIndex()].dibujar(this.drawingTapesArea.getGraphics());
        } catch(Exception ex){
            System.out.println("Excepción");
        }
    }//GEN-LAST:event_jButton37ActionPerformed
    
    private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
        // Add your handling code here:
        //this.drawingMachinesArea.print(null);
        this.drawingMachinesArea.currentMachineComponents = currentMachineComponents;
        
       /* 
        PrinterJob printJob = PrinterJob.getPrinterJob();
        PageFormat pf = new PageFormat();
        Paper paper = new Paper();
        //Book book = new Book();
        paper.setImageableArea(0,0,1000,1000);
        paper.setSize(8.5/72, 11/72);
        pf.setPaper(paper);
        pf.setOrientation(pf.LANDSCAPE);
        //book.append(this.drawingMachinesArea,pf,2);
        //printJob.setPageable(book);
        printJob.setPrintable(this.drawingMachinesArea,pf);
        
        if (printJob.printDialog()) {
            try {
                printJob.print();
            } catch (Exception PrintException) {
                PrintException.printStackTrace();
            }
        }*/
        
        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
        DocPrintJob job = printService.createPrintJob();
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        pras.add(OrientationRequested.LANDSCAPE);
        pras.add(new MediaPrintableArea((float)0.0,(float)0.0,(float)8.5,(float)11.0,MediaPrintableArea.INCH));
        //pras.add(new MediaSize((float)0.0,(float)0.0,Size2DSyntax.INCH, MediaSizeName.NA_LETTER));
        pras.add(Finishings.NONE);
        DocAttributeSet das = new HashDocAttributeSet();
        Doc doc = new SimpleDoc(this.drawingMachinesArea, flavor, das);
        try {
          job.print(doc, pras);
        } catch (PrintException pe) {
          pe.printStackTrace();
        }

    }//GEN-LAST:event_jMenuItem6ActionPerformed
    
    private void jMenuItem16ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem16ActionPerformed
        // Add your handling code here:
        new DialogNotacion(new javax.swing.JFrame(), true).setVisible(true);
        changeIconBottonFromNotation();
        this.drawingMachinesArea.repaint();
    }//GEN-LAST:event_jMenuItem16ActionPerformed
    
    private void jButton20ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton20ActionPerformed
        // Add your handling code here:
        if(Maquina.running) return;
        
        Hashtable parametros = this.rootTreeTrace.dicMetavalores.getParametros();
        Vector vectorParametros = ((Vector2)currentMachineComponents).getParametros();
        Enumeration en = vectorParametros.elements();
        //parametros.clear(); //Transitorio
        while(en.hasMoreElements()){
            String parametro = (String)en.nextElement();
            if(!parametros.containsKey(parametro))
                parametros.put(parametro,new Parametro(parametro));
        }
        
        en = null;
        en = ((Hashtable)parametros.clone()).keys();
        
        while(en.hasMoreElements()){
            String parametro = (String)en.nextElement();
            if(!vectorParametros.contains(parametro))
                parametros.remove(parametro);
        }
        new DialogParametros(new javax.swing.JFrame(), true,parametros).setVisible(true);
        this.rootTreeTrace.dicMetavalores.setParametros0((Hashtable)parametros.clone());
    }//GEN-LAST:event_jButton20ActionPerformed
    
    private void jButton19ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton19ActionPerformed
        // Add your handling code here:
        if(Maquina.running) return;
        
        if(Maquina.selectedMachine!=null){
            ComandoEM comandoEM = new ComandoEM(Maquina.selectedMachine,(Vector2)currentMachineComponents);
            Comando.addComando2UR(comandoEM);
            if(!(Maquina.selectedMachine instanceof Enlace)){
                if(Maquina.selectedMachine.previa!=null){
                    ComandoIMG comandoIMG = new ComandoIMG(Maquina.selectedMachine.previa,(Vector2)currentMachineComponents,Maquina.selectedMachine,false);
                    comandoEM.setInverse(comandoIMG);
                } else if(Maquina.selectedMachine.proxima!=null && !(Maquina.selectedMachine.proxima instanceof EnlaceCompuesto)){
                    ComandoIMG comandoIMG = new ComandoIMG(Maquina.selectedMachine.proxima,(Vector2)currentMachineComponents,Maquina.selectedMachine,true);
                    comandoEM.setInverse(comandoIMG);
                } else{
                    ComandoIML comandoIML = new ComandoIML(Maquina.selectedMachine,(Vector2)currentMachineComponents);
                    comandoEM.setInverse(comandoIML);
                }
                Comando.flagDelete=true;
                Maquina.selectedMachine.deleteMachine(this.currentMachineComponents);
                Comando.flagDelete=false;
            } else{
                ComandoIE comandoIE = new ComandoIE(Maquina.selectedMachine,(Vector2)currentMachineComponents);
                comandoEM.setInverse(comandoIE);
                Maquina.selectedMachine.deleteMachine(this.currentMachineComponents);
                
            }
            Clipboard.sendMessage(false);
        } else{
            Clipboard.delete(currentMachineComponents);
        }
        Maquina.selectedMachine=null;
        this.drawingMachinesArea.repaint();
        
    }//GEN-LAST:event_jButton19ActionPerformed
    
    private void jButton32ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton32ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton32,JTV.ESTADO_PUNTERO);
    }//GEN-LAST:event_jButton32ActionPerformed
    
    private void jButton26ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton26ActionPerformed
        // Add your handling code here:
        if(this.jComboBox4.getItemCount()==0){
            JOptionPane.showMessageDialog(null, "No existen submáquinas disponibles para insertar","JTV",JOptionPane.WARNING_MESSAGE);
            return;
        }
        this.changePressedButton(jButton26,JTV.ESTADO_SUBMAQUINA);
    }//GEN-LAST:event_jButton26ActionPerformed
    
    private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
        // Add your handling code here:
        /*this.changePressedButton(jButton10,JTV.ESTADO_COPIADORA);
        Vector2 vector2 = (Vector2)currentMachineComponents;
        Vector out = vector2.getParametros();
        System.out.println(out.toString());*/
    }//GEN-LAST:event_jButton10ActionPerformed
    
    private void jButton31ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton31ActionPerformed
        // Add your handling code here:
        //this.showDialogEnlace = true;
        this.changePressedButton(jButton31,JTV.ESTADO_ENLACE_CONDICIONAL);
    }//GEN-LAST:event_jButton31ActionPerformed
    
    private void jButton25ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton25ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton25,JTV.ESTADO_SR);
    }//GEN-LAST:event_jButton25ActionPerformed
    
    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton9,JTV.ESTADO_SL);
    }//GEN-LAST:event_jButton9ActionPerformed
    
    private void jButton30ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton30ActionPerformed
        // Add your handling code here:
        //this.showDialogEnlace = false;
        this.changePressedButton(jButton30,JTV.ESTADO_ENLACE);
    }//GEN-LAST:event_jButton30ActionPerformed
    
    private void jButton24ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton24ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton24,JTV.ESTADO_R_NO_SIGMA);
    }//GEN-LAST:event_jButton24ActionPerformed
    
    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton8,JTV.ESTADO_L_NO_SIGMA);
    }//GEN-LAST:event_jButton8ActionPerformed
    
    private void jButton29ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton29ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton29,JTV.ESTADO_AUTOENLACE);
    }//GEN-LAST:event_jButton29ActionPerformed
    
    private void jButton23ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton23ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton23,JTV.ESTADO_R_SIGMA);
    }//GEN-LAST:event_jButton23ActionPerformed
    
    private void jButton28ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton28ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton28,JTV.ESTADO_CONCENTRADOR);
    }//GEN-LAST:event_jButton28ActionPerformed
    
    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton6,JTV.ESTADO_L);
    }//GEN-LAST:event_jButton6ActionPerformed
    
    private void jButton27ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton27ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton27,JTV.ESTADO_PARAMETRO);
    }//GEN-LAST:event_jButton27ActionPerformed
    
    private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton11,JTV.ESTADO_SIGMA);
    }//GEN-LAST:event_jButton11ActionPerformed
    
    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton5,JTV.ESTADO_SIMBOLO);
        
    }//GEN-LAST:event_jButton5ActionPerformed
    
    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
        // Add your handling code here:
        
        //final JFileChooser fc = new JFileChooser();
        while(true){
            int returnVal = fc.showSaveDialog(this);
            if (returnVal != JFileChooser.APPROVE_OPTION) return;
            fileMachine = fc.getSelectedFile();
            checkFileMachineExtension();
            if(fileMachine.exists()){
                //int yesnoVal = JOptionPane.showMessageDialog(null, "Esta máquina ya existe. ¿Desea sobreescribirla?","JTV",JOptionPane.YES_NO_OPTION);
                int yesnoVal = JOptionPane.showConfirmDialog(this,"Esta máquina ya existe. ¿Desea sobreescribirla?.","JTV",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                if(yesnoVal==JOptionPane.YES_OPTION) break;
            } else break;
        }
        
        try{
            this.saveMachine(fileMachine,true);
            this.jMenuItem4.setEnabled(false);
            this.jButton3.setEnabled(false);
        } catch(Exception ex){
            JOptionPane.showMessageDialog(null, "Se produjo un error durante el almacenamiento de la máquina.","JTV",JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
            this.fileMachine = null;
        }
        //this is where a real application would open the file.
        /*
        log.append("Opening: " + file.getName() + "." + newline);
        } else {
        log.append("Open command cancelled by user." + newline);
        }*/
    }//GEN-LAST:event_jMenuItem5ActionPerformed
    
    private void saveMachine(File file,boolean dialog) throws Exception{
        
        
        
        //this.setTitle("JTV ["+file.getPath()+"]");
        
        if(dialog){
            
            
            String name = file.getName().substring(0,file.getName().lastIndexOf('.')).toUpperCase();
            dicOfMachines.remove(rootTreeTrace2.getUserObject());
            if(rootTreeTrace2.getUserObject().equals(this.currentRepository))
                this.currentRepository = name;
            this.rootTreeTrace.setUserObject(name);
            dicOfMachines.put(name,this.rootTreeTrace2.vector2);
            this.rootTreeTrace2.vector2.setNombreLargo(name);
            this.rootTreeTrace2.vector2.setNombreCorto(name.substring(0,Math.min(name.length(),4)));
            //this.rootTreeTrace2.vector2.setNombreCorto(name.substring(0,4));
            this.rootTreeTrace2.refreshUserObject();
            this.rootTreeTrace2.refreshChildDependences();
            this.treeModel.reload();
            this.treeModel2.reload();
            this.setTitle("JTV ["+file.getPath()+"]");
        }
        
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write(getXML());
        fileWriter.close();
        
    }
    
    
    private void addRecentMachineItemMenu(File file){
        
        String path = file.getAbsolutePath();
        
        //this.jMenu6.a
    }
    
    public void checkFileMachineExtension(){
        String fileName = fileMachine.getName();
        if(!(fileName.endsWith(".jtv") || fileName.endsWith(".JTV"))){
            fileMachine = new File(fileMachine.getPath()+".jtv");
        }
    }
    
    public void checkFileMachineExtension2(){
        String fileName = fileLatex.getName();
        if(!(fileName.endsWith(".tex") || fileName.endsWith(".TEX"))){
            fileLatex = new File(fileLatex.getPath()+".tex");
        }
    }
    
    public void checkFileMachineExtension3(){
        String fileName = fileSOC.getName();
        if(!(fileName.endsWith(".soc") || fileName.endsWith(".SOC"))){
            fileSOC = new File(fileSOC.getPath()+".soc");
        }
    }
    
    private String getXML(){
        
        String xml="";
        //xml+="<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n\n";
        //xml+="<!DOCTYPE jtv SYSTEM \"file:C:/Documents and Settings/Administrador/Mis documentos/Mi estudio/JTV (Memoria)/JTV/JTV.dtd\">\n\n";
        //xml+="<!DOCTYPE jtv SYSTEM \""+JTV.pathJTV+"JTV.dtd\">\n\n";
        xml+="<jtv>\n";
        /*xml+="  <configuracion\n";
        xml+="      max-rafaga=\""+SharedInteger.getMaxValue()+"\"\n";
        xml+="      notacion-antigua=\""+Maquina.oldNotation+"\"\n";
        xml+="  />\n"; */
        Enumeration en = dicOfMachines.elements();
        while(en.hasMoreElements()){
            Vector2 machineComponent = (Vector2)en.nextElement();
            if(machineComponent.isMonocinta()) continue;
            xml+=machineComponent.getXML();
        }
        xml+="</jtv>\n";
        
        return xml;
    }
    
    private String getAllXML(){
        
        String xml="";
        
        xml+="<jtv>\n";
        
        Enumeration en = dicOfMachines.elements();
        while(en.hasMoreElements()){
            Vector2 machineComponent = (Vector2)en.nextElement();
            //if(machineComponent.isMonocinta()) continue;
            xml+=machineComponent.getXML();
        }
        xml+="</jtv>\n";
        
        return xml;
    }
    
    private String getXML(NodeTreeMachine node){
        if(!node.vector2.isPrincipal()) node.vector2.setPrincipal(true);
        String xml="";
        //xml+="<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n\n";
        //xml+="<!DOCTYPE jtv SYSTEM \"file:C:/Documents and Settings/Administrador/Mis documentos/Mi estudio/JTV (Memoria)/JTV/JTV.dtd\">\n\n";
        //xml+="<!DOCTYPE jtv SYSTEM \""+JTV.pathJTV+"JTV.dtd\">\n\n";
        xml+="<jtv>\n";
        /*xml+="  <configuracion\n";
        xml+="      max-rafaga=\""+SharedInteger.getMaxValue()+"\"\n";
        xml+="      notacion-antigua=\""+Maquina.oldNotation+"\"\n";
        xml+="  />\n"; */
        Enumeration en = node.preorderEnumeration();
        while(en.hasMoreElements()){
            Vector2 machineComponent = ((NodeTreeMachine)en.nextElement()).vector2;
            if(machineComponent.isMonocinta()) continue;
            xml+=machineComponent.getXML();
        }
        xml+="</jtv>\n";
        if(!node.vector2.isPrincipal()) //EDITAR
            node.vector2.setPrincipal(false);
        else{
            if(!node.vector2.getDependencia().equals("null"))
                node.vector2.setPrincipal(false);
        }
        
        return xml;
    }
    
    
    public void setArrayOfTapes(){
        this.rootTreeTrace.setArrayOfTapes(arrayOfTapes);
    }
    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        
        openMachine(null);
         
    }//GEN-LAST:event_jMenuItem3ActionPerformed
    
    private void jMenuItem15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem15ActionPerformed
        // Add your handling code here:
        new DialogMaximoRafaga(new javax.swing.JFrame(), true).setVisible(true);
        //System.out.println("HOLA");
    }//GEN-LAST:event_jMenuItem15ActionPerformed
    
    private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
        // Add your handling code here:
        this.changePressedButton(jButton12,JTV.ESTADO_R);
        //jButton12.setIcon(new ImageIcon(getClass().getResource("/images/R_push.gif")));
    }//GEN-LAST:event_jButton12ActionPerformed
    
    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // Add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // Add your handling code here:
        if(Maquina.running) return;
        
        jMenuItem1ActionPerformed(evt);
    }//GEN-LAST:event_jButton1ActionPerformed
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // Add your handling code here:
        if(Maquina.running) return;
        
        jMenuItem3ActionPerformed(evt);
        
        
    }//GEN-LAST:event_jButton2ActionPerformed
    
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // Add your handling code here:
        if(Maquina.running) return;
        
        jMenuItem6ActionPerformed(evt);
    }//GEN-LAST:event_jButton4ActionPerformed
    
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // Add your handling code here:
        if(Maquina.running) return;
        
        jMenuItem4ActionPerformed(evt);
        
        //jButton3.setEnabled(false);
        
        
    }//GEN-LAST:event_jButton3ActionPerformed
    
    private void jButton39ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton39ActionPerformed
        // Add your handling code here:
        if(Maquina.running) return;
        
        this.arrayOfTapes[this.jComboBox2.getSelectedIndex()].limpiar();
        this.drawingTapesArea.repaint();
    }//GEN-LAST:event_jButton39ActionPerformed
    
    private void jButton35ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton35ActionPerformed
        // Add your handling code here:
        
        if(Maquina.running) return;
        
        for(int i=0;i<this.arrayOfTapes.length;i++)
            arrayOfTapes[i].limpiar();
        
        this.drawingTapesArea.repaint();
    }//GEN-LAST:event_jButton35ActionPerformed
    
    private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed
        // Add your handling code here:
        
        if(Maquina.running) return;
        
        Comando.redo();
        //if(!Comando.redo()) this.jButton14.setEnabled(false);
        //if(!this.jButton13.isEnabled()) this.jButton13.setEnabled(true);
        
        drawingMachinesArea.repaint();
    }//GEN-LAST:event_jButton14ActionPerformed
    
    private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
        // Add your handling code here:
        
        if(Maquina.running) return;
        
        Comando.undo();
        //if(!Comando.undo()) this.jButton13.setEnabled(false);
        //if(!this.jButton14.isEnabled()) this.jButton14.setEnabled(true);
        
        drawingMachinesArea.repaint();
    }//GEN-LAST:event_jButton13ActionPerformed
    
    private void keyPressedHandler(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_keyPressedHandler
        // Add your handling code here:
        if(evt.getKeyCode()==evt.VK_ENTER){
            if(Maquina.running) return;
            String input = this.jTextField1.getText();
            if(input==null || input.length()==0){
                
                JOptionPane.showMessageDialog(null, "Debe ingresar una cadena no vacía para cargar la Cinta " + (this.jComboBox2.getSelectedIndex()+1),"JTV",JOptionPane.WARNING_MESSAGE);
                
            } else if(!testInput(input)){
                
                JOptionPane.showMessageDialog(null, "Cada carácter de la entrada debe pertenecer al conjunto {a..z}U{0..9}U{#}","JTV",JOptionPane.WARNING_MESSAGE);
                this.jTextField1.selectAll();
            } else{
                this.arrayOfTapes[this.jComboBox2.getSelectedIndex()].cargar(input);
                this.drawingTapesArea.repaint();
            }
            
        }
        
    }//GEN-LAST:event_keyPressedHandler
    
    private void jButton38ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton38ActionPerformed
        // Add your handling code here:
        try{
            Cinta cinta = this.arrayOfTapes[this.jComboBox2.getSelectedIndex()];
            cinta.browseMode=true;
            cinta.incrPageBrowse();
            cinta.dibujar(this.drawingTapesArea.getGraphics());
            cinta.browseMode=false;
        } catch(Exception ex){
            System.out.println("Excepción");
        }
    }//GEN-LAST:event_jButton38ActionPerformed
    
    private void jButton36ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton36ActionPerformed
        // Add your handling code here:
        try{
            Cinta cinta = this.arrayOfTapes[this.jComboBox2.getSelectedIndex()];
            cinta.browseMode=true;
            cinta.decrPageBrowse();
            cinta.dibujar(this.drawingTapesArea.getGraphics());
            cinta.browseMode=false;
        } catch(Exception ex){
            System.out.println("Excepción");
        }
    }//GEN-LAST:event_jButton36ActionPerformed
    
    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // Add your handling code here:
        
    }//GEN-LAST:event_jTextField1ActionPerformed
    
          private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
              // Add your handling code here:
              
              int retVal=JOptionPane.NO_OPTION;
              
              if(this.isMachineModified())
                  retVal = JOptionPane.showConfirmDialog(this,"Esta máquina ha sido cambiada. ¿Desea guardarla?.","JTV",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);
              
              if(retVal==JOptionPane.CANCEL_OPTION) return;
              
              if(retVal==JOptionPane.YES_OPTION){
                  
                  retVal=JOptionPane.NO_OPTION;
                  
                  //final JFileChooser fc = new JFileChooser();
            /*int returnVal2 = fc.showSaveDialog(this);
            if (returnVal2 != JFileChooser.APPROVE_OPTION) {
             
                return;
            }*/
                  
                  
                  
                  //fileMachine = fc.getSelectedFile();
                  
                  while(true){
                      int returnVal = fc.showSaveDialog(this);
                      if (returnVal != JFileChooser.APPROVE_OPTION) return;
                      fileMachine = fc.getSelectedFile();
                      checkFileMachineExtension();
                      if(fileMachine.exists()){
                          int yesnoVal = JOptionPane.showConfirmDialog(this,"Esta máquina ya existe. ¿Desea sobreescribirla?.","JTV",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                          if(yesnoVal==JOptionPane.YES_OPTION) break;
                      } else break;
                  }
                  
                  try{
                      //this.saveMachine(fileMachine,dialog);
                      FileWriter fileWriter = new FileWriter(fileMachine);
                      fileWriter.write(getXML());
                      fileWriter.close();
                      //this.jMenuItem4.setEnabled(false);
                  } catch(Exception ex){
                      ex.printStackTrace();
                      JOptionPane.showMessageDialog(null, "Se produjo un error durante el almacenamiento de la máquina.","JTV",JOptionPane.ERROR_MESSAGE);
                      this.fileMachine = null;
                  }
                  
              }
              
              
              if(retVal==JOptionPane.NO_OPTION){
                  
                  rootTreeTrace.setUserObject("NUEVA");
                  
                  Enumeration en = this.rootTreeTrace2.preorderEnumeration();
                  while(en.hasMoreElements())
                      this.dicOfMachines.remove((String)((NodeTreeMachine)en.nextElement()).getUserObject());
                  
                  
                  rootTreeTrace2.removeAllChildren();
                  treeModel.reload();
                  treeModel2.reload();
                  
                  rootTreeTrace2.setUserObject("NUEVA");
                  
                  Vector2 vector2 = new Vector2();
                  vector2.setNombreLargo("NUEVA");
                  this.currentRepository = "NUEVA";
                  this.currentMachineComponents = vector2;
                  vector2.setNombreCorto("NUEV");
                  vector2.setDescripcion("");
                  vector2.setNumeroCintas(this.arrayOfTapes.length);
                  vector2.setPrincipal(true);
                  vector2.setMonocinta(false);
                  rootTreeTrace2.vector2 = vector2;
                  //this.dicOfMachines.clear();
                  this.dicOfMachines.put("NUEVA",vector2);
                  this.fileMachine = null;
                  //this.jTree1.repaint();
                  //this.jTree2.repaint();
                  this.drawingMachinesArea.repaint();
                  this.jMenuItem4.setEnabled(false);
                  this.jButton3.setEnabled(false);
                  setTitle("JTV [NUEVA]");
                  
                  
                  
                  
              }
          }//GEN-LAST:event_jMenuItem1ActionPerformed
          
          private void jMenuItem27ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem27ActionPerformed
              DialogPresentacioAcercaDe dp = new DialogPresentacioAcercaDe(this,false);
              dp.setVisible(true);
          }//GEN-LAST:event_jMenuItem27ActionPerformed
          
  private void jButton21ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton21ActionPerformed
// Add your handling code here:
      Maquina.running=false;
      if(treeModel.getRoot()!=rootTreeTrace.getRoot()){
          treeModel.setRoot(rootTreeTrace.getRoot());
          currentMachineComponents = getRepository((String)rootTreeTrace.getUserObject());
          currentRepository = (String)rootTreeTrace.getUserObject();
          arrayOfTapes = rootTreeTrace.arrayOfTapes;
          drawingMachinesArea.repaint();
          drawingTapesArea.repaint();
      }
      this.jButton18.setEnabled(true);
      this.jButton21.setEnabled(false);
      this.jTabbedPane1.setEnabledAt(1,true);
      this.enableMenus(true);
      /*this.enableMachinesToobars(true);
      this.enableTapesComponents(true);
      this.enableUpperButtons(true);
      this.enableUpperCombobox(true);*/
      selectedNode = null;
      rootTreeTrace.removeAllChildren();
      this.rootTreeTrace.setArrayOfTapes(arrayOfTapes);
      rootTreeTrace.setMachine(mainMachine);
      rootTreeTrace.setThread(new Thread(rootTreeTrace));
      rootTreeTrace.dicMetavalores.limpiar2();
      playTreeTrace = rootTreeTrace;
      this.numberOfNodes.reset();
      Maquina.playMachine = null;
      repaint();
      treeModel.reload();
      System.gc();
      JOptionPane.showMessageDialog(null, "Simulación finalizada, ATE liberado.","JTV",JOptionPane.INFORMATION_MESSAGE);
  }//GEN-LAST:event_jButton21ActionPerformed
  
  private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton18ActionPerformed
// Add your handling code here:
      
      //this.rootTreeTrace.start();
      SharedInteger numOfNodes;
      Maquina inicial = ((Vector2)this.getRepository(this.currentRepository)).inicial;
      if(inicial==null){
          JOptionPane.showMessageDialog(this,"No existe máquina inicial desde donde comenzar la ejecución.","JTV",JOptionPane.ERROR_MESSAGE);
          return;
      }
      
      Maquina.running=true;
      Maquina.selectedMachine = null;
      this.jTabbedPane1.setSelectedIndex(0);
      this.jTabbedPane1.setEnabledAt(1,false);
      this.jButton18.setEnabled(false);
      this.jButton21.setEnabled(true);
      this.enableMenus(false);
      /*this.enableMachinesToobars(false);
      this.enableTapesComponents(false);
      this.enableUpperButtons(false);
      this.enableUpperCombobox(false);*/
      
      this.drawingMachinesArea.repaint();
      
      if(selectedNode!=null){
          
          
          NodeTreeTrace nodeParent = (NodeTreeTrace) selectedNode.getParent();
          
          if(!selectedNode.isRoot() && selectedNode.getParent().getIndex(selectedNode)==(selectedNode.getParent().getChildCount()-1) && selectedNode.getChildCount()==0){
              
              numberOfNodes.reset();
              
              if(((NodeTreeTrace)selectedNode).getIconValue()==JTV.MyRenderer.ICONO_EXPANDIR){
                  
                  nodeParent.setThread(new Thread(nodeParent));
                  playTreeTrace = nodeParent;
                  playTreeTrace.getNumOfNodes().reset();
                  playTreeTrace.arrayOfTapes = arrayOfTapes;
                  playTreeTrace.flagAOT0= false;
                  numOfNodes = playTreeTrace.getNumOfNodes();
                  playTreeTrace.start(selectedNode);
                  jTree1.updateUI();
              } else{
                  
                  nodeParent.setThread(new Thread(nodeParent));
                  playTreeTrace = nodeParent;
                  playTreeTrace.getNumOfNodes().reset();
                  playTreeTrace.arrayOfTapes = arrayOfTapes;
                  playTreeTrace.flagAOT0= false;
                  numOfNodes = playTreeTrace.getNumOfNodes();
                  playTreeTrace.start(selectedNode);
                  jTree1.updateUI();
              }
              synchronized(numOfNodes){
                  try{
                      numOfNodes.wait();
                  } catch(InterruptedException ie){
                      ie.printStackTrace();
                  }
              }

              JOptionPane.showMessageDialog(null, "ATE generado, simulación iniciada.","JTV",JOptionPane.INFORMATION_MESSAGE);
              return;
          }
      } else{
          
          this.playTreeTrace.setMachine(inicial);  //AGREGADO 12-12-2002
          numOfNodes = playTreeTrace.getNumOfNodes();
          this.playTreeTrace.start();
          jTree1.updateUI();
          synchronized(numOfNodes){
              try{
                  
                  numOfNodes.wait();
              } catch(InterruptedException ie){
                  ie.printStackTrace();
              }
          }
          JOptionPane.showMessageDialog(null, "ATE generado, simulación iniciada.","JTV",JOptionPane.INFORMATION_MESSAGE);
      }
      
  }//GEN-LAST:event_jButton18ActionPerformed
  
  private void jMenuItem2StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jMenuItem2StateChanged
// Add your handling code here:
      
  }//GEN-LAST:event_jMenuItem2StateChanged
  
  private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
      
      int retVal=JOptionPane.NO_OPTION;
      
      if(this.isMachineModified())
          retVal = JOptionPane.showConfirmDialog(this,"Esta máquina ha sido cambiada. ¿Desea guardarla?.","JTV",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);
      
      if(retVal==JOptionPane.CANCEL_OPTION) return;
      
      if(retVal==JOptionPane.YES_OPTION){
          
          //final JFileChooser fc = new JFileChooser();
          int returnVal2 = 0; //fc.showSaveDialog(this);
          while(true){
              returnVal2 = fc.showSaveDialog(this);
              if (returnVal2 != JFileChooser.APPROVE_OPTION) break;
              fileMachine = fc.getSelectedFile();
              checkFileMachineExtension();
              if(fileMachine.exists()){
                  //int yesnoVal = JOptionPane.showMessageDialog(null, "Esta máquina ya existe. ¿Desea sobreescribirla?","JTV",JOptionPane.YES_NO_OPTION);
                  int yesnoVal = JOptionPane.showConfirmDialog(this,"Esta máquina ya existe. ¿Desea sobreescribirla?.","JTV",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                  if(yesnoVal==JOptionPane.YES_OPTION) break;
              } else break;
          }
          
          if (returnVal2 == JFileChooser.APPROVE_OPTION) {
              
              //fileMachine = fc.getSelectedFile();
              try{
                  //this.saveMachine(fileMachine,dialog);
                  FileWriter fileWriter = new FileWriter(fileMachine);
                  fileWriter.write(getXML());
                  fileWriter.close();
                  //this.jMenuItem4.setEnabled(false);
              } catch(Exception ex){
                  ex.printStackTrace();
                  JOptionPane.showMessageDialog(null, "Se produjo un error durante el almacenamiento de la máquina.","JTV",JOptionPane.ERROR_MESSAGE);
                  this.fileMachine = null;
              }
          }
      }
      
      
      String xml = getXMLConfig();
      try{
          
          File file = new File(java.net.URLDecoder.decode(System.getProperty("user.dir") + File.separatorChar + "JTVConfig.xml", "UTF-8"));
          FileWriter fileWriter = new FileWriter(file);
          fileWriter.write(xml);
          fileWriter.close();
          xml=null;
      } catch(Exception ex){
          JOptionPane.showMessageDialog(null, "Se produjo un error durante el almacenamiento de la configuración de JTV","JTV",JOptionPane.ERROR_MESSAGE);
          ex.printStackTrace();
      }
      this.dispose();
      System.exit(0);
      // Add your handling code here:
  }//GEN-LAST:event_jMenuItem2ActionPerformed
  
//  public String getXMLConfig(){
//
//      String xml="";
//      xml+="<jtv-config\n";
//      xml+="      max-rafaga=\""+SharedInteger.getMaxValue()+"\"\n";
//      xml+="      notacion-antigua=\""+Maquina.oldNotation+"\"\n";
//      xml+="/>\n";
//
//      return xml;
//  }
  
  public String getXMLConfig(){
      
      String xml="";
      xml+="<jtv-config max-rafaga=\""+SharedInteger.getMaxValue()+"\" notacion-antigua=\""+Maquina.oldNotation+"\">\n";
      xml+=JTV.listaMaquinasRecientes.getXML();
      xml+="</jtv-config>";
      
      return xml;
  }
  
  private void jMenuItem2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenuItem2MouseClicked
// Add your handling code here:
      
  }//GEN-LAST:event_jMenuItem2MouseClicked
  
  private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
// Add your handling code here:
      this.changePressedButton(jButton7,JTV.ESTADO_L_SIGMA);
  }//GEN-LAST:event_jButton7ActionPerformed
  
  private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed
// Add your handling code here:
  }//GEN-LAST:event_formMousePressed
  
  /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
        //System.exit (0);
        jMenuItem2ActionPerformed(null);
    }//GEN-LAST:event_exitForm
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        
        //String _languajeBundlePath = JTV.LANG_BUNDLE_PATH + args[0];
        //JTV jtv = new JTV(_languajeBundlePath);
        //System.out.println(System.getProperty("java.class.path"));
        try{
            if(args.length>1) throw new Exception();
            if(args.length==0)
                JTV.numeroCintas=1;
            else{
                JTV.numeroCintas=Integer.parseInt(args[0]);
                if(0>=JTV.numeroCintas || JTV.numeroCintas>=JTV.MAXIMO_NUMERO_CINTAS+1){
                    System.out.println("El número de cintas debe ser entre 1 y " + JTV.MAXIMO_NUMERO_CINTAS);
                    return;
                }
            }
        } catch(Exception ex){
            System.out.println("Forma de uso: java -classpath \"JTV.jar\" cl.jtv.JTV <numero-de-cintas>");
            return;
        }
        
        try{
            //System.out.println(System.getProperty("java.class.path"));
            DialogPresentacio dp = new DialogPresentacio(null,false);
            
            Thread presentacionThread = new Thread(dp);
            presentacionThread.start();
            JTV jtv = new JTV(null);
            
            jtv.setSize(Toolkit.getDefaultToolkit().getScreenSize());
            jtv.setLocation(0,0);
            jtv.setTitle("JTV [NUEVA]");
            
            
            presentacionThread.interrupt();
            dp.setVisible(false);
            dp.dispose();
            dp = null;
            jtv.setVisible(true);
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    /** Getter for property drawingTapesArea.
     * @return Value of property drawingTapesArea.
     */
    public javax.swing.JPanel getDrawingTapesArea() {
        return drawingTapesArea;
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton11;
    private javax.swing.JButton jButton12;
    private javax.swing.JButton jButton13;
    private javax.swing.JButton jButton14;
    private javax.swing.JButton jButton15;
    private javax.swing.JButton jButton16;
    private javax.swing.JButton jButton17;
    private javax.swing.JButton jButton18;
    private javax.swing.JButton jButton19;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton20;
    private javax.swing.JButton jButton21;
    private javax.swing.JButton jButton23;
    private javax.swing.JButton jButton24;
    private javax.swing.JButton jButton25;
    private javax.swing.JButton jButton26;
    private javax.swing.JButton jButton27;
    private javax.swing.JButton jButton28;
    private javax.swing.JButton jButton29;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton30;
    private javax.swing.JButton jButton31;
    private javax.swing.JButton jButton32;
    private javax.swing.JButton jButton33;
    private javax.swing.JButton jButton34;
    private javax.swing.JButton jButton35;
    private javax.swing.JButton jButton36;
    private javax.swing.JButton jButton37;
    private javax.swing.JButton jButton38;
    private javax.swing.JButton jButton39;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JComboBox jComboBox4;
    private javax.swing.JComboBox jComboBox5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenu jMenu6;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem10;
    private javax.swing.JMenuItem jMenuItem11;
    private javax.swing.JMenuItem jMenuItem12;
    private javax.swing.JMenuItem jMenuItem13;
    private javax.swing.JMenuItem jMenuItem14;
    private javax.swing.JMenuItem jMenuItem15;
    private javax.swing.JMenuItem jMenuItem16;
    private javax.swing.JMenuItem jMenuItem17;
    private javax.swing.JMenuItem jMenuItem18;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem26;
    private javax.swing.JMenuItem jMenuItem27;
    private javax.swing.JMenuItem jMenuItem29;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem30;
    private javax.swing.JMenuItem jMenuItem31;
    private javax.swing.JMenuItem jMenuItem32;
    private javax.swing.JMenuItem jMenuItem33;
    private javax.swing.JMenuItem jMenuItem34;
    private javax.swing.JMenuItem jMenuItem35;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JMenuItem jMenuItem7;
    private javax.swing.JMenuItem jMenuItem8;
    private javax.swing.JMenuItem jMenuItem9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JToolBar jToolBar3;
    private javax.swing.JToolBar jToolBar4;
    private javax.swing.JToolBar jToolBar5;
    private javax.swing.JToolBar jToolBar6;
    // End of variables declaration//GEN-END:variables
    private javax.swing.JTree jTree1,jTree2;
    private NodeTreeTrace rootTreeTrace,playTreeTrace;
    private NodeTreeMachine rootTreeTrace2,copycutTreeMachine=null;
    private DefaultMutableTreeNode selectedNode=null,selectedNode2=null;
    private DefaultTreeModel treeModel,treeModel2;
    private DefaultTreeSelectionModel treeSelectionModel;
    private TreePath treePath;
    private javax.swing.JScrollPane scrollPane11;
    private javax.swing.JScrollPane scrollPanel2;
    //private TraceDispatcher traceDispatcher;
    //private TestTree testTree;
    private FlagContexto flagContexto;
    private SharedInteger numberOfNodes;
    private Hashtable dicOfMachines;
    private Vector currentMachineComponents;
    private String currentRepository;
    private DiccionarioMetavalores currentDicMetavalores;
    private Submaquina mainSubmachine;
    public static int estadoJTV;
    public static boolean modifiedMachine=false;
    public static boolean savedMachine=false;
    public static int draggedType=JTV.DRAGGED_NOTHING;
    public static String pathJTV;
    public static File rootJTV;
    private String languajeBundlePath;
    private static int numeroCintas;
    //private JPanel drawingMachinesArea;
    private DrawingMachinesArea drawingMachinesArea;
    private JPopupMenu popup,popup2;
    private Cursor cursor;
    //private Maquina drawingMachine,mainMachine,searchedMachine,insertMachine;
    private Maquina drawingMachine,mainMachine,insertMachine;
    public static Maquina searchedMachine;
    public static boolean flagLatex = true;
    private Maquina maquinaI,maquinaF;
    private Vector puntosEnlace=new Vector();
    private int pressedX,pressedY,firstPressedX,firstPressedY,movedX,movedY;
    private Point searchedPoint;
    private boolean leftInsert;
    private boolean showDialogEnlace;
    private boolean refreshSubmaquinas = false;
    private Cinta[] arrayOfTapes;
    private Cinta writeTape;
    private JPanel drawingTapesArea;
    private JButton lastPressedButton;
    private Submaquina submaquina1,submaquina2,submaquina3;
    private File fileMachine=null,fileLatex=null,fileSOC=null;
    private JFileChooser fc = new JFileChooser();
    private JFileChooser fc2 = new JFileChooser();
    private JFileChooser fc3 = new JFileChooser();
    private javax.swing.filechooser.FileFilter ff;
    private javax.swing.filechooser.FileFilter ff2;
    private javax.swing.filechooser.FileFilter ff3;
}
