/* 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 java.awt.Color;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.jdom.Element;

/**
 *
 * @author Nabil
 */
public class Graph extends javax.swing.JFrame {
  
    One got = null;
    /** Creates new form Graph */
    public Graph() {
        initComponents();
        reload();
    }
    public Graph(One thisgot) {
        initComponents();
        got = thisgot;
      
        if(BRIG.PROFILE.getRootElement().getAttributeValue("queryFile") != null ){
         File query = new File(BRIG.PROFILE.getRootElement().getAttributeValue("queryFile"));
         if(query.exists()){
             queryField.setText( query.getAbsolutePath());
         }
        }
          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() {

        jSeparator1 = new javax.swing.JSeparator();
        queryBrowseButton = new javax.swing.JButton();
        queryField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        sequenceAddField = new javax.swing.JTextField();
        refBrowseButton = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        blastOptionField = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        outputFolderField = new javax.swing.JTextField();
        outputBrowseButton = new javax.swing.JButton();
        submit = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        outputArea = new javax.swing.JTextArea();
        seqField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        seqBrowseButton = new javax.swing.JButton();
        windowSize = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Create custom graph");

        queryBrowseButton.setText("Browse");
        queryBrowseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                queryBrowseButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("Reference sequence:");

        jLabel2.setText("Query sequence:");

        refBrowseButton.setText("Browse");
        refBrowseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refBrowseButtonActionPerformed(evt);
            }
        });

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

        blastOptionField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                blastOptionFieldActionPerformed(evt);
            }
        });

        jLabel5.setText("BLAST options:");

        jLabel4.setText("Output folder:");

        outputBrowseButton.setText("Browse");
        outputBrowseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                outputBrowseButtonActionPerformed(evt);
            }
        });

        submit.setText("Create Graph");
        submit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitActionPerformed(evt);
            }
        });

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Contig mapping", "Coverage graph", "Convert graph" }));
        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });

        outputArea.setColumns(20);
        outputArea.setRows(5);
        jScrollPane1.setViewportView(outputArea);

        jLabel3.setText("Graph file:");

        seqBrowseButton.setText("Browse");
        seqBrowseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                seqBrowseButtonActionPerformed(evt);
            }
        });

        jLabel6.setText("Window size:");

        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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(queryField, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(queryBrowseButton))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(sequenceAddField, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(refBrowseButton)))
                        .addContainerGap())
                    .addComponent(jLabel5)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(seqField, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                                .addGap(6, 6, 6)
                                .addComponent(seqBrowseButton))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(outputFolderField, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(outputBrowseButton))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(windowSize, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 334, Short.MAX_VALUE)
                                .addComponent(submit)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1)
                                .addGap(8, 8, 8)))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addContainerGap(564, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addContainerGap(604, Short.MAX_VALUE))
                    .addComponent(jLabel4)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(blastOptionField, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE)
                        .addGap(83, 83, 83))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 651, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(queryField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(queryBrowseButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sequenceAddField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(refBrowseButton))
                .addGap(6, 6, 6)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(seqField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(seqBrowseButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(blastOptionField, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12)
                .addComponent(jLabel4)
                .addGap(2, 2, 2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(outputFolderField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(outputBrowseButton))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(submit)
                        .addComponent(jButton1))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel6)
                        .addComponent(windowSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

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

    private void queryBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_queryBrowseButtonActionPerformed
        JFileChooser fc = new JFileChooser();
        File text = new File(queryField.getText());
        if (text.exists()) {
            if (text.getParentFile().isDirectory()) {
                fc = new JFileChooser(text.getParent());
            }
        }
        fc.showOpenDialog(this);
        if (fc.getSelectedFile() != null) {
            queryField.setText(fc.getSelectedFile().getAbsolutePath());
        }
}//GEN-LAST:event_queryBrowseButtonActionPerformed

    private void refBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refBrowseButtonActionPerformed
        JFileChooser fc = new JFileChooser();
        File text = new File(sequenceAddField.getText());
        if (text.exists()) {
            if (text.getParentFile().isDirectory()) {
                fc = new JFileChooser(text.getParent());
            }
        }else{
            text = new File(queryField.getText());
            if(text.exists() ){
            if (text.getParentFile().isDirectory()) {
                fc = new JFileChooser(text.getParent());
            }
            }
        }
        fc.showOpenDialog(this);
        if (fc.getSelectedFile() != null) {
            sequenceAddField.setText(fc.getSelectedFile().getAbsolutePath());
        }
}//GEN-LAST:event_refBrowseButtonActionPerformed

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

    private void outputBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_outputBrowseButtonActionPerformed
        JFileChooser fc = new JFileChooser();
        File text = new File(outputFolderField.getText());
        if (text.exists()) {
            if (text.getParentFile().isDirectory()) {
                fc = new JFileChooser(text.getParent());
            }
        }else{
            text = new File(queryField.getText());
            if(text.exists()){
            if (text.getParentFile().isDirectory()) {
                fc = new JFileChooser(text.getParent());
            }
            }
        }
        fc.setFileSelectionMode(fc.DIRECTORIES_ONLY);
        fc.showOpenDialog(this);       
        if (fc.getSelectedFile() != null) {
            outputFolderField.setText(fc.getSelectedFile().getAbsolutePath());
        }
}//GEN-LAST:event_outputBrowseButtonActionPerformed

    private void submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitActionPerformed
        submit.setVisible(false);
        Thread execute = new Thread() {
            @Override
            public void run() {
                try {
                    compute();
                    if (got != null) {
                       /* if (Main.PROFILE.getRootElement().getAttributeValue("queryFile") != null) {
                        String query = Main.PROFILE.getRootElement().getAttributeValue("queryFile");
                        if (query.compareTo("") == 0) {
                            Main.PROFILE.getRootElement().setAttribute("queryFile", queryField.getText());
                        }
                        }else{
                             Main.PROFILE.getRootElement().setAttribute("queryFile", queryField.getText());
                        }*/
                        got.reload();
                    }
                } catch (Exception e) {
                }
            }
        };
        execute.start();
        submit.setVisible(true);
    }//GEN-LAST:event_submitActionPerformed

    private void compute() throws InterruptedException {
        if (jComboBox1.getSelectedItem().toString().compareTo("Coverage graph") == 0) {
            updateProgress("Parsing assembly file...");
            try {
                if(sequenceAddField.getText().endsWith(".sam") ){
                    try{
                        int d = Integer.parseInt(windowSize.getText());
                     addFile(SamcontigCoverage(sequenceAddField.getText(), outputFolderField.getText(),BRIG.FetchFilename(sequenceAddField.getText()),  d) );
                    }catch(NumberFormatException e){
                                            JOptionPane.showMessageDialog(this,
                            "Window size is not a number",
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                    }
                }else if( sequenceAddField.getText().endsWith(".ace")  ) {
                    try{
                        int d = Integer.parseInt(windowSize.getText());
                    addFile(contigCoverage(sequenceAddField.getText(), outputFolderField.getText(),d));
                    }catch(Exception e){
                                            JOptionPane.showMessageDialog(this,
                            "Window size is not a number",
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(this,
                            "Only .sam or .ace files supported",
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                updateProgress(e.getMessage());
            }
        } else if (jComboBox1.getSelectedItem().toString().compareTo("Convert graph") == 0) {
            updateProgress("Converting graph file...");
            try {
                try {
                    int d = Integer.parseInt(windowSize.getText());
                    String ch = checkGraph();
                    if(ch == null){
                    addFile(convertGraph());
                    }else{
                    JOptionPane.showMessageDialog(this,
                            ch,
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                    }
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this,
                            "Window size is not a number",
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                updateProgress(e.getMessage());
            }
        } else if (jComboBox1.getSelectedItem().toString().compareTo("Reorder ace") == 0) {
            updateProgress("Reordering ace file...");
            try {
                reorderGraph();

            } catch (Exception e) {
                updateProgress(e.getMessage());
            }
        } else {
            try {
                int div  = 1000;                
                String dooo = "";
                String ou = "";
                updateProgress("Parsing ace file...");
                Vector initRing = new Vector();
                initRing.add("");
                initRing.add(Color.white);
                initRing.add(0);
                initRing.add(sequenceAddField.getText());
                Vector graph = new Vector();
                graph.add(initRing);
                int  multiFasta =  BRIG.isMultiFasta(queryField.getText());
                File get  = new File(queryField.getText());
                int len = BRIG.FastaLength(get.getAbsolutePath(), false);
                if(len < 100000 ){
                    div =10;
                }
                //TODO: Add genbank file support
                new File(outputFolderField.getText() + BRIG.SL + "scratch").mkdir();
                if (sequenceAddField.getText().endsWith(".ace")) {
                    updateProgress("Converting ace file to multi-FASTA");
                    graph = aceParse(graph);
                }
                if (multiFasta > 1) {
                    updateProgress("Formating Multi-FASTA reference file...");
                    BRIG.formatMultiFASTA(get.getAbsolutePath(),  outputFolderField.getText() + BRIG.SL +"Spaced"+ get.getName() , 0, false);
                    updateProgress("Running BLAST...");
                    updateProgress(GraphFunctions.RunGraphBlast(outputFolderField.getText() + BRIG.SL +"Spaced"+ get.getName(), graph, outputFolderField.getText(), blastOptionField.getText(), null));
                }else{
                    updateProgress("Running BLAST...");
                    updateProgress(GraphFunctions.RunGraphBlast(queryField.getText(), graph, outputFolderField.getText(), blastOptionField.getText(), null));
                }
                int length = 0;
                try {
                    length = BRIG.FastaLength(queryField.getText(), false);
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this,
                            "Could not open query file",
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
                int[] ia = new int[(length / div) + 2];
                int[] repeats = new int[(length / div) + 2];
                for (int i = 0; i < ia.length; i++) {
                    ia[i] = 0;
                    repeats[i] = 0;
                }
                for (int j = 0; j < graph.size(); j++) {
                    Vector currentRing = (Vector) graph.get(j);
                    for (int k = 3; k < currentRing.size(); k++) {
                        String db = currentRing.get(k).toString();
                        if (System.getProperty("os.name").toLowerCase().indexOf("windows") == -1) {
                            db = db.replaceAll(BRIG.SL + BRIG.SL, BRIG.SL);
                        }
                        ou = outputFolderField.getText() + BRIG.SL + "scratch" + BRIG.SL + BRIG.FetchFilename(queryField.getText()) + "Vs" + BRIG.FetchFilename(db) + ".tab ";
                        dooo = outputFolderField.getText()
                                + BRIG.SL + BRIG.FetchFilename(queryField.getText()) + "Vs" + BRIG.FetchFilename(db) + ".graph";
                        if (multiFasta > 1) {
                        ou = outputFolderField.getText() + BRIG.SL + "scratch" + BRIG.SL + "Spaced" + get.getName() + "Vs" + BRIG.FetchFilename(db) + ".tab ";
                        dooo = outputFolderField.getText()
                                + BRIG.SL + get.getName() + "Vs" + BRIG.FetchFilename(db) + ".graph";
                            updateProgress(GraphFunctions.parseBlast2Graph(ia, repeats, ou, dooo, true, div,len));
                        } else {
                            updateProgress(GraphFunctions.parseBlast2Graph(ia, repeats, ou, dooo, false, div,len));
                        }
                        addFile(dooo);
                        addFile(dooo+"rep.graph");
                    }
                }
                updateProgress("Done.");

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void seqBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_seqBrowseButtonActionPerformed
        JFileChooser fc = new JFileChooser();
        File text = new File(seqField.getText());
        if (text.exists()) {
            if (text.getParentFile().isDirectory()) {
                fc = new JFileChooser(text.getParent());
            }
        } else {
            text = new File(queryField.getText());
            if(text.exists()){
            if (text.getParentFile().isDirectory()) {
                fc = new JFileChooser(text.getParent());
            }
            }
        }
        fc.showOpenDialog(this);

        if (fc.getSelectedFile() != null) {
            seqField.setText(fc.getSelectedFile().getAbsolutePath());
        }
    }//GEN-LAST:event_seqBrowseButtonActionPerformed

    private void blastOptionFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_blastOptionFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_blastOptionFieldActionPerformed

    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged
    reload();
    }//GEN-LAST:event_jComboBox1ItemStateChanged


        public void reload(){
        if (jComboBox1.getSelectedItem().toString().compareTo("Coverage graph") == 0) {
            queryField.setText("");
            sequenceAddField.setText("");
            queryField.setVisible(false);
            queryBrowseButton.setVisible(false);
            blastOptionField.setVisible(false);
            seqField.setVisible(false);
            seqBrowseButton.setVisible(false);
            jLabel2.setText("Assembly file (.ace or .sam only)");
            jLabel1.setVisible(false);
            jLabel3.setVisible(false);
            jLabel5.setVisible(false);
            jLabel6.setVisible(true);
            windowSize.setVisible(true);
        } else if(jComboBox1.getSelectedItem().toString().compareTo("Contig mapping") == 0){
             jLabel6.setVisible(false);
            windowSize.setVisible(false);
            queryField.setText("");
            sequenceAddField.setText("");
            queryField.setVisible(true);
            queryBrowseButton.setVisible(true);
            blastOptionField.setVisible(true);
            seqField.setVisible(false);
            seqBrowseButton.setVisible(false);
            jLabel1.setText("Reference sequence");
            jLabel2.setText("Query sequence");
            jLabel1.setVisible(true);
            jLabel3.setVisible(false);
            jLabel5.setVisible(true);
        } else if (jComboBox1.getSelectedItem().toString().compareTo("Convert graph") == 0) {
            jLabel6.setVisible(true);
            windowSize.setVisible(true);
            //queryField.setText("");
            sequenceAddField.setText("");
            queryField.setVisible(true);
            queryBrowseButton.setVisible(true);
            seqField.setVisible(true);
            seqBrowseButton.setVisible(true);
            blastOptionField.setVisible(true);
            jLabel1.setText("Original sequence");
            jLabel2.setText("New sequence");
            jLabel1.setVisible(true);
            jLabel3.setVisible(true);
            jLabel5.setVisible(true);
        } else if (jComboBox1.getSelectedItem().toString().compareTo("Reorder ace") == 0) {
            jLabel6.setVisible(false);
            windowSize.setVisible(false);
            queryField.setText("");
            sequenceAddField.setText("");
            queryField.setVisible(true);
            queryBrowseButton.setVisible(true);
            blastOptionField.setVisible(false);
            seqField.setVisible(false);
            seqBrowseButton.setVisible(false);
            jLabel2.setText("Assembly file (.ace)");
            jLabel1.setText("Contig List");
            jLabel1.setVisible(true);
            jLabel3.setVisible(false);
            jLabel5.setVisible(false);
        }

        }
    public void addFile(String file){
        File add = new File(file);
        File dir = new File(add.getParent());
        List<Element> existDir = BRIG.PROFILE.getRootElement().getChildren("refDir");
        Element child = new Element("refDir");
        boolean exist = false;
        for (int i = 0; i < existDir.size(); i++) {
            if (dir.getAbsolutePath().compareTo(new File(existDir.get(i).getAttributeValue("location")).getAbsolutePath()) == 0) {
                exist = true;
                child = existDir.get(i);
            }
        }
        Vector fil = One.SearchDir(dir.getAbsolutePath());
        List<Element> exFiles = child.getChildren("refFile");
        if (exist) {
            for (int i = 0; i < fil.size(); i++) {
                boolean fileExist = false;
                for (int j = 0; j < exFiles.size(); j++) {
                    if (exFiles.get(j).getAttributeValue("location").compareTo(add.getAbsolutePath()) == 0) {
                        fileExist = true;
                    }
                }
                if (!exist || !fileExist) {
                    Element fileloc = new Element("refFile");
                    fileloc.setAttribute("location", add.getAbsolutePath());
                    child.addContent(fileloc);
                }
            }
        } else {
            Element fileloc = new Element("refFile");
            fileloc.setAttribute("location", add.getAbsolutePath());
            child.addContent(fileloc);
            child.setAttribute("location", dir.getAbsolutePath());
            BRIG.PROFILE.getRootElement().addContent(child);
        }
    }

    public String reorderGraph() {
        try {
            String line = "";
            FileWriter fstream4 = new FileWriter(outputFolderField.getText() + BRIG.SL + BRIG.FetchFilename(sequenceAddField.getText()) + "new.ace");
            BufferedWriter out1 = new BufferedWriter(fstream4);
            BufferedReader in = new BufferedReader(new FileReader(queryField.getText()));
            String name = "";
            int on = 0;
            int totalContigs = 0;
            int currentContig = 0;
            try {
                while ((line = in.readLine()) != null) {
                    if (line.startsWith(">")) {
                        BufferedReader blast = new BufferedReader(new FileReader(sequenceAddField.getText()));
                        String[] lineArray = line.split("\\s+");
                        String get = "";
                        name = lineArray[0].replaceAll(">", "");
                        while ((get = blast.readLine()) != null) {
                            if (get.startsWith("AS")) {
                                String[] g = get.split("\\s+");
                                totalContigs = Integer.parseInt(g[1]);
                                out1.write(get);
                                out1.newLine();
                                out1.newLine();
                            } else if (get.startsWith("CO")) {
                                if (get.contains(name)) {
                                    on = 1;
                                    out1.write(get);
                                    out1.newLine();
                                    currentContig++;
                                } else {
                                    on = 0;
                                }
                            } else if (on == 1) {
                                out1.write(get);
                                out1.newLine();
                            }
                        }
                        blast.close();
                        updateProgress((int) (100 * ((double) currentContig / (double) totalContigs)) + "% Complete");
                    }
                }
                
            } catch (Exception e) {
                System.out.println(line);
                updateProgress("SYS_ERROR: " + e.getMessage());
                e.printStackTrace();
            }
            in.close();
            out1.close();
        } catch (Exception e) {
            updateProgress("SYS_ERROR: " + e.getMessage());
        }
        return (outputFolderField.getText() + BRIG.SL + BRIG.FetchFilename(sequenceAddField.getText()) + "new.ace");
    }

    public String checkGraph() throws FileNotFoundException, IOException {
        BufferedReader in = new BufferedReader(new FileReader(seqField.getText()));
        String line = "";
        int lineNum = 0 ;
        while ((line = in.readLine()) != null) {
            lineNum++;
            if (!line.contains("#")) {
                String[] lineArray = line.split("\t");
                if (Integer.parseInt( lineArray[1] ) - Integer.parseInt( lineArray[0] )  >1 ){
                    return "SYS_ERROR: Values must be listed for a single base pair only;\n check line "
                            + lineNum +" \"" + lineArray[0]+"  "+lineArray[1]+"  "+lineArray[2] + "\"";
                }
            }
        }
        return null;
    }

    
    public String convertGraph() {
        String blastLocation = "";
        if (BRIG.PROFILE.getRootElement().getChild("brig_settings") != null) {
            if (BRIG.PROFILE.getRootElement().getChild("brig_settings").getAttributeValue("blastLocation") != null) {
                blastLocation = BRIG.PROFILE.getRootElement().getChild("brig_settings").getAttributeValue("blastLocation");
                if (!(BRIG.PROFILE.getRootElement().getChild("brig_settings").getAttributeValue("blastLocation").endsWith(BRIG.SL))) {
                    if (BRIG.PROFILE.getRootElement().getChild("brig_settings").getAttributeValue("blastLocation").compareTo("") != 0) {
                        blastLocation += BRIG.SL;
                    }
                }
            }
        }
        String exec;
        if (BRIG.PROFILE.getRootElement().getAttribute("blastPlus") != null) {
            exec = (blastLocation + "makeblastdb -dbtype nucl  -in " + sequenceAddField.getText());
        } else {
            exec = (blastLocation + "formatdb -p F -i " + sequenceAddField.getText());
        }
        try {
            int div = 1000 ;
            try{
            div = Integer.parseInt(windowSize.getText());
            }catch(Exception e ){
                div = 1000;
            }
            // Run blast against query & ref
            updateProgress(exec);
            String data = "";
            Process p = Runtime.getRuntime().exec(exec);
            InputStream istrm = p.getErrorStream();
            InputStreamReader istrmrdr = new InputStreamReader(istrm);
            BufferedReader buffrdr = new BufferedReader(istrmrdr);
            String ergo = "";            
            while ((data = buffrdr.readLine()) != null) {
                ergo += data + "\n";
            }
            if (ergo.length() > 3) {
                updateProgress(ergo);
            } else {
                String ou = outputFolderField.getText() + BRIG.SL + BRIG.FetchFilename(queryField.getText()) + "vs" + BRIG.FetchFilename(sequenceAddField.getText()) + ".tab";
                updateProgress("Success!");
                if (BRIG.PROFILE.getRootElement().getAttribute("blastPlus") != null) {
                    //   exec = blastLocation + blastType + " -outfmt 6 -query " + goodRingFile + " -db " + queryFastaFile + " -out " + ou + " " + blastOptions;
                    exec = (blastLocation + "blastn -outfmt 6  -query " + queryField.getText() + " -db " + sequenceAddField.getText() + " -out " + ou + " "  + blastOptionField.getText() );
                } else {
                    exec = (blastLocation + "blastall -n T -m8 -i " + queryField.getText() + " -d " + sequenceAddField.getText() + " -o " + ou + " -p blastn " + blastOptionField.getText());
                }
                updateProgress(exec);
                p = Runtime.getRuntime().exec(exec);
                istrm = p.getErrorStream();
                istrmrdr = new InputStreamReader(istrm);
                buffrdr = new BufferedReader(istrmrdr);
                ergo = "";
                String line = "";
                while ((data = buffrdr.readLine()) != null) {
                    ergo += data + "\n";
                }
                if (ergo.length() > 3) {
                    updateProgress(ergo);
                } else {
                    updateProgress("Success!");
                    try {
                        int[] map = new int[BRIG.FastaLength(sequenceAddField.getText(), false)];
                        String[] res = sortBlast(ou);
                        FileWriter fstream4 = new FileWriter(outputFolderField.getText() + BRIG.SL + BRIG.FetchFilename(queryField.getText()) + "new.graph");
                        BufferedWriter out1 = new BufferedWriter(fstream4);
                        for (int j = 0; j < res.length; j++) {
                            // For each blast result, look up coverage value in file.
                            String[] resultsArray = res[j].split("\t");
                            boolean On = false;
                            int oldStart = Integer.parseInt(resultsArray[6]);
                            int oldStop = Integer.parseInt(resultsArray[7]);
                            if( oldStop < oldStart ){
                                oldStop =  Integer.parseInt(resultsArray[6]);
                                oldStart = Integer.parseInt(resultsArray[7]);
                            }
                            if(oldStart == 1){
                                oldStart = 0 ;
                            }
                            int newStart = Integer.parseInt(resultsArray[8]);
                            int newStop = Integer.parseInt(resultsArray[9]);
                            if( newStop < newStart ){
                                newStop  = Integer.parseInt(resultsArray[8]);
                                newStart = Integer.parseInt(resultsArray[9]);
                            }
                            if(newStart == 1){
                                newStart = 0 ;
                            }
                            int trimStart = 0;
                            BufferedReader in = new BufferedReader(new FileReader(seqField.getText()));
                            while ((line = in.readLine()) != null) {
                                String[] lineArray = line.split("\t");
                                if (line.startsWith("#")) {                                    
                                    if( resultsArray[0].compareTo(lineArray[2]) == 0 ){
                                        trimStart = Integer.parseInt(lineArray[0].replaceAll("\\D+", ""));
                                        int st = newStart;
                                        int sp = newStop;
                                        if( st == 0 ){
                                            st =1;
                                        }
                                        if (sp >= map.length) {
                                            sp = map.length - 1;
                                        }
                                        out1.write("#" + st + "\t" + sp + "\t" + resultsArray[0]);
                                        out1.newLine();
                                        On = true;
                                    }else{
                                        On = false;
                                    }
                                } else {
                                    if( On ){
                                        int trim = Integer.parseInt( lineArray[0])-trimStart;
                                        if(trim >= (oldStart) &&
                                          trim <= (oldStop ) && (newStart + (trim - oldStart) < map.length )) {
                                         /*   int eleStart = Integer.parseInt(lineArray[0]);
                                            int eleStop = Integer.parseInt(lineArray[1]);
                                            if( eleStop - eleStart  > 1  ){
                                                for( int k=eleStart; k< eleStop;k++){
                                                    if(k <= oldStop){
                                                        map[newStart + (trim - oldStart) + (k-eleStart)] =  (int) (Double.parseDouble(lineArray[2]) );
                                                        System.out.println((newStart + (trim - oldStart)+ (k-eleStart) )  + "\t" + map[newStart + (trim - oldStart)  ]);
                                                    }
                                                }
                                            }else{*/
                                            map[newStart + (trim - oldStart)] =  (int) (Double.parseDouble(lineArray[2]) );
                                         //   }
                                        }
                                    }
                                }

                            }
                            in.close();
                        }
                        updateProgress("Calculating coverage...");
                        int hund = 0;
                        int hundInc = 0;
                        int prevHund = 0;
                        for (int i = 0; i < map.length; i++) {
                            if (map[i] != -1) {
                                if (hundInc >= div) {
                                    //      System.out.println(pretemp + "\t" + prevHund + "\t" + hundInc + "\t" + hund);
                                    out1.write((prevHund) + "\t" + (prevHund + hundInc) + "\t" + ((double) hund / (double) hundInc));
                                    //       System.out.println( ((prevHund) + "\t" + (prevHund + hundInc) + "\t" + ((double) hund / (double) hundInc))   );
                                    out1.newLine();
                                    prevHund += hundInc;
                                    hundInc = 0;
                                    hund = 0;
                                }
                                hund += map[i];
                                hundInc++;
                            }
                        }
                        if (hundInc > 0) {
                            out1.write((prevHund) + "\t" + (prevHund + hundInc) + "\t" + ((double) hund / (double) hundInc));
                            //      System.out.println( (prevHund) + "\t" + (prevHund + hundInc) + "\t" + ((double) hund / (double) hundInc)  );
                            out1.newLine();
                        }
                        updateProgress("Done.");
                        out1.close();
                    } catch (Exception e) {
                        System.out.println(line);
           //             System.out.println(blastResult);
                        updateProgress("SYS_ERROR: " + e.getMessage());
                        e.printStackTrace();
                    }
              //      in.close();
            //        out1.close();

                }
            }
        } catch (Exception e) {
            updateProgress("SYS_ERROR: " + e.getMessage());
            e.printStackTrace();


        }
        return (outputFolderField.getText() + BRIG.SL + BRIG.FetchFilename(queryField.getText()) + "new.graph");
    }
    
    public String[] sortBlast(String file) throws IOException {
        BufferedReader first = new BufferedReader(new FileReader(file));
        String line = "";
        int num = 0;
        while ((line = first.readLine()) != null) {
            if (!line.startsWith("#")) {
                num++;
            }
        }
        first.close();
        String[] results = new String[num];
        first = new BufferedReader(new FileReader(file));
        line = "";
        int gum = 0;
        while ((line = first.readLine()) != null) {
            if (!line.startsWith("#")) {
                results[gum] = line;
                gum++;
            }
        }
        first.close();
        RevBlastComparator comp = new RevBlastComparator();
        Arrays.sort(results, comp);
        return results;
    }

    public Vector aceParse(Vector<Vector> graph) {
        try {
            BufferedReader in = new BufferedReader(new FileReader(sequenceAddField.getText()));
            FileWriter fstream4 = new FileWriter(outputFolderField.getText() + BRIG.SL + "scratch" + BRIG.SL + BRIG.FetchFilename(sequenceAddField.getText()) + "contigs.fna");
            FileWriter fstream5 = new FileWriter(outputFolderField.getText() + BRIG.SL + "scratch" + BRIG.SL + BRIG.FetchFilename(sequenceAddField.getText()) + "reads.fna");
            graph.get(0).set(3, outputFolderField.getText() + BRIG.SL + "scratch" + BRIG.SL + BRIG.FetchFilename(sequenceAddField.getText()) + "contigs.fna");
            graph.get(0).add(outputFolderField.getText() + BRIG.SL + "scratch" + BRIG.SL + BRIG.FetchFilename(sequenceAddField.getText()) + "reads.fna");
            BufferedWriter out2 = new BufferedWriter(fstream5);
            BufferedWriter out1 = new BufferedWriter(fstream4);
            String line = "";
            int contigOn = 0;
            int readOn = 0;
            updateProgress("Reading ace file..");
            while ((line = in.readLine()) != null) {
                Pattern COpattern = Pattern.compile("^CO\\s(\\S+)\\s+");
                Pattern BQpattern = Pattern.compile("^BQ");
                Pattern RDpattern = Pattern.compile("^RD\\s(\\S+)\\s+");
                Pattern QApattern = Pattern.compile("^QA");
                Matcher COmatcher = COpattern.matcher(line);
                Matcher BQmatcher = BQpattern.matcher(line);
                Matcher RDmatcher = RDpattern.matcher(line);
                Matcher QAmatcher = QApattern.matcher(line);
                if (COmatcher.find()) {
                    String contigName = COmatcher.group(1);
                    out1.write(">" + contigName);
                    out1.newLine();
                    contigOn = 1;
                }
                if (BQmatcher.find()) {
                    contigOn = 0;
                }
                if (RDmatcher.find()) {
                    String readName = RDmatcher.group(1);
                    out2.write(">" + readName);
                    out2.newLine();
                    readOn = 1;
                    contigOn = 0;
                    //  System.out.println("RD\t" +line);
                }
                if (QAmatcher.find()) {
                    readOn = 0;
                }
                if ((contigOn == 1) && !line.contains("CO")) {
                    out1.write(line);
                    out1.newLine();
                }
                if (readOn == 1 && !line.contains("RD")) {
                    out2.write(line);
                    out2.newLine();
                }
            }
            in.close();
            out1.close();
            out2.close();
            updateProgress("Reading ace file..Complete");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return graph;
    }

    public String SamcontigCoverage(String samFile, String outDirectory, String file, int div) throws IOException {
        
        int[] map = new int[1];
        FileWriter fstream5 = new FileWriter(outDirectory + BRIG.SL + BRIG.FetchFilename(file) + ".graph");
        BufferedWriter out = new BufferedWriter(fstream5);
        BufferedReader in = new BufferedReader(new FileReader(samFile));
        String line = "";
        Pattern SQpattern = Pattern.compile("^@SQ.+LN:(\\d+)");
        int length = 0;
         updateProgress("Reading sam file..");
        while ((line = in.readLine()) != null) {
            if (!line.startsWith("@")) {
                String[] lineArray = line.split("\t");
                int start = Integer.parseInt(lineArray[3]);
                int stop = start + lineArray[9].length();
                if (start > 0) {
                    if (start < stop) {
                        for (int j = start; j < stop; j++) {
                            try {
                                map[j] = map[j] + 1;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else if (start == stop) {
                        map[start] = map[start] + 1;
                    }
                }
            } else if (line.startsWith("@SQ")) {
                Matcher COmatcher = SQpattern.matcher(line);
                if (COmatcher.find()) {
                    length = Integer.parseInt(COmatcher.group(1));
                    map = new int[length];
                    System.out.println("# " + length);
                }
            }
        }
          updateProgress("Calculating coverage...");
        in.close();
        int hund = 0;
        int hundInc = 0;
        int prevHund = 0;
        for (int i = 0; i < map.length; i++) {
            if (map[i] != -1) {
                if (hundInc >= div) {
                    //      System.out.println(pretemp + "\t" + prevHund + "\t" + hundInc + "\t" + hund);
                    out.write((prevHund) + "\t" + (prevHund + hundInc) + "\t" + ((double) hund / (double) hundInc));
                    //       System.out.println( ((prevHund) + "\t" + (prevHund + hundInc) + "\t" + ((double) hund / (double) hundInc))   );
                    out.newLine();
                    prevHund += hundInc;
                    hundInc = 0;
                    hund = 0;
                }
                hund += map[i];
                hundInc++;
            }
        }
        if (hundInc > 0) {
            out.write((prevHund) + "\t" + (prevHund + hundInc) + "\t" + ((double) hund / (double) hundInc));
            //      System.out.println( (prevHund) + "\t" + (prevHund + hundInc) + "\t" + ((double) hund / (double) hundInc)  );
            out.newLine();
        }
        updateProgress("Done.");
        out.close();
        return (outDirectory + BRIG.SL + BRIG.FetchFilename(file) + ".graph");

    }


    public String contigCoverage(String aceFile, String outDirectory, int div) throws FileNotFoundException, IOException {
        // CREATE MAP
        int[] map = new int[1];
        BufferedReader in = new BufferedReader(new FileReader(aceFile));
        String line = "";
        //CREATE list of reads
        Vector<String> readNameList = new Vector<String>();
        Vector<Integer> readPositionList = new Vector<Integer>();
        Vector<Integer> readLengthList = new Vector<Integer>();
        int genomePosition = 0;
        int f = 0;
        int totalReads = 0;
        int isContigSequence = 0;
        int currentRead = 0;
        int gapPosition = 0;
        String contigName = "";
        Vector<Integer> gapLocations = new Vector<Integer>();
        FileWriter fstream5 = new FileWriter(outDirectory + BRIG.SL + BRIG.FetchFilename(sequenceAddField.getText()) + ".graph");
        BufferedWriter out = new BufferedWriter(fstream5);
        while ((line = in.readLine()) != null) {
            if (line.startsWith("AS ")) {
                String[] spaceArray = line.split("\\s+");
                totalReads = Integer.parseInt(spaceArray[2]);
            }
            if (line.startsWith("CO ")) {
                //CO FETCH length for boundaries of contig.  SPACE [2]
                //FORMAT list of READS into MAP
                if (readPositionList.size() > 0) {
                    for (int i = 0; i < readPositionList.size(); i++) {
                        int start = readPositionList.get(i);
                        int stop = readLengthList.get(i) + start;
                        if (start < stop) {
                            for (int j = start; j < stop; j++) {
                                map[j] = map[j] + 1;
                            }
                        } else if (start == stop) {
                            map[start] = map[start] + 1;
                        }
                    }
                    for (int a = 0; a < gapLocations.size(); a++) {
                        if (gapLocations.get(a) < map.length) {
                            map[gapLocations.get(a)] = -1;
                        }
                    }
                    int pretemp = genomePosition;
                    genomePosition += map.length - gapLocations.size();
                    if (pretemp == 0) {
                        out.write("#1\t" + genomePosition + "\t"+contigName);
                    } else {
                        out.write("#" + pretemp + "\t" + genomePosition+ "\t"+contigName);
                    }
                    out.newLine();
                    int hund = 0;
                    int hundInc = 0;
                    int prevHund = 0;
                    for (int i = 0; i < map.length; i++) {
                        if (map[i] != -1) {
                            if (hundInc >= div) {
                          //      System.out.println(pretemp + "\t" + prevHund + "\t" + hundInc + "\t" + hund);
                                out.write((pretemp + prevHund) + "\t" + (pretemp + prevHund + hundInc) + "\t" + ((double) hund / (double) hundInc));
                                out.newLine();
                                prevHund += hundInc;
                                hundInc = 0;
                                hund = 0;
                            }
                            hund += map[i];
                            hundInc++;
                        }
                    }
                    if (hundInc > 0) {
                        out.write((pretemp + prevHund) + "\t" + (pretemp + prevHund + hundInc) + "\t" + ((double) hund / (double) hundInc));
                        out.newLine();
                    }
                }
                String[] linesplit = line.split("\\s+");
                contigName = linesplit[1];
                map = new int[(Integer.parseInt(linesplit[2]))];
                readNameList = new Vector<String>();
                readPositionList = new Vector<Integer>();
                readLengthList = new Vector<Integer>();
                isContigSequence = 1;
                gapPosition = 0;
                gapLocations = new Vector();
                updateProgress((int) (100 * ((double) f / (double) totalReads)) + "% Complete");
            } else if (line.startsWith(
                    "BQ")) {
                isContigSequence = 0;
                gapPosition = 0;
            } else if (line.startsWith(
                    "AF ")) {
                //AF FETCH position within contig SPACE [3]
                String[] spaceArray = line.split("\\s+");
                readNameList.add(spaceArray[1]);
                readPositionList.add(Integer.parseInt(spaceArray[3]) - 1);
                readLengthList.add(0);
                f++;
            } else if (line.startsWith(
                    "RD ")) {
                //RD FETCH length of read SPACE [2]
                String[] spaceArray = line.split("\\s+");
                for (int i = 0; i < readNameList.size(); i++) {
                    if (readNameList.get(i).compareTo(spaceArray[1]) == 0) {
                        readLengthList.set(i, Integer.parseInt(spaceArray[2]));
                        currentRead = i;
                    }
                }
            } else if (line.startsWith(
                    "QA ")) {
                //QA FETCH trim space of read SPACE [3] & [4]
                String[] spaceArray = line.split("\\s+");
                readPositionList.set(currentRead, (readPositionList.get(currentRead) + Integer.parseInt(spaceArray[3]) - 1));
                readLengthList.set(currentRead, (Integer.parseInt(spaceArray[4]) - Integer.parseInt(spaceArray[3])));
            } else if (isContigSequence == 1) {
                for (int s = 0; s < line.length(); s++) {
                    gapPosition++;
                    if ("*".compareTo(String.valueOf(line.charAt(s))) == 0) {
                        gapLocations.add(gapPosition);

                    }
                }
            }
        }
        if (readPositionList.size() > 0) {
            for (int i = 0; i < readPositionList.size(); i++) {
                int start = readPositionList.get(i);
                int stop = readLengthList.get(i) + start;
                if (start < stop) {
                    for (int j = start; j < stop; j++) {
                        map[j] = map[j] + 1;
                    }
                } else if (start == stop) {
                    map[start] = map[start] + 1;
                }
            }
            for (int a = 0; a < gapLocations.size(); a++) {
                if (gapLocations.get(a) < map.length) {
                    map[gapLocations.get(a)] = -1;
                }
            }
            int pretemp = genomePosition;
            genomePosition += map.length - gapLocations.size();
            if (pretemp == 0) {
                out.write("#1\t" + genomePosition + "\t" + contigName);
            } else {
                out.write("#" + pretemp + "\t" + genomePosition + "\t" + contigName);
            }
            out.newLine();

            int hund = 0;
            int hundInc = 0;
            int prevHund = 0;
            for (int i = 0; i < map.length; i++) {
                if (map[i] != -1) {
                    if (hundInc >= div) {
                        //      System.out.println(pretemp + "\t" + prevHund + "\t" + hundInc + "\t" + hund);
                        out.write((pretemp + prevHund) + "\t" + (pretemp + prevHund + hundInc) + "\t" + ((double) hund / (double) hundInc));
                        out.newLine();
                        prevHund += hundInc;
                        hundInc = 0;
                        hund = 0;
                    }
                    hund += map[i];
                    hundInc++;
                }
            }
            if (hundInc > 0) {
                out.write((pretemp + prevHund) + "\t" + (pretemp + prevHund + hundInc) + "\t" + ((double) hund / (double) hundInc));
                out.newLine();
            }
        }
        in.close();
        out.close();
        updateProgress("Combined contigs length\t" + genomePosition);
        updateProgress("Done.");
        return (outDirectory + BRIG.SL + BRIG.FetchFilename(sequenceAddField.getText()) + ".graph");
    }

    private void updateProgress(final String text) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // Here, we can safely update the GUI
                // because we'll be called from the
                // event dispatch thread
                outputArea.append(text + "\n");
            }
        });
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Graph().setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField blastOptionField;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    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.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextArea outputArea;
    private javax.swing.JButton outputBrowseButton;
    private javax.swing.JTextField outputFolderField;
    private javax.swing.JButton queryBrowseButton;
    private javax.swing.JTextField queryField;
    private javax.swing.JButton refBrowseButton;
    private javax.swing.JButton seqBrowseButton;
    private javax.swing.JTextField seqField;
    private javax.swing.JTextField sequenceAddField;
    private javax.swing.JButton submit;
    private javax.swing.JTextField windowSize;
    // End of variables declaration//GEN-END:variables
}

class RevBlastComparator implements Comparator<String> {

    public int compare(String o1, String o2) {
        String[] o1Array = o1.split("\t");
        String[] o2Array = o2.split("\t");
        if (Double.parseDouble(o1Array[10]) <= Double.parseDouble(o2Array[10])) {
            return 1;
        } else if (Double.parseDouble(o1Array[10]) > Double.parseDouble(o2Array[10])) {
            return -1;
        } else {
            return 0;
        }
    }
}