/* Copyright Nabil Alikhan. 2010.
 * This file is part of BLAST Ring Image Generator (BRIG).
 * BRIG is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * BRIG is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 *  along with BRIG.  If not, see <http://www.gnu.org/licenses/>.
 */

package brig;

import javax.swing.DefaultListModel;
import javax.swing.JColorChooser;
import javax.swing.JList;
import javax.swing.JOptionPane;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import org.jdom.*;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JFileChooser;
import org.jdom.input.SAXBuilder;

/**
 *
 * @author Nabil
 */
public class Two extends javax.swing.JFrame {

    private DefaultListModel refModel;
    private DefaultListModel ringModel;
    private DefaultListModel genomeModel;
    Color selected = Color.red;
    boolean multiFasta = false; 
    int got = 0;
    One parent; 
    /** Creates new form Two */
    public Two(One par) {
        parent = par;
        initTwo();
    }

    public Two() {
        initTwo();
    }

    private void initTwo(){
       FixRingNumber();
        ringModel = new DefaultListModel();
        genomeModel = new DefaultListModel();
        refModel = new DefaultListModel();
        List special = BRIG.PROFILE.getRootElement().getChildren("special");
        for (int k = 0; k < special.size(); k++) {
            refModel.addElement(((Element) special.get(k)).getAttributeValue("value"));
        }
        List<Element> oldRefs = BRIG.PROFILE.getRootElement().getChildren("refDir");
        for (int i = 0; i < oldRefs.size(); i++) {
            List<Element> fil = oldRefs.get(i).getChildren("refFile");
            for (int j = 0; j < fil.size(); j++) {
                try {
                    refModel.addElement(fil.get(j).getAttributeValue("location"));
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this,
                            "Could not open " + oldRefs.get(i).getAttributeValue("location") + " because:\n" + e.getMessage(),
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        }
        initComponents();
        checkMultiFasta();

        ringu.setModel(ringModel);
        MouseListener mouseListener = new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    save();
                    BRIG.POSITION = ringu.locationToIndex(e.getPoint());
                    reload();
                }
            }
        };
        setTitle(BRIG.header + " - Customize rings") ;
        ringu.addMouseListener(mouseListener);
        MouseAdapter listener = new ReorderListener(ringu,this);
        ringu.addMouseListener(listener);
        ringu.addMouseMotionListener(listener);
        jButton2.setToolTipText("Click here to add custom annotations this ring");
        blastType.setToolTipText("Specify blast program to run");
        legendCheck.setToolTipText(("Legend will show a coloured key of upper/lower identity"));
        labelCheckBox.setToolTipText("Image will show labels for this ring, NOT recommend for BLAST results");
        queryField.setToolTipText("Reference sequence, you can change this on the previous page");
        upperInt.setToolTipText("This value will be used to show a coloured key in the legend");
        lowerInt.setToolTipText("This value will be used to calculate colour gradient and to show a coloured key in the legend");
        queryField.setEditable(false);
        fixFileType();
        reload();
    }
    
    /** 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 Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu2 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();
        jPopupMenu1 = new javax.swing.JPopupMenu();
        jPanel3 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        queryField = new javax.swing.JTextField();
        jScrollPane3 = new javax.swing.JScrollPane();
        ringu = new javax.swing.JList();
        jLabel5 = new javax.swing.JLabel();
        currentRingField = new javax.swing.JTextField();
        InsertRing = new javax.swing.JButton();
        spacerField = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        genbankType = new javax.swing.JComboBox();
        jLabel11 = new javax.swing.JLabel();
        changeGenbank = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        poolList = new javax.swing.JList(refModel);
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        removeRingButton = new javax.swing.JButton();
        newRingButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        genomeList = new javax.swing.JList();
        jPanel4 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        legendCheck = new javax.swing.JCheckBox();
        labelCheckBox = new javax.swing.JCheckBox();
        graphMax = new javax.swing.JLabel();
        graphMaxField = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        selectedColourBox = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        upperInt = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        lowerInt = new javax.swing.JTextField();
        blastType = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        Size = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jButton6 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        File = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        OpenMenu = new javax.swing.JMenuItem();
        SaveMenu = new javax.swing.JMenuItem();
        jMenuItem8 = new javax.swing.JMenuItem();
        bundle = new javax.swing.JMenuItem();
        QuitMenu = new javax.swing.JMenuItem();
        jMenu4 = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu5 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem6 = new javax.swing.JMenuItem();
        jMenuItem7 = new javax.swing.JMenuItem();

        jMenuItem4.setText("BRIG Options");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });

        jMenuItem5.setText("BRIG Options");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem5ActionPerformed(evt);
            }
        });

        jMenu2.setText("File");
        jMenuBar2.add(jMenu2);

        jMenu3.setText("Edit");
        jMenuBar2.add(jMenu3);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(721, 550));

        jLabel3.setText("Reference/Database sequence:");

        ringu.setModel(ringModel);
        jScrollPane3.setViewportView(ringu);

        jLabel5.setText("Legend text:");

        currentRingField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                currentRingFieldKeyTyped(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                currentRingFieldKeyReleased(evt);
            }
        });

        InsertRing.setText("Insert new ring");
        InsertRing.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                InsertRingActionPerformed(evt);
            }
        });

        spacerField.setText("-1");

        jLabel10.setText("Spacer:");

        genbankType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nucleotide", "Protein" }));

        jLabel11.setText("Genbank sequence:");

        changeGenbank.setText("Change");
        changeGenbank.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeGenbankActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(currentRingField, javax.swing.GroupLayout.DEFAULT_SIZE, 656, Short.MAX_VALUE))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 741, Short.MAX_VALUE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(queryField, javax.swing.GroupLayout.DEFAULT_SIZE, 546, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(InsertRing)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 179, Short.MAX_VALUE)
                        .addComponent(jLabel11)
                        .addGap(18, 18, 18)
                        .addComponent(genbankType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(changeGenbank)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(spacerField, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(queryField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(InsertRing)
                    .addComponent(spacerField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10)
                    .addComponent(jLabel11)
                    .addComponent(genbankType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(changeGenbank))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(currentRingField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel2.setText("Data pool: ");

        jLabel8.setText("Data shown on this ring:");

        poolList.setModel(refModel);
        poolList.setFixedCellWidth(250);
        poolList.setFocusCycleRoot(true);
        jScrollPane4.setViewportView(poolList);

        jButton1.setText("Add data");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("Remove data");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        removeRingButton.setText("Remove ring");
        removeRingButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeRingButtonActionPerformed(evt);
            }
        });

        newRingButton.setText("Add new ring");
        newRingButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newRingButtonActionPerformed(evt);
            }
        });

        genomeList.setModel(genomeModel);
        genomeList.setFixedCellWidth(250);
        jScrollPane1.setViewportView(genomeList);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 501, Short.MAX_VALUE)
                        .addComponent(newRingButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removeRingButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 741, Short.MAX_VALUE)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 741, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(removeRingButton)
                    .addComponent(newRingButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton3)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton2.setText("Add custom features");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        legendCheck.setSelected(true);
        legendCheck.setText("Show thresholds in legend?");

        labelCheckBox.setText("Show labels?");

        graphMax.setText("Graph maximum value");

        graphMaxField.setText("Default");

        jButton4.setText("Next >");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jButton2)
            .addComponent(legendCheck)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(335, Short.MAX_VALUE)
                .addComponent(jButton4))
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(labelCheckBox)
                .addContainerGap())
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(graphMax)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(graphMaxField, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(139, 139, 139))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(jButton2)
                .addGap(13, 13, 13)
                .addComponent(legendCheck)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(graphMax)
                    .addComponent(graphMaxField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(89, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(173, Short.MAX_VALUE)
                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        selectedColourBox.setBackground(new java.awt.Color(153, 102, 0));
        selectedColourBox.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        selectedColourBox.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                selectedColourBoxMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout selectedColourBoxLayout = new javax.swing.GroupLayout(selectedColourBox);
        selectedColourBox.setLayout(selectedColourBoxLayout);
        selectedColourBoxLayout.setHorizontalGroup(
            selectedColourBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 68, Short.MAX_VALUE)
        );
        selectedColourBoxLayout.setVerticalGroup(
            selectedColourBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 28, Short.MAX_VALUE)
        );

        jLabel7.setText("Lower identity threshold (%)");

        upperInt.setText("70");

        jLabel6.setText("Upper identity threshold (%)");

        lowerInt.setText("50");

        jLabel1.setText("Blast type:");

        jLabel4.setText("Ring colour:");

        Size.setText("40");

        jLabel9.setText("Ring size ");

        jButton6.setText("< Prev");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addGap(198, 198, 198)
                        .addComponent(Size, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel4)
                                .addComponent(jLabel6))
                            .addComponent(jLabel7))
                        .addGap(37, 37, 37)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(selectedColourBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(upperInt, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(blastType, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lowerInt, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jButton6))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(blastType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(21, 21, 21)
                        .addComponent(jLabel6))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(37, 37, 37)
                        .addComponent(upperInt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(11, 11, 11)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lowerInt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7)))
                    .addComponent(selectedColourBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel9)
                    .addComponent(Size, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        File.setText("File");

        jMenuItem1.setText("New");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        File.add(jMenuItem1);

        OpenMenu.setText("Open...");
        OpenMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OpenMenuActionPerformed(evt);
            }
        });
        File.add(OpenMenu);

        SaveMenu.setText("Save As...");
        SaveMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveMenuActionPerformed(evt);
            }
        });
        File.add(SaveMenu);

        jMenuItem8.setText("Save As Profile...");
        jMenuItem8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem8ActionPerformed(evt);
            }
        });
        File.add(jMenuItem8);

        bundle.setText("Bundle Session...");
        bundle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bundleActionPerformed(evt);
            }
        });
        File.add(bundle);

        QuitMenu.setText("Quit");
        QuitMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                QuitMenuActionPerformed(evt);
            }
        });
        File.add(QuitMenu);

        jMenuBar1.add(File);

        jMenu4.setText("Modules");

        jMenuItem3.setText("Create graph files");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu4.add(jMenuItem3);

        jMenuBar1.add(jMenu4);

        jMenu5.setText("Preferences");

        jMenuItem2.setText("Image options");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu5.add(jMenuItem2);

        jMenuItem6.setText("BRIG options");
        jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem6ActionPerformed(evt);
            }
        });
        jMenu5.add(jMenuItem6);

        jMenuItem7.setText("About...");
        jMenuItem7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem7ActionPerformed(evt);
            }
        });
        jMenu5.add(jMenuItem7);

        jMenuBar1.add(jMenu5);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        save();

        parent.reload();

        this.dispose();
    }//GEN-LAST:event_jButton6ActionPerformed

    private void newRingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newRingButtonActionPerformed
        save();
        Element newChild = new Element("ring");
        List doop = BRIG.PROFILE.getRootElement().getChildren("ring");
        // Shift all rings down one, to make room for new ring
        for (int i = 0; i < doop.size(); i++) {
            Element ccur = (Element) doop.get(i);
            int nextInt = Integer.parseInt(ccur.getAttributeValue("position"));
            if (nextInt >= (BRIG.POSITION + 1)) {
                nextInt++;
                ccur.setAttribute("position", Integer.toString(nextInt));
            }
        }
        Color newcol = BRIG.FetchColor(BRIG.POSITION + 1);
        String col = newcol.getRed() + "," + newcol.getGreen() + "," + newcol.getBlue();
        newChild.setAttribute("colour", col);
        newChild.setAttribute("name", "null");
        newChild.setAttribute("position", Integer.toString(BRIG.POSITION + 1));
        BRIG.PROFILE.getRootElement().addContent(newChild);
        BRIG.POSITION++;
        reload();
    }//GEN-LAST:event_newRingButtonActionPerformed

    private void removeRingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRingButtonActionPerformed
        save();
        List doop = BRIG.PROFILE.getRootElement().getChildren("ring");
        Element currentRing = (Element) doop.get(BRIG.POSITION);
        for (int z = 0; z < doop.size(); z++) {
            if (((Element) doop.get(z)).getAttributeValue("position").compareTo(Integer.toString(BRIG.POSITION)) == 0) {
                currentRing = (Element) doop.get(z);
            }
        }
        int currInt = Integer.parseInt(currentRing.getAttributeValue("position"));
        currentRing.detach();
        doop = BRIG.PROFILE.getRootElement().getChildren("ring");
        BRIG.POSITION--;
        for (int z = 0; z < doop.size(); z++) {
            int pos = Integer.parseInt(((Element) doop.get(z)).getAttributeValue("position"));
            if (pos >= currInt  ) {
                int newInt = Integer.parseInt(((Element) doop.get(z)).getAttributeValue("position")) -1 ;
                ((Element) doop.get(z)).setAttribute("position", Integer.toString(newInt));
            }
        }        
        if (BRIG.POSITION < 0) {
            BRIG.POSITION = 0;
        }
        reload();
    }//GEN-LAST:event_removeRingButtonActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        save();
        new CustomXML(this).setVisible(true);
        reload();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        save();
        try {
            if (BRIG.isBlastOk()) {
                String query = BRIG.PROFILE.getRootElement().getAttributeValue("queryFile");
                if (!multiFasta) {
                    BRIG.PROFILE.getRootElement().removeAttribute("spacer");
                    new Three2(this).setVisible(true);
                    this.dispose();
                } else {
                    try {
                        int spacer = Integer.parseInt(spacerField.getText());
                        new Three2(this).setVisible(true);
                        this.setVisible(false);
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(this,
                                "Spacer value is not an integer",
                                "ERROR!",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this,
                        "Could not run BLAST, please check it is installed and BRIG's BLAST location is correct",
                        "ERROR!",
                        JOptionPane.ERROR_MESSAGE);
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this,
                    "Could not run BLAST, please check it is installed and BRIG's BLAST location is correct",
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        new Options().setVisible(true);
}//GEN-LAST:event_jMenuItem4ActionPerformed

    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
        new Options().setVisible(true);
}//GEN-LAST:event_jMenuItem5ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        SAXBuilder builder = new SAXBuilder();
        try {
            BRIG.PROFILE = builder.build("default-BRIG.xml");
            //Open one page.
            reload();
        } catch (JDOMException e) {
            JOptionPane.showMessageDialog(this,
                    "default-BRIG.xml is corrupt. Please check:\n" + e.getMessage(),
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this,
                    "Could not read default-BRIG.xml because:\n" + e.getMessage(),
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenMenuActionPerformed
        final JFileChooser fc = new JFileChooser();
        fc.showOpenDialog(this);
        if (fc.getSelectedFile() != null) {
            try {
                SAXBuilder builder = new SAXBuilder();
                try {
                    Document temp = builder.build(fc.getSelectedFile().toString());
                    String bl = null;
                    if (BRIG.PROFILE.getRootElement().getChild("brig_settings") != null){
                        if(BRIG.PROFILE.getRootElement().getChild("brig_settings").getAttributeValue("blastLocation") != null){
                            bl = BRIG.PROFILE.getRootElement().getChild("brig_settings").getAttributeValue("blastLocation");
                        }
                    }
                    if (temp.getRootElement().getAttributeValue("archive") != null) {
                        temp = BRIG.FormatArchive(temp, fc.getSelectedFile().toString() );
                    }
                    BRIG.PROFILE = temp;
                    BRIG.PROFILE_LOCATION = fc.getSelectedFile().toString();
                    if (bl != null) {
                        if (BRIG.PROFILE.getRootElement().getChild("brig_settings") != null) {
                            BRIG.PROFILE.getRootElement().getChild("brig_settings").setAttribute("blastLocation", bl);
                        }
                    }
                    reload();
                } catch (JDOMException e) {
                    JOptionPane.showMessageDialog(this,
                            fc.getSelectedFile().toString() + " is corrupt because :\n" + e.getMessage(),
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(this,
                            "Could not read " + fc.getSelectedFile().toString() + " because :\n" + e.getMessage(),
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this,
                        "This is not a valid save file " + e.getMessage(),
                        "ERROR!",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
}//GEN-LAST:event_OpenMenuActionPerformed

    private void SaveMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveMenuActionPerformed
        save();
        BRIG.PROFILE.getRootElement().removeAttribute("archive");
        final JFileChooser fc = new JFileChooser();
        fc.showSaveDialog(this);
        if (fc.getSelectedFile() != null) {
            try {
                int j = BRIG.saveXML(fc.getSelectedFile().toString(), BRIG.PROFILE);
                if (j == 0) {
                    JOptionPane.showMessageDialog(this,
                            "Saved!",
                            "Saved!",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_SaveMenuActionPerformed

    private void QuitMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QuitMenuActionPerformed
        this.dispose();
}//GEN-LAST:event_QuitMenuActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        try{
        if (BRIG.isBlastOk()) {
             new Graph().setVisible(true);
        } else {
            JOptionPane.showMessageDialog(this,
                    "Could not run BLAST, please check it is installed and BRIG's BLAST location is correct",
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
        }
        }catch(Exception e ){
            e.printStackTrace();
            JOptionPane.showMessageDialog(this,
                    "Could not run BLAST, please check it is installed and BRIG's BLAST location is correct",
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        new CGHeader().setVisible(true);
}//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
        new Options().setVisible(true);
}//GEN-LAST:event_jMenuItem6ActionPerformed

    private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed
        new About().setVisible(true);
}//GEN-LAST:event_jMenuItem7ActionPerformed

    private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem8ActionPerformed
        final JFileChooser fc = new JFileChooser();
        fc.showSaveDialog(this);
        if (fc.getSelectedFile() != null) {
            try {
                Document newProfile = BRIG.prepProfile(BRIG.PROFILE);
                int j = BRIG.saveXML(fc.getSelectedFile().toString(), newProfile);
                if (j == 0) {
                    JOptionPane.showMessageDialog(this,
                            "Saved!",
                            "Saved!",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_jMenuItem8ActionPerformed

    private void selectedColourBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_selectedColourBoxMouseClicked

        selected = JColorChooser.showDialog(this, "Choose Colour", selected);
        save();
        reload();
    }//GEN-LAST:event_selectedColourBoxMouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (!poolList.isSelectionEmpty()) {
            Object[] add = poolList.getSelectedValues();
            Element root = BRIG.PROFILE.getRootElement();
            List doop = root.getChildren("ring");
            Element currentRing = (Element) doop.get(BRIG.POSITION);
                for (int z = 0; z < doop.size(); z++) {
                    if (((Element) doop.get(z)).getAttributeValue("position").compareTo(Integer.toString(BRIG.POSITION)) == 0) {
                        currentRing = (Element) doop.get(z);
                    }
                }
            List seq = currentRing.getChildren();
            boolean cuContent = false;
            boolean cuGraph = false;
            boolean cuYes = false;
            for (int j=0; j<seq.size();j++){
                String cu = ((Element)seq.get(j)).getAttributeValue("location");
                if (cu != null) {
                    if (cu.compareTo("GC Content") == 0 || cu.compareTo("GC Skew") == 0) {
                        cuContent = true;
                    } else if (cu.endsWith(".graph")) {
                        cuGraph = true;
                    } else {
                        cuYes = true;
                    }
                }
            }
            boolean content = false;
            boolean skew = false;
            boolean graph = false;
            boolean yes = false;
            for (int i = 0; i < add.length; i++) {
                if (add[i].toString().compareTo("GC Content") == 0) {
                    content = true;
                } else if (add[i].toString().compareTo("GC Skew") == 0) {
                    skew = true;
                } else if (add[i].toString().endsWith(".graph")) {
                    graph = true;
                } else {
                    yes = true;
                }
            }
            if ( (content && skew) || ( (content || skew) && cuContent) ) {
                JOptionPane.showMessageDialog(this,
                        "You can't mix GC Skew and Content",
                        "ERROR!",
                        JOptionPane.ERROR_MESSAGE);
            } else if ( (!((content || skew) ^ (graph || yes)) ) ||
                     ((content||skew ) && (cuContent || cuGraph || cuYes))   ) {
                JOptionPane.showMessageDialog(this,
                        "You can't mix GC graphs with other data",
                        "ERROR!",
                        JOptionPane.ERROR_MESSAGE);
            } else if ( (graph && yes) || (yes && cuGraph) || (graph && cuYes)) {
                JOptionPane.showMessageDialog(this,
                        "You can't mix graphs with sequences",
                        "ERROR!",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                for (int i = 0; i < add.length; i++) {
                    Element child = new Element("sequence");
                    child.setAttribute("location", add[i].toString());
                    currentRing.addContent(child);
                }
                save();
                reload();
        }
        }    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        List doop = BRIG.PROFILE.getRootElement().getChildren("ring");
        Element currentRing = (Element) doop.get(BRIG.POSITION);
        for (int z = 0; z < doop.size(); z++) {
            if (((Element) doop.get(z)).getAttributeValue("position").compareTo(Integer.toString(BRIG.POSITION)) == 0) {
                currentRing = (Element) doop.get(z);
            }
        }
        int[] del = genomeList.getSelectedIndices();
        for (int i = 0; i < del.length; i++) {           
            List temp = currentRing.getChildren("sequence");
            ((Element)temp.get(del[i])).detach();
            for (int j = 0; j < del.length; j++) {
                if ( j > i) {
                    del[j]--;
                }
            }
        }
        save();
        reload();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void InsertRingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InsertRingActionPerformed
        save();
        int sel  = ringu.getSelectedIndex();
        Element newChild = new Element("ring");
        List doop = BRIG.PROFILE.getRootElement().getChildren("ring");
        // Shift all rings down one, to make room for new ring
        for (int i = 0; i < doop.size(); i++) {
            Element ccur = (Element) doop.get(i);
            int nextInt = Integer.parseInt(ccur.getAttributeValue("position"));
            if (nextInt > sel ) {
                nextInt++;
                ccur.setAttribute("position", Integer.toString(nextInt));
            }
        }
        Color newcol = BRIG.FetchColor(sel + 1);
        String col = newcol.getRed() + "," + newcol.getGreen() + "," + newcol.getBlue();
        newChild.setAttribute("colour", col);
        newChild.setAttribute("name", "null");
        newChild.setAttribute("position", Integer.toString(sel + 1));
        BRIG.PROFILE.getRootElement().addContent(newChild);
        if (BRIG.POSITION > sel) {
            BRIG.POSITION++;
        }

        reload();
    }//GEN-LAST:event_InsertRingActionPerformed

    private void currentRingFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_currentRingFieldKeyTyped
        ringModel.set(got, "Ring " + currentRingField.getText());
    }//GEN-LAST:event_currentRingFieldKeyTyped

    private void currentRingFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_currentRingFieldKeyReleased
        ringModel.set(got, "Ring " + currentRingField.getText());
    }//GEN-LAST:event_currentRingFieldKeyReleased

    private void changeGenbankActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeGenbankActionPerformed
        fixFileType();
        reload();
    }//GEN-LAST:event_changeGenbankActionPerformed

    private void bundleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bundleActionPerformed
      final JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int status = fc.showOpenDialog(this);
        if (fc.getSelectedFile() != null && status != JFileChooser.CANCEL_OPTION) {
            try {
            Thread execute = new Thread() {
                @Override
                public void run() {
                    try {
                        BRIG.bundleSession(fc.getSelectedFile().getAbsolutePath());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                };
                if (fc.getSelectedFile().isDirectory()) {
                    execute.start();
                } else {
                    JOptionPane.showMessageDialog(this,
                           fc.getSelectedFile().getName() + " is not a valid directory",
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_bundleActionPerformed

    public void checkMultiFasta(){
                String queryFile = BRIG.PROFILE.getRootElement().getAttributeValue("queryFile");
        if (BRIG.isEmbl(queryFile) || BRIG.isGenbank(queryFile)) {
            if (BRIG.PROFILE.getRootElement().getAttribute("genbankProtein") != null) {
                multiFasta = true;
                genbankType.setSelectedIndex(1);
            } else {
                multiFasta = false;
                BRIG.PROFILE.getRootElement().removeAttribute("spacer");
                  genbankType.setSelectedIndex(0);
            }
        } else {
            try {
                if (BRIG.isMultiFasta(queryFile) <= 1) {
                    multiFasta = false;
                    BRIG.PROFILE.getRootElement().removeAttribute("spacer");
                } else {
                    multiFasta = true;
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this,
                        "Could not open " + queryFile + " because:\n" + e.getMessage(),
                        "ERROR!",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    public void fixFileType(){
       String queryFile = BRIG.PROFILE.getRootElement().getAttributeValue("queryFile");
       blastType.removeAllItems();
       if (BRIG.isEmbl(queryFile) || BRIG.isGenbank(queryFile)) {
           jLabel11.setVisible(true);
           genbankType.setVisible(true);
           changeGenbank.setVisible(true);
           if (genbankType.getSelectedIndex() == 0) {
               BRIG.PROFILE.getRootElement().removeAttribute("genbankProtein");
               multiFasta = false;
           } else {
               BRIG.PROFILE.getRootElement().setAttribute("genbankProtein", "true");
               multiFasta = true;
           }
           List bad = new LinkedList();
           if (BRIG.PROFILE.getRootElement().getAttribute("genbankProtein") != null) {
               blastType.addItem("blastp");
               blastType.addItem("blastx");
               bad.add("blastn");
               bad.add("tblastn");
               bad.add("tblastx");      
           } else {
               blastType.addItem("blastn");
               blastType.addItem("tblastn");
               blastType.addItem("tblastx");
               bad.add("blastp");
               bad.add("blastx");
           }
           // CHECK IF BLAST SETTINGS FOR EACH RING IS OK.
           List doop = BRIG.PROFILE.getRootElement().getChildren("ring");
           List no = new LinkedList();
           for (int i = 0; i < doop.size(); i++) {
               Element ring = (Element) doop.get(i);
               if (ring.getAttributeValue("blastType") != null) {
                   String type = ring.getAttributeValue("blastType");
                   for (int j = 0; j < bad.size(); j++) {
                       if (type.compareTo(bad.get(j).toString()) == 0) {
                          no.add(i);
                       }
                   }
               }
           }
           if(no.size() > 0 ){
                Genbank oh = new Genbank(this,true);
                oh.setVisible(true);
                String type = oh.type;
                oh.dispose();
                for(int i = 0 ; i<no.size();i++){
                    Element dor = (Element)doop.get( (Integer)no.get(i)  );
                    dor.setAttribute("blastType", type);
                }
           }
        } else {
            jLabel11.setVisible(false);
            genbankType.setVisible(false);
            changeGenbank.setVisible(false);
            blastType.addItem("blastn");
            blastType.addItem("blastp");
            blastType.addItem("blastx");
            blastType.addItem("tblastn");
            blastType.addItem("tblastx");
        }
    }
    public void FixRingNumber() {
        List doop = BRIG.PROFILE.getRootElement().getChildren("ring");
        List<Integer> used = new LinkedList<Integer>();
        for (int i = 0; i < doop.size(); i++) {
            Element ring = (Element) doop.get(i);
            if (ring.getAttributeValue("position") != null) {
                used.add(Integer.parseInt(ring.getAttributeValue("position")));
            }
        }
        for (int i = 0; i < doop.size(); i++) {
            Element ring = (Element) doop.get(i);
            if (ring.getAttributeValue("position") == null) {
                int position = 0;
                boolean blank = true;
                while (blank) {
                    if (!used.contains(position)) {
                        ring.setAttribute("position", Integer.toString(position));
                        used.add(position);
                        blank = false;
                    }
                    position++;
                }
            }
        }
    }

    public void save() {       
        Element root = BRIG.PROFILE.getRootElement();
        List doop = BRIG.PROFILE.getRootElement().getChildren("ring");
        Element currentRing = (Element) doop.get(BRIG.POSITION);
        for (int z = 0; z < doop.size(); z++) {
            if (((Element) doop.get(z)).getAttributeValue("position").compareTo(Integer.toString(BRIG.POSITION)) == 0) {
                currentRing = (Element) doop.get(z);
            }
        }
        try {
            currentRing.setAttribute("upperInt", upperInt.getText());
            currentRing.setAttribute("lowerInt", lowerInt.getText());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,
                    "Identity values are not Integers!",
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
        }
        if (legendCheck.isSelected()) {
            currentRing.setAttribute("legend", "yes");
        }
        if (!legendCheck.isSelected()) {
            currentRing.setAttribute("legend", "no");
        }

        if (selected != null) {
            currentRing.setAttribute("colour", selected.getRed() + "," + selected.getGreen() + "," + selected.getBlue());
        }
        try{
            Integer.parseInt(Size.getText() );
            currentRing.setAttribute("size", Size.getText() ) ;
        }catch(Exception e) {
            e.printStackTrace();
        }
        String le = currentRingField.getText();
        le = le.replaceFirst("\\d+:", "");
        currentRing.setAttribute("name", le.trim());

        if (labelCheckBox.isSelected()) {
            currentRing.setAttribute("labels", "yes");
        } else {
            currentRing.setAttribute("labels", "no");
        }
  /*     if (interCheck.isSelected()) {
            root.setAttribute("interactive", "yes");
        }
        if (!interCheck.isSelected()) {
            root.setAttribute("interactive", "no");
        }*/
        try {
            Integer.parseInt( graphMaxField.getText()  );
            currentRing.setAttribute("custom_graph", graphMaxField.getText());
        }catch(Exception e){
             currentRing.removeAttribute("custom_graph");
        }
        try {
            Integer.parseInt( spacerField.getText()  );
            root.setAttribute("spacer", spacerField.getText());
        }catch(Exception e){
             root.setAttribute("spacer","0");
        }
        currentRing.setAttribute("blastType", blastType.getSelectedItem().toString());
          checkMultiFasta();
       
    }

    public void mute(boolean status) {
        upperInt.setEnabled(status);
        lowerInt.setEnabled(status);
        legendCheck.setEnabled(status);
        labelCheckBox.setEnabled(status);
    }

    public void reload() {
        BRIG.Print("Position: \t" + BRIG.POSITION);
        Element root = BRIG.PROFILE.getRootElement();
        queryField.setText(root.getAttributeValue("queryFile"));
        List doop = BRIG.PROFILE.getRootElement().getChildren("ring");
        Element setting = BRIG.PROFILE.getRootElement().getChild("cgview_settings");
        String notch = setting.getAttributeValue("featureThickness");
        Size.setText(notch);
        if (doop.size() < 1) {
            Element newChild = new Element("ring");
            newChild.setAttribute("position", Integer.toString(0));
            Color newcol = BRIG.FetchColor(1);
            String col = newcol.getRed() + "," + newcol.getGreen() + "," + newcol.getBlue();
            newChild.setAttribute("colour", col);
            newChild.setAttribute("name", "null");
            root.addContent(newChild);
        }
        doop = root.getChildren("ring");
        Element currentRing = (Element) doop.get(BRIG.POSITION);
        for (int z = 0; z < doop.size(); z++) {
            if (((Element) doop.get(z)).getAttributeValue("position").compareTo(Integer.toString(BRIG.POSITION)) == 0) {
                currentRing = (Element) doop.get(z);
            }
        }
        if(currentRing.getAttributeValue("size") != null ){
            Size.setText(currentRing.getAttributeValue("size"));
        }
        currentRingField.setText( ( Integer.parseInt( currentRing.getAttributeValue("position") ) +1  )
                + ": " + currentRing.getAttributeValue("name"));
        if (currentRing.getAttributeValue("upperInt") != null) {
            upperInt.setText(currentRing.getAttributeValue("upperInt"));
        } else if (BRIG.PROFILE.getRootElement().getChild("brig_settings") != null) {
            if (BRIG.PROFILE.getRootElement().getChild("brig_settings").getAttributeValue("defaultUpper") != null) {
                upperInt.setText(BRIG.PROFILE.getRootElement().getChild("brig_settings").getAttributeValue("defaultUpper"));
            } else {
                upperInt.setText("70");
            }
        }
        if (root.getChild("brig_settings") != null && root.getAttributeValue("spacer") == null) {
            Element settings = BRIG.PROFILE.getRootElement().getChild("brig_settings");
            if (settings.getAttributeValue("defaultSpacer") != null) {
                spacerField.setText(settings.getAttributeValue("defaultSpacer"));
            }
        }
        if (root.getAttributeValue("spacer") != null) {
                spacerField.setText(BRIG.PROFILE.getRootElement().getAttributeValue("spacer"));
        }
        if (currentRing.getAttributeValue("lowerInt") != null) {
            lowerInt.setText(currentRing.getAttributeValue("lowerInt"));
        } else if (BRIG.PROFILE.getRootElement().getChild("brig_settings") != null) {
            if (BRIG.PROFILE.getRootElement().getChild("brig_settings").getAttributeValue("defaultLower") != null) {
                lowerInt.setText(BRIG.PROFILE.getRootElement().getChild("brig_settings").getAttributeValue("defaultLower"));
            } else {
                lowerInt.setText("50");
            }
        }
        genomeModel.removeAllElements();
        List genomes = currentRing.getChildren("sequence");
        jButton1.setEnabled(true);
        for (int k = 0; k < genomes.size(); k++) {
            String lo = ((Element) genomes.get(k)).getAttributeValue("location");
            if(lo.compareTo("GC Skew") == 0 ||
                  lo.compareTo("GC Content") == 0 ){
                jButton1.setEnabled(false);

            }
            genomeModel.addElement(lo);
        }
        genomeList.setModel(genomeModel);
        List seq = currentRing.getChildren("sequence");
        if (seq.size() > 0) {
            String lastFile = ((Element) seq.get(seq.size()-1)).getAttributeValue("location") ;
            if (lastFile.endsWith(".graph")) {
                legendCheck.setText("Show red and blue?");
                graphMax.setVisible(true);
                graphMaxField.setVisible(true);
                if ( currentRing.getAttributeValue("custom_graph") != null){
                    graphMaxField.setText( currentRing.getAttributeValue("custom_graph") );
                }else{
                    graphMaxField.setText("Default");
                }
            } else {
                legendCheck.setText("Show thresholds in legend?");
                graphMax.setVisible(false);
                graphMaxField.setVisible(false);
            }
            if (lastFile.compareTo("GC Skew") == 0 || lastFile.compareTo("GC Content") == 0) {
                mute(false);
            } else {
                mute(true);
            }
        } else {
            mute(true);
            legendCheck.setText("Show thresholds in legend?");
            graphMax.setVisible(false);
            graphMaxField.setVisible(false);
        }
        poolList.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        if (currentRing.getAttribute("legend") != null) {
            if (currentRing.getAttributeValue("legend").compareTo("yes") == 0) {
                legendCheck.setSelected(true);
            } else {
                legendCheck.setSelected(false);
            }
        }
        if (currentRing.getAttribute("labels") != null) {
            if (currentRing.getAttributeValue("labels").compareTo("yes") == 0) {
                labelCheckBox.setSelected(true);
            } else {
                labelCheckBox.setSelected(false);
            }
        }
        if (currentRing.getAttributeValue("colour") != null) {
            String[] doopArray = currentRing.getAttributeValue("colour").split(",");
            selected = new Color(Integer.parseInt(doopArray[0]), Integer.parseInt(doopArray[1]), Integer.parseInt(doopArray[2]));
            selectedColourBox.setBackground(selected);
        }
        String out = "";
        List files = currentRing.getChildren("sequence");
        for (int i = 0; i < files.size(); i++) {
            Element temp = (Element) files.get(i);
            out = out + BRIG.FetchFilename(temp.getAttributeValue("location")) + "\n";
        }

/*        if (root.getAttribute("interactive") != null) {
           if (root.getAttributeValue("interactive").compareTo("yes") == 0) {
                interCheck.setSelected(true);
            } else {
                interCheck.setSelected(false);
            }
        } else {
            interCheck.setSelected(false);
        }*/
        ringModel.removeAllElements();
        List rings = BRIG.PROFILE.getRootElement().getChildren("ring");
        int pos = 0;
        int stop = 1;
        if (currentRing.getAttributeValue("blastType") != null) {
            for(int g=0; g< blastType.getItemCount(); g++){
                if(blastType.getItemAt(g).toString().compareTo(currentRing.getAttributeValue("blastType")) == 0 ){
                    blastType.setSelectedIndex(g);
                }
            }
            blastType.setSelectedItem(currentRing.getAttributeValue("blastType"));
        }
        while(stop != 0){
            stop =0;
            for (int k = 0; k < rings.size(); k++) {
                currentRing = (Element) rings.get(k);
                if( Integer.parseInt( currentRing.getAttributeValue("position") ) == pos ){
                    ringModel.addElement("Ring " +
                    Integer.toString( Integer.parseInt( currentRing.getAttributeValue("position") ) +1)
                    + ": " + currentRing.getAttributeValue("name"));
                    stop++;
                    pos++;
                }
            }
        }
        if(multiFasta){
                spacerField.setVisible(true);
                jLabel10.setVisible(true);
        }else{
                spacerField.setVisible(false);
                jLabel10.setVisible(false);
                BRIG.PROFILE.getRootElement().removeAttribute("spacer");
        }
        charman();
        BRIG.dumpXML("errorlog.xml",BRIG.PROFILE);
        if ( parent != null){
         parent.reload();
        }
    }

    private void charman(){
        List doop = BRIG.PROFILE.getRootElement().getChildren("ring");
        Element currentRing = (Element) doop.get(BRIG.POSITION);
        for (int z = 0; z < doop.size(); z++) {
            if (((Element) doop.get(z)).getAttributeValue("position").compareTo(Integer.toString(BRIG.POSITION)) == 0) {
                currentRing = (Element) doop.get(z);
            }
        }
        got = ringModel.indexOf("Ring " +
                    Integer.toString( Integer.parseInt( currentRing.getAttributeValue("position") ) +1)
                    + ": " + currentRing.getAttributeValue("name") );
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Two().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu File;
    private javax.swing.JButton InsertRing;
    private javax.swing.JMenuItem OpenMenu;
    private javax.swing.JMenuItem QuitMenu;
    private javax.swing.JMenuItem SaveMenu;
    private javax.swing.JTextField Size;
    private javax.swing.JComboBox blastType;
    private javax.swing.JMenuItem bundle;
    private javax.swing.JButton changeGenbank;
    private javax.swing.JTextField currentRingField;
    private javax.swing.JComboBox genbankType;
    private javax.swing.JList genomeList;
    private javax.swing.JLabel graphMax;
    private javax.swing.JTextField graphMaxField;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    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.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JCheckBox labelCheckBox;
    private javax.swing.JCheckBox legendCheck;
    private javax.swing.JTextField lowerInt;
    private javax.swing.JButton newRingButton;
    private javax.swing.JList poolList;
    private javax.swing.JTextField queryField;
    private javax.swing.JButton removeRingButton;
    private javax.swing.JList ringu;
    private javax.swing.JPanel selectedColourBox;
    private javax.swing.JTextField spacerField;
    private javax.swing.JTextField upperInt;
    // End of variables declaration//GEN-END:variables
}

class ReorderListener extends MouseAdapter {

    private JList list;
    private int pressIndex = 0;
    private int releaseIndex = 0;
    private Two parent;
    public ReorderListener(JList list, Two parents) {
        if (!(list.getModel() instanceof DefaultListModel)) {
            throw new IllegalArgumentException("List must have a DefaultListModel");
        }
        this.list = list;
        parent = parents;
    }

    @Override
    public void mousePressed(MouseEvent e) {
        pressIndex = list.locationToIndex(e.getPoint());
        parent.save();
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        releaseIndex = list.locationToIndex(e.getPoint());
        if (releaseIndex != pressIndex && releaseIndex != -1) {
            reorder();
        }
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        mouseReleased(e);
        pressIndex = releaseIndex;
    }


    private void reorder() {
        List doop = BRIG.PROFILE.getRootElement().getChildren("ring");
        int fix = BRIG.POSITION ;
        Element move = new Element("blanko");
        for (int z = 0; z < doop.size(); z++) {
            Element ccur = (Element) doop.get(z);
            int nextInt = Integer.parseInt(ccur.getAttributeValue("position"));
            if(nextInt == pressIndex ){
                move = ccur;
            }
        }
        for (int z = 0; z < doop.size(); z++) {
            Element ccur = (Element) doop.get(z);
            int nextInt = Integer.parseInt(ccur.getAttributeValue("position"));
            if (pressIndex > releaseIndex) {
                if (nextInt < pressIndex && nextInt >= releaseIndex) {
                    ccur.setAttribute("position", Integer.toString(nextInt + 1));
                    if(nextInt == BRIG.POSITION){
                        BRIG.POSITION++;
                    }
                }
            } else if (pressIndex < releaseIndex) {
                if (nextInt > pressIndex && nextInt <= releaseIndex) {
                    ccur.setAttribute("position", Integer.toString(nextInt - 1));
                    if (nextInt == BRIG.POSITION) {
                        BRIG.POSITION--;
                    }
                }
            }
        }
        move.setAttribute("position", Integer.toString(releaseIndex));
        if (fix == pressIndex) {
            BRIG.POSITION = releaseIndex;
        }
        parent.reload();
        BRIG.Print("HELP \t"+ BRIG.POSITION);
    }


}
