On 'save' menu entry check to see if fileformat is a valid output format and open...
[jalview.git] / src / jalview / gui / AlignFrame.java
index 8c9246b..72691cc 100755 (executable)
@@ -28,6 +28,7 @@ import java.awt.dnd.*;
 import java.awt.event.*;
 import java.awt.print.*;
 import javax.swing.*;
+import javax.swing.event.MenuEvent;
 
 import jalview.analysis.*;
 import jalview.commands.*;
@@ -57,11 +58,17 @@ public class AlignFrame
 
   Vector alignPanels = new Vector();
 
-  /** DOCUMENT ME!! */
-  String currentFileFormat = null;
 
+  /** 
+   * Last format used to load or save alignments in this window 
+   */
+  String currentFileFormat = null;
+  /**
+   * Current filename for this alignment
+   */
   String fileName = null;
 
+
   /**
    * Creates a new AlignFrame object.
    *
@@ -72,6 +79,7 @@ public class AlignFrame
     this(al, null, width, height);
   }
 
+
   /**
    * new alignment window with hidden columns
    * @param al AlignmentI
@@ -85,7 +93,7 @@ public class AlignFrame
 
     alignPanel = new AlignmentPanel(this, viewport);
 
-    if (al.getDataset() == null)
+    if(al.getDataset()==null)
     {
       al.setDataset(null);
     }
@@ -109,16 +117,14 @@ public class AlignFrame
 
   void init()
   {
-    this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
-
     if (viewport.conservation == null)
     {
       BLOSUM62Colour.setEnabled(false);
       conservationMenuItem.setEnabled(false);
       modifyConservation.setEnabled(false);
-      //  PIDColour.setEnabled(false);
-      //  abovePIDThreshold.setEnabled(false);
-      //  modifyPID.setEnabled(false);
+    //  PIDColour.setEnabled(false);
+    //  abovePIDThreshold.setEnabled(false);
+    //  modifyPID.setEnabled(false);
     }
 
     String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT", "No sort");
@@ -133,246 +139,255 @@ public class AlignFrame
     }
 
     if (Desktop.desktop != null)
-    {
-      addServiceListeners();
-      setGUINucleotide(viewport.alignment.isNucleotide());
-    }
-
-    setMenusFromViewport(viewport);
+   {
+     this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
+     addServiceListeners();
+     setGUINucleotide(viewport.alignment.isNucleotide());
+   }
 
-    if (viewport.wrapAlignment)
-    {
-      wrapMenuItem_actionPerformed(null);
-    }
+   setMenusFromViewport(viewport);
+   buildSortByAnnotationScoresMenu();
+   if (viewport.wrapAlignment)
+   {
+     wrapMenuItem_actionPerformed(null);
+   }
 
     if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW",false))
     {
       this.overviewMenuItem_actionPerformed(null);
     }
 
-    addKeyListener();
+   addKeyListener();
 
   }
-
+  /**
+   * Change the filename and format for the alignment, and
+   * enable the 'reload' button functionality.
+   * @param file valid filename
+   * @param format format of file
+   */
   public void setFileName(String file, String format)
   {
-    fileName = file;
-    currentFileFormat = format;
-    reload.setEnabled(true);
+     fileName = file;
+     currentFileFormat = format;
+     reload.setEnabled(true);
   }
 
   void addKeyListener()
   {
-    addKeyListener(new KeyAdapter()
-    {
-      public void keyPressed(KeyEvent evt)
+      addKeyListener(new KeyAdapter()
       {
-        if (viewport.cursorMode
-            && evt.getKeyCode() >= KeyEvent.VK_0
-            && evt.getKeyCode() <= KeyEvent.VK_9)
-        {
-          alignPanel.seqPanel.numberPressed(evt.getKeyChar());
-        }
-
-        switch (evt.getKeyCode())
+        public void keyPressed(KeyEvent evt)
         {
+          if (viewport.cursorMode &&
+              ( (evt.getKeyCode() >= KeyEvent.VK_0 &&
+                 evt.getKeyCode() <= KeyEvent.VK_9)
+               ||
+               (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0 &&
+                evt.getKeyCode() <= KeyEvent.VK_NUMPAD9)
+              )
+              && Character.isDigit(evt.getKeyChar()))
+            alignPanel.seqPanel.numberPressed(evt.getKeyChar());
+
+          switch (evt.getKeyCode())
+          {
 
-          case 27: // escape key
-            deselectAllSequenceMenuItem_actionPerformed(null);
+            case 27: // escape key
+              deselectAllSequenceMenuItem_actionPerformed(null);
 
-            break;
+              break;
 
-          case KeyEvent.VK_DOWN:
+            case KeyEvent.VK_DOWN:
              if (evt.isAltDown() || !viewport.cursorMode)
               moveSelectedSequences(false);
-            if(viewport.cursorMode)
-              alignPanel.seqPanel.moveCursor(0, 1);
-            break;
+              if (viewport.cursorMode)
+                alignPanel.seqPanel.moveCursor(0, 1);
+              break;
 
-          case KeyEvent.VK_UP:
+            case KeyEvent.VK_UP:
             if (evt.isAltDown() || !viewport.cursorMode)
               moveSelectedSequences(true);
-            if(viewport.cursorMode)
-              alignPanel.seqPanel.moveCursor(0, -1);
+              if (viewport.cursorMode)
+                alignPanel.seqPanel.moveCursor(0, -1);
 
-            break;
+              break;
 
-          case KeyEvent.VK_LEFT:
+            case KeyEvent.VK_LEFT:
             if (evt.isAltDown() || !viewport.cursorMode)
               slideSequences(false,
                              alignPanel.seqPanel.getKeyboardNo1());
             else
-              alignPanel.seqPanel.moveCursor( -1, 0);
+                alignPanel.seqPanel.moveCursor( -1, 0);
 
 
-            break;
+              break;
 
-          case KeyEvent.VK_RIGHT:
+            case KeyEvent.VK_RIGHT:
             if (evt.isAltDown() || !viewport.cursorMode)
               slideSequences(true,
                              alignPanel.seqPanel.getKeyboardNo1());
             else
-              alignPanel.seqPanel.moveCursor( 1, 0);
-            break;
+                alignPanel.seqPanel.moveCursor(1, 0);
+              break;
 
-          case KeyEvent.VK_SPACE:
-            if (viewport.cursorMode)
-            {
-              alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
-                  || evt.isShiftDown()
-                  || evt.isAltDown());
-            }
-            break;
+            case KeyEvent.VK_SPACE:
+              if (viewport.cursorMode)
+              {
+                alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
+                                           || evt.isShiftDown()
+                                           || evt.isAltDown());
+              }
+              break;
 
-          case KeyEvent.VK_DELETE:
-          case KeyEvent.VK_BACK_SPACE:
-            if (!viewport.cursorMode)
-            {
-              cut_actionPerformed(null);
-            }
-            else
+            case KeyEvent.VK_DELETE:
+            case KeyEvent.VK_BACK_SPACE:
+              if (!viewport.cursorMode)
+              {
+                cut_actionPerformed(null);
+              }
+              else
             {
-              alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
-                  || evt.isShiftDown()
-                  || evt.isAltDown());
+                alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
+                                           || evt.isShiftDown()
+                                           || evt.isAltDown());
             }
 
-            break;
+              break;
 
-          case KeyEvent.VK_S:
-            if (viewport.cursorMode)
-            {
-              alignPanel.seqPanel.setCursorRow();
-            }
-            break;
-          case KeyEvent.VK_C:
-            if (viewport.cursorMode && !evt.isControlDown())
-            {
-              alignPanel.seqPanel.setCursorColumn();
-            }
-            break;
-          case KeyEvent.VK_P:
-            if (viewport.cursorMode)
-            {
-              alignPanel.seqPanel.setCursorPosition();
-            }
-            break;
+            case KeyEvent.VK_S:
+              if (viewport.cursorMode)
+              {
+                alignPanel.seqPanel.setCursorRow();
+              }
+              break;
+            case KeyEvent.VK_C:
+              if (viewport.cursorMode && !evt.isControlDown())
+              {
+                alignPanel.seqPanel.setCursorColumn();
+              }
+              break;
+            case KeyEvent.VK_P:
+              if (viewport.cursorMode)
+              {
+                alignPanel.seqPanel.setCursorPosition();
+              }
+              break;
 
-          case KeyEvent.VK_ENTER:
-          case KeyEvent.VK_COMMA:
-            if (viewport.cursorMode)
-            {
-              alignPanel.seqPanel.setCursorRowAndColumn();
-            }
-            break;
+            case KeyEvent.VK_ENTER:
+            case KeyEvent.VK_COMMA:
+              if (viewport.cursorMode)
+              {
+                alignPanel.seqPanel.setCursorRowAndColumn();
+              }
+              break;
 
-          case KeyEvent.VK_Q:
-            if (viewport.cursorMode)
-            {
-              alignPanel.seqPanel.setSelectionAreaAtCursor(true);
-            }
-            break;
-          case KeyEvent.VK_M:
-            if (viewport.cursorMode)
-            {
-              alignPanel.seqPanel.setSelectionAreaAtCursor(false);
-            }
-            break;
+            case KeyEvent.VK_Q:
+              if (viewport.cursorMode)
+              {
+                alignPanel.seqPanel.setSelectionAreaAtCursor(true);
+              }
+              break;
+            case KeyEvent.VK_M:
+              if (viewport.cursorMode)
+              {
+                alignPanel.seqPanel.setSelectionAreaAtCursor(false);
+              }
+              break;
 
-          case KeyEvent.VK_F2:
-            viewport.cursorMode = !viewport.cursorMode;
-            statusBar.setText("Keyboard editing mode is " +
-                              (viewport.cursorMode ? "on" : "off"));
-            if (viewport.cursorMode)
-            {
-              alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
-              alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
-            }
-            alignPanel.seqPanel.seqCanvas.repaint();
-            break;
+            case KeyEvent.VK_F2:
+              viewport.cursorMode = !viewport.cursorMode;
+              statusBar.setText("Keyboard editing mode is " +
+                                           (viewport.cursorMode ? "on" : "off"));
+              if (viewport.cursorMode)
+              {
+                alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
+                alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
+              }
+              alignPanel.seqPanel.seqCanvas.repaint();
+              break;
 
-          case KeyEvent.VK_F1:
-            try
-            {
-              ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
-              java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
-              javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
+            case KeyEvent.VK_F1:
+              try
+              {
+                ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
+                java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
+                javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
 
-              javax.help.HelpBroker hb = hs.createHelpBroker();
-              hb.setCurrentID("home");
-              hb.setDisplayed(true);
-            }
-            catch (Exception ex)
+                javax.help.HelpBroker hb = hs.createHelpBroker();
+                hb.setCurrentID("home");
+                hb.setDisplayed(true);
+              }
+              catch (Exception ex)
+              {
+                ex.printStackTrace();
+              }
+              break
+                  ;
+            case KeyEvent.VK_H:
             {
-              ex.printStackTrace();
-            }
-            break
-                ;
-          case KeyEvent.VK_H:
-          {
-            boolean toggleSeqs = !evt.isControlDown();
-            boolean toggleCols = !evt.isShiftDown();
+              boolean toggleSeqs = !evt.isControlDown();
+              boolean toggleCols = !evt.isShiftDown();
 
-            boolean hide = false;
+              boolean hide = false;
 
-            SequenceGroup sg = viewport.getSelectionGroup();
-            if (toggleSeqs)
-            {
-              if (sg != null && sg.getSize() != viewport.alignment.getHeight())
+              SequenceGroup sg = viewport.getSelectionGroup();
+              if (toggleSeqs)
               {
-                hideSelSequences_actionPerformed(null);
-                hide = true;
-              }
+                if (sg != null && sg.getSize() != viewport.alignment.getHeight())
+                {
+                  hideSelSequences_actionPerformed(null);
+                  hide = true;
+                }
               else if (! (toggleCols &&
                           viewport.colSel.getSelected().size() > 0))
               {
-                showAllSeqs_actionPerformed(null);
+                  showAllSeqs_actionPerformed(null);
               }
             }
 
-            if (toggleCols)
-            {
-              if (viewport.colSel.getSelected().size() > 0)
+              if (toggleCols)
               {
-                hideSelColumns_actionPerformed(null);
-                if (!toggleSeqs)
+                if (viewport.colSel.getSelected().size() > 0)
                 {
-                  viewport.selectionGroup = sg;
+                  hideSelColumns_actionPerformed(null);
+                  if (!toggleSeqs)
+                {
+                    viewport.selectionGroup = sg;
                 }
               }
-              else if (!hide)
+                else if (!hide)
               {
-                showAllColumns_actionPerformed(null);
+                  showAllColumns_actionPerformed(null);
               }
             }
-            break;
-          }
-          case KeyEvent.VK_PAGE_UP:
-            if (viewport.wrapAlignment)
+              break;
+            }
+            case KeyEvent.VK_PAGE_UP:
+              if (viewport.wrapAlignment)
             {
-              alignPanel.scrollUp(true);
+                alignPanel.scrollUp(true);
             }
-            else
+              else
             {
-              alignPanel.setScrollValues(viewport.startRes,
-                                         viewport.startSeq
-                                         - viewport.endSeq + viewport.startSeq);
+                alignPanel.setScrollValues(viewport.startRes,
+                                           viewport.startSeq
+                                           - viewport.endSeq + viewport.startSeq);
             }
-            break;
-          case KeyEvent.VK_PAGE_DOWN:
-            if (viewport.wrapAlignment)
+              break;
+            case KeyEvent.VK_PAGE_DOWN:
+              if (viewport.wrapAlignment)
             {
-              alignPanel.scrollUp(false);
+                alignPanel.scrollUp(false);
             }
-            else
+              else
             {
-              alignPanel.setScrollValues(viewport.startRes,
-                                         viewport.startSeq
-                                         + viewport.endSeq - viewport.startSeq);
+                alignPanel.setScrollValues(viewport.startRes,
+                                           viewport.startSeq
+                                           + viewport.endSeq - viewport.startSeq);
             }
-            break;
+              break;
+          }
         }
-      }
 
       public void keyReleased(KeyEvent evt)
       {
@@ -391,9 +406,10 @@ public class AlignFrame
             break;
         }
       }
-    });
+      });
   }
 
+
   public void addAlignmentPanel(final AlignmentPanel ap,
                                 boolean newPanel)
   {
@@ -405,9 +421,9 @@ public class AlignFrame
 
     int aSize = alignPanels.size();
 
-    tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
+    tabbedPane.setVisible(aSize>1 || ap.av.viewName!=null);
 
-    if (aSize == 1 && ap.av.viewName == null)
+    if (aSize == 1 && ap.av.viewName==null)
     {
       this.getContentPane().add(ap, BorderLayout.CENTER);
     }
@@ -425,7 +441,7 @@ public class AlignFrame
       ap.setVisible(false);
     }
 
-    if (newPanel)
+    if(newPanel)
     {
       if (ap.av.padGaps)
       {
@@ -442,10 +458,11 @@ public class AlignFrame
     gatherViews.setEnabled(true);
     tabbedPane.setVisible(true);
     AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
-    tabbedPane.addTab(first.av.viewName, first);
+    tabbedPane.addTab(first.av.viewName,first);
     this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
   }
 
+
   public AlignViewport getViewport()
   {
     return viewport;
@@ -487,17 +504,20 @@ public class AlignFrame
 
   public void setGUINucleotide(boolean nucleotide)
   {
-    showTranslation.setVisible(nucleotide);
-    conservationMenuItem.setEnabled(!nucleotide);
-    modifyConservation.setEnabled(!nucleotide);
-
+    showTranslation.setVisible( nucleotide );
+    conservationMenuItem.setEnabled( !nucleotide );
+    modifyConservation.setEnabled(   !nucleotide );
+    
     //Remember AlignFrame always starts as protein
-    if (!nucleotide)
+    if(!nucleotide)
     {
-      calculateMenu.remove(calculateMenu.getItemCount() - 2);
+      calculateMenu.remove(calculateMenu.getItemCount()-2);
     }
+    setShowProductsEnabled();
   }
 
+
+
   /**
    * Need to call this method when tabs are selected for multiple views,
    * or when loading from Jalview2XML.java
@@ -530,29 +550,30 @@ public class AlignFrame
     updateEditMenuBar();
   }
 
+
   Hashtable progressBars;
   public void setProgressBar(String message, long id)
   {
-    if (progressBars == null)
+    if(progressBars == null)
     {
       progressBars = new Hashtable();
     }
 
     JPanel progressPanel;
     GridLayout layout = (GridLayout) statusPanel.getLayout();
-    if (progressBars.get(new Long(id)) != null)
-    {
-      progressPanel = (JPanel) progressBars.get(new Long(id));
-      statusPanel.remove(progressPanel);
-      progressBars.remove(progressPanel);
-      progressPanel = null;
-      if (message != null)
+    if(progressBars.get( new Long(id) )!=null)
+     {
+       progressPanel = (JPanel)progressBars.get( new Long(id) );
+       statusPanel.remove(progressPanel);
+       progressBars.remove( progressPanel );
+       progressPanel = null;
+       if(message!=null)
       {
-        statusBar.setText(message);
+         statusBar.setText(message);
       }
 
-      layout.setRows(layout.getRows() - 1);
-    }
+       layout.setRows(layout.getRows() - 1);
+     }
     else
     {
       progressPanel = new JPanel(new BorderLayout(10, 5));
@@ -571,13 +592,24 @@ public class AlignFrame
 
     validate();
   }
-
+  /**
+   * 
+   * @return true if any progress bars are still active
+   */
+  public boolean operationInProgress()
+  {
+    if (progressBars!=null && progressBars.size()>0)
+    {
+      return true;
+    }
+    return false;
+  }
   /*
    Added so Castor Mapping file can obtain Jalview Version
-   */
+  */
   public String getVersion()
   {
-    return jalview.bin.Cache.getProperty("VERSION");
+    return  jalview.bin.Cache.getProperty("VERSION");
   }
 
   public FeatureRenderer getFeatureRenderer()
@@ -585,6 +617,7 @@ public class AlignFrame
     return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
   }
 
+
   public void fetchSequence_actionPerformed(ActionEvent e)
   {
     new SequenceFetcher(this);
@@ -597,12 +630,12 @@ public class AlignFrame
 
   public void reload_actionPerformed(ActionEvent e)
   {
-    if (fileName != null)
+    if(fileName!=null)
     {
-      if (currentFileFormat.equals("Jalview"))
+      if(currentFileFormat.equals("Jalview"))
       {
-        JInternalFrame[] frames = Desktop.desktop.getAllFrames();
-        for (int i = 0; i < frames.length; i++)
+        JInternalFrame [] frames = Desktop.desktop.getAllFrames();
+        for(int i=0; i<frames.length; i++)
         {
           if (frames[i] instanceof AlignFrame
               && frames[i] != this
@@ -612,7 +645,7 @@ public class AlignFrame
             {
               frames[i].setSelected(true);
               Desktop.instance.closeAssociatedWindows();
-            }
+          }
             catch (java.beans.PropertyVetoException ex)
             {}
           }
@@ -640,6 +673,7 @@ public class AlignFrame
     }
   }
 
+
   public void addFromText_actionPerformed(ActionEvent e)
   {
     Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
@@ -650,11 +684,12 @@ public class AlignFrame
     Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
   }
 
+
   public void save_actionPerformed(ActionEvent e)
   {
-    if (fileName == null
-        || currentFileFormat == null
-        || fileName.startsWith("http")
+    if(fileName==null
+       || (currentFileFormat==null || jalview.io.AppletFormatAdapter.isValidFormat(currentFileFormat, true))
+       || fileName.startsWith("http")
         )
     {
       saveAs_actionPerformed(null);
@@ -662,7 +697,7 @@ public class AlignFrame
     else
     {
       saveAlignment(fileName, currentFileFormat);
-    }
+  }
   }
 
   /**
@@ -673,14 +708,13 @@ public class AlignFrame
   public void saveAs_actionPerformed(ActionEvent e)
   {
     JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
-        getProperty("LAST_DIRECTORY"),
-        new String[]
-        {"fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc", "jar"},
-        new String[]
-        {"Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "Jalview"},
+        getProperty( "LAST_DIRECTORY"),
+        jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
+        jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
         currentFileFormat,
         false);
 
+
     chooser.setFileView(new JalviewFileView());
     chooser.setDialogTitle("Save Alignment to file");
     chooser.setToolTipText("Save");
@@ -689,24 +723,27 @@ public class AlignFrame
 
     if (value == JalviewFileChooser.APPROVE_OPTION)
     {
-      currentFileFormat = chooser.getSelectedFormat();
-      if (currentFileFormat == null)
-      {
-        JOptionPane.showInternalMessageDialog(Desktop.desktop,
-                                              "You must select a file format before saving!",
-                                              "File format not specified",
-                                              JOptionPane.WARNING_MESSAGE);
-        value = chooser.showSaveDialog(this);
-        return;
-      }
+        currentFileFormat = chooser.getSelectedFormat();
+        if (currentFileFormat == null)
+        {
+          JOptionPane.showInternalMessageDialog(Desktop.desktop,
+                                                "You must select a file format before saving!",
+                                                "File format not specified",
+                                                JOptionPane.WARNING_MESSAGE);
+          value = chooser.showSaveDialog(this);
+          return;
+        }
 
-      fileName = chooser.getSelectedFile().getPath();
+        fileName = chooser.getSelectedFile().getPath();
 
       jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
                                     currentFileFormat);
 
       jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
-
+      if (currentFileFormat.indexOf(" ")>-1)
+      {
+        currentFileFormat = currentFileFormat.substring(0, currentFileFormat.indexOf(" "));
+      }
       saveAlignment(fileName, currentFileFormat);
     }
   }
@@ -728,13 +765,23 @@ public class AlignFrame
       success = new Jalview2XML().SaveAlignment(this, file, shortName);
 
       statusBar.setText("Successfully saved to file: "
-                        + fileName + " in "
-                        + format + " format.");
+                          +fileName+" in "
+                          +format +" format.");
 
     }
     else
-    {
-
+    {        
+      if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
+      {
+        // JBPNote need to have a raise_gui flag here
+        JOptionPane.showInternalMessageDialog(
+                this, "Cannot save file " + fileName + " using format "+format,
+                "Alignment output format not supported",
+                JOptionPane.WARNING_MESSAGE);
+        saveAs_actionPerformed(null);
+        return false;
+      }
+        
       String[] omitHidden = null;
 
       if (viewport.hasHiddenColumns)
@@ -748,13 +795,13 @@ public class AlignFrame
         if (reply == JOptionPane.YES_OPTION)
         {
           omitHidden = viewport.getViewAsString(false);
-        }
       }
-
-      String output = new FormatAdapter().formatSequences(
+      }
+      FormatAdapter f = new FormatAdapter();
+      String output = f.formatSequences(
           format,
-          viewport.alignment.getSequencesArray(),
-          omitHidden);
+          (Alignment) viewport.alignment, // class cast exceptions will occur in the distant future
+          omitHidden, f.getCacheSuffixDefault(format), viewport.colSel);
 
       if (output == null)
       {
@@ -800,17 +847,17 @@ public class AlignFrame
    */
   protected void outputText_actionPerformed(ActionEvent e)
   {
-    String[] omitHidden = null;
+    String [] omitHidden = null;
 
-    if (viewport.hasHiddenColumns)
+    if(viewport.hasHiddenColumns)
     {
       int reply = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
           "The Alignment contains hidden columns."
-          + "\nDo you want to output only the visible alignment?",
-          "Save / Omit Hidden Columns",
-          JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
+      +"\nDo you want to output only the visible alignment?",
+      "Save / Omit Hidden Columns",
+      JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
 
-      if (reply == JOptionPane.YES_OPTION)
+      if(reply==JOptionPane.YES_OPTION)
       {
         omitHidden = viewport.getViewAsString(false);
       }
@@ -822,10 +869,11 @@ public class AlignFrame
                              "Alignment output - " + e.getActionCommand(), 600,
                              500);
 
+
     cap.setText(new FormatAdapter().formatSequences(
         e.getActionCommand(),
-        viewport.alignment.getSequencesArray(),
-        omitHidden));
+        viewport.alignment,
+        omitHidden, viewport.colSel));
   }
 
   /**
@@ -835,9 +883,9 @@ public class AlignFrame
    */
   protected void htmlMenuItem_actionPerformed(ActionEvent e)
   {
-    new HTMLOutput(viewport,
+    new HTMLOutput(alignPanel,
                    alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
-                   alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
+        alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
   }
 
   public void createImageMap(File file, String image)
@@ -865,6 +913,7 @@ public class AlignFrame
     alignPanel.makeEPS(f);
   }
 
+
   public void pageSetup_actionPerformed(ActionEvent e)
   {
     PrinterJob printJob = PrinterJob.getPrinterJob();
@@ -888,15 +937,18 @@ public class AlignFrame
     new AnnotationExporter().exportFeatures(alignPanel);
   }
 
+
   public void exportAnnotations_actionPerformed(ActionEvent e)
   {
     new AnnotationExporter().exportAnnotations(
-        alignPanel,
+      alignPanel,
         viewport.showAnnotation ? viewport.alignment.getAlignmentAnnotation() : null,
-        viewport.alignment.getGroups()
+      viewport.alignment.getGroups(),
+      ((Alignment)viewport.alignment).alignmentProperties
         );
   }
 
+
   public void associatedData_actionPerformed(ActionEvent e)
   {
     // Pick the tree file
@@ -918,6 +970,7 @@ public class AlignFrame
 
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -925,23 +978,26 @@ public class AlignFrame
    */
   public void closeMenuItem_actionPerformed(boolean closeAllTabs)
   {
-    if (alignPanels != null && alignPanels.size() < 2)
+    if(alignPanels!=null && alignPanels.size()<2)
     {
       closeAllTabs = true;
     }
 
     try
     {
-      if (alignPanels != null)
+      if(alignPanels!=null)
       {
         if (closeAllTabs)
         {
           for (int i = 0; i < alignPanels.size(); i++)
           {
             AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
+            jalview.structure.StructureSelectionManager.getStructureSelectionManager()
+                .removeStructureViewerListener(ap.seqPanel, null);
             PaintRefresher.RemoveComponent(ap.seqPanel.seqCanvas);
             PaintRefresher.RemoveComponent(ap.idPanel.idCanvas);
             PaintRefresher.RemoveComponent(ap);
+            ap.av.alignment = null;
           }
         }
         else
@@ -952,15 +1008,16 @@ public class AlignFrame
           PaintRefresher.RemoveComponent(alignPanel.seqPanel.seqCanvas);
           PaintRefresher.RemoveComponent(alignPanel.idPanel.idCanvas);
           PaintRefresher.RemoveComponent(alignPanel);
+          viewport.alignment = null;
           alignPanel = null;
           viewport = null;
 
           tabbedPane.removeTabAt(index);
           tabbedPane.validate();
 
-          if (index == tabbedPane.getTabCount())
+          if(index==tabbedPane.getTabCount())
           {
-            index--;
+            index --;
           }
 
           this.tabSelectionChanged(index);
@@ -970,7 +1027,7 @@ public class AlignFrame
       if (closeAllTabs)
       {
         this.setClosed(true);
-      }
+    }
     }
     catch (Exception ex)
     {
@@ -978,6 +1035,7 @@ public class AlignFrame
     }
   }
 
+
   /**
    * DOCUMENT ME!
    */
@@ -1010,9 +1068,10 @@ public class AlignFrame
     }
   }
 
+
   public void addHistoryItem(CommandI command)
   {
-    if (command.getSize() > 0)
+    if(command.getSize()>0)
     {
       viewport.historyList.push(command);
       viewport.redoList.clear();
@@ -1022,20 +1081,44 @@ public class AlignFrame
   }
 
   /**
+   *
+   * @return alignment objects for all views
+   */
+  AlignmentI[] getViewAlignments()
+  {
+    if (alignPanels!=null)
+    {
+      Enumeration e = alignPanels.elements();
+      AlignmentI[] als = new AlignmentI[alignPanels.size()];
+      for (int i=0; e.hasMoreElements(); i++)
+      {
+        als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
+      }
+      return als;
+    }
+    if (viewport!=null)
+    {
+      return new AlignmentI[] { viewport.alignment };
+    }
+    return null;
+  }
+  /**
    * DOCUMENT ME!
    *
    * @param e DOCUMENT ME!
    */
   protected void undoMenuItem_actionPerformed(ActionEvent e)
   {
-    CommandI command = (CommandI) viewport.historyList.pop();
+    if (viewport.historyList.empty())
+      return;
+    CommandI command = (CommandI)viewport.historyList.pop();
     viewport.redoList.push(command);
-    command.undoCommand();
+    command.undoCommand(getViewAlignments());
 
     AlignViewport originalSource = getOriginatingSource(command);
     updateEditMenuBar();
 
-    if (originalSource != null)
+    if(originalSource!=null)
     {
       originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
       originalSource.firePropertyChange("alignment",
@@ -1051,19 +1134,19 @@ public class AlignFrame
    */
   protected void redoMenuItem_actionPerformed(ActionEvent e)
   {
-    if (viewport.redoList.size() < 1)
+    if(viewport.redoList.size()<1)
     {
       return;
     }
 
     CommandI command = (CommandI) viewport.redoList.pop();
     viewport.historyList.push(command);
-    command.doCommand();
+    command.doCommand(getViewAlignments());
 
     AlignViewport originalSource = getOriginatingSource(command);
     updateEditMenuBar();
 
-    if (originalSource != null)
+    if(originalSource!=null)
     {
       originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
       originalSource.firePropertyChange("alignment",
@@ -1076,9 +1159,9 @@ public class AlignFrame
   {
     AlignViewport originalSource = null;
     //For sequence removal and addition, we need to fire
-    //the property change event FROM the viewport where the
-    //original alignment was altered
-    AlignmentI al = null;
+   //the property change event FROM the viewport where the
+   //original alignment was altered
+    AlignmentI al=null;
     if (command instanceof EditCommand)
     {
       EditCommand editCommand = (EditCommand) command;
@@ -1177,16 +1260,10 @@ public class AlignFrame
   }
 
 
+
+
   synchronized void slideSequences(boolean right, int size)
   {
-    if(viewport.hasHiddenColumns)
-    {
-      JOptionPane.showInternalMessageDialog(Desktop.desktop,
-          "Slide Sequences not available with hidden columns",
-          "Slide Sequence not Available",
-          JOptionPane.WARNING_MESSAGE);
-      return;
-    }
     Vector sg = new Vector();
     if(viewport.cursorMode)
     {
@@ -1287,8 +1364,8 @@ public class AlignFrame
     {
       return;
     }
-
-    SequenceI[] seqs = viewport.getSelectionAsNewSequence();
+    //  TODO: preserve the ordering of displayed alignment annotation in any internal paste (particularly sequence associated annotation)
+    SequenceI [] seqs = viewport.getSelectionAsNewSequence();
     String[] omitHidden = null;
 
     if (viewport.hasHiddenColumns)
@@ -1318,25 +1395,25 @@ public class AlignFrame
     {
       er.printStackTrace();
       javax.swing.SwingUtilities.invokeLater(new Runnable()
-      {
-        public void run()
-        {
-          javax.swing.JOptionPane.showInternalMessageDialog(Desktop.desktop,
-              "Out of memory copying region!!"
-              +
-              "\nSee help files for increasing Java Virtual Machine memory."
-              , "Out of memory",
-              javax.swing.JOptionPane.WARNING_MESSAGE);
-        }
-      });
+          {
+            public void run()
+            {
+              javax.swing.JOptionPane.showInternalMessageDialog(Desktop.desktop,
+                  "Out of memory copying region!!"
+                  +
+                  "\nSee help files for increasing Java Virtual Machine memory."
+                  , "Out of memory",
+                  javax.swing.JOptionPane.WARNING_MESSAGE);
+            }
+          });
 
       return;
     }
 
     Vector hiddenColumns = null;
-    if (viewport.hasHiddenColumns)
+    if(viewport.hasHiddenColumns)
     {
-      hiddenColumns = new Vector();
+      hiddenColumns =new Vector();
       int hiddenOffset = viewport.getSelectionGroup().getStartRes();
       for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns().size();
            i++)
@@ -1346,7 +1423,7 @@ public class AlignFrame
 
         hiddenColumns.addElement(new int[]
                                  {region[0] - hiddenOffset,
-                                 region[1] - hiddenOffset});
+                          region[1]-hiddenOffset});
       }
     }
 
@@ -1355,7 +1432,7 @@ public class AlignFrame
         seqs,
         viewport.alignment.getDataset(),
         hiddenColumns};
-    statusBar.setText("Copied " + seqs.length + " sequences to clipboard.");
+    statusBar.setText("Copied "+seqs.length+" sequences to clipboard.");
   }
 
   /**
@@ -1379,12 +1456,13 @@ public class AlignFrame
   }
 
   /**
-   * DOCUMENT ME!
+   * Paste contents of Jalview clipboard
    *
-   * @param newAlignment DOCUMENT ME!
+   * @param newAlignment true to paste to a new alignment, otherwise add to this.
    */
   void paste(boolean newAlignment)
   {
+    boolean externalPaste=true;
     try
     {
       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
@@ -1427,137 +1505,222 @@ public class AlignFrame
       }
 
       SequenceI[] sequences;
-
-      if (Desktop.jalviewClipboard != null)
-      {
-        // The clipboard was filled from within Jalview, we must use the sequences
-        // And dataset from the copied alignment
-        sequences = (SequenceI[]) Desktop.jalviewClipboard[0];
-      }
-      else
-      {
-        sequences = new FormatAdapter().readFile(str, "Paste", format).
-            getSequencesArray();
-      }
-
+      boolean annotationAdded = false;
       AlignmentI alignment = null;
 
-      if (newAlignment)
-      {
-        alignment = new Alignment(sequences);
-
-        if (Desktop.jalviewClipboard != null)
-        {
-          alignment.setDataset( (Alignment) Desktop.jalviewClipboard[1]);
-        }
-        else
-        {
-          alignment.setDataset(null);
-        }
-      }
-      else
-      {
-        alignment = viewport.getAlignment();
-
-        //!newAlignment
-        SequenceI[] newseqs = new SequenceI[sequences.length];
-        for (int i = 0; i < sequences.length; i++)
-        {
-          newseqs[i] = new Sequence(sequences[i].getName(),
-                                    sequences[i].getSequence(),
-                                    sequences[i].getStart(),
-                                    sequences[i].getEnd());
+     if(Desktop.jalviewClipboard!=null)
+     {
+       // The clipboard was filled from within Jalview, we must use the sequences
+       // And dataset from the copied alignment
+       SequenceI[] newseq = (SequenceI[])Desktop.jalviewClipboard[0];
+       // be doubly sure that we create *new* sequence objects.
+       sequences = new SequenceI[newseq.length];
+       for (int i=0;i<newseq.length;i++) {
+         sequences[i] = new Sequence(newseq[i]);
+       }
+       alignment = new Alignment(sequences);
+       externalPaste = false;
+     }
+     else
+     {
+       // parse the clipboard as an alignment.
+       alignment = new FormatAdapter().readFile(str, "Paste", format);
+       sequences = alignment.getSequencesArray();
+     }
 
-          alignment.addSequence(newseqs[i]);
-        }
+     int alwidth=0;
 
-        /*
-         //ADD HISTORY ITEM
-         */
-        addHistoryItem(new EditCommand(
-            "Add sequences",
-            EditCommand.PASTE,
-            newseqs,
-            0,
-            alignment.getWidth(),
-            alignment)
-            );
+     if (newAlignment)
+     {
 
-        viewport.setEndSeq(alignment.getHeight());
-        alignment.getWidth();
-        viewport.firePropertyChange("alignment", null, alignment.getSequences());
-      }
+       if (Desktop.jalviewClipboard != null)
+       {
+         // dataset is inherited
+         alignment.setDataset( (Alignment) Desktop.jalviewClipboard[1]);
+       }
+       else
+       {
+         // new dataset is constructed
+         alignment.setDataset(null);
+       }
+       alwidth = alignment.getWidth()+1;
+     }
+     else
+     {
+       AlignmentI pastedal = alignment; // preserve pasted alignment object
+       // Add pasted sequences and dataset into existing alignment.
+       alignment = viewport.getAlignment();
+       alwidth = alignment.getWidth()+1;
+        // decide if we need to import sequences from an existing dataset
+        boolean importDs = Desktop.jalviewClipboard != null
+                && Desktop.jalviewClipboard[1] != alignment.getDataset();
+        // importDs==true instructs us to copy over new dataset sequences from
+        // an existing alignment
+        Vector newDs = (importDs) ? new Vector() : null; // used to create
+                                                          // minimum dataset set
 
-      // Add any annotations attached to sequences
-      for (int i = 0; i < sequences.length; i++)
-      {
-        if (sequences[i].getAnnotation() != null)
+        for (int i = 0; i < sequences.length; i++)
         {
-          for (int a = 0; a < sequences[i].getAnnotation().length; a++)
+          if (importDs)
           {
-            AlignmentAnnotation newAnnot =
-                new AlignmentAnnotation(
-                    sequences[i].getAnnotation()[a].label,
-                    sequences[i].getAnnotation()[a].description,
-                    sequences[i].getAnnotation()[a].annotations,
-                    sequences[i].getAnnotation()[a].graphMin,
-                    sequences[i].getAnnotation()[a].graphMax,
-                    sequences[i].getAnnotation()[a].graph);
-
-            sequences[i].getAnnotation()[a] = newAnnot;
-            newAnnot.sequenceMapping = sequences[i].getAnnotation()[a].
-                sequenceMapping;
-            newAnnot.sequenceRef = sequences[i];
-            newAnnot.adjustForAlignment();
-            alignment.addAnnotation(newAnnot);
-            alignment.setAnnotationIndex(newAnnot, a);
+            newDs.addElement(null);
           }
-
-          alignPanel.annotationPanel.adjustPanelHeight();
-        }
-      }
-
-      if (newAlignment)
-      {
-        AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH, DEFAULT_HEIGHT);
-        String newtitle = new String("Copied sequences");
-
-        if (Desktop.jalviewClipboard != null && Desktop.jalviewClipboard[2] != null)
-        {
-          Vector hc = (Vector) Desktop.jalviewClipboard[2];
-          for (int i = 0; i < hc.size(); i++)
+          SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
+                                                            // paste
+          if (importDs && ds != null)
           {
-            int[] region = (int[]) hc.elementAt(i);
-            af.viewport.hideColumns(region[0], region[1]);
+            if (!newDs.contains(ds))
+            {
+              newDs.setElementAt(ds, i);
+              ds = new Sequence(ds);
+              // update with new dataset sequence
+              sequences[i].setDatasetSequence(ds);
+            }
+            else
+            {
+              ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
+            }
           }
+          else
+          {
+            // copy and derive new dataset sequence
+            sequences[i] = sequences[i].deriveSequence();
+            alignment.getDataset().addSequence(sequences[i].getDatasetSequence());
+            // TODO: avoid creation of duplicate dataset sequences with a
+            // 'contains' method using SequenceI.equals()/SequenceI.contains()
+          }
+          alignment.addSequence(sequences[i]); // merges dataset
         }
-
-        //>>>This is a fix for the moment, until a better solution is found!!<<<
-        af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().transferSettings(
-            alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
-
-        if (title.startsWith("Copied sequences"))
+        if (newDs != null)
         {
-          newtitle = title;
+          newDs.clear(); // tidy up
         }
-        else
-        {
-          newtitle = newtitle.concat("- from " + title);
+        if (pastedal.getAlignmentAnnotation()!=null) {
+          // Add any annotation attached to alignment.
+          AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
+          for (int i=0; i<alann.length; i++)
+          {
+            annotationAdded=true;
+            if (alann[i].sequenceRef==null && !alann[i].autoCalculated) {
+              AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
+              newann.padAnnotation(alwidth);
+              alignment.addAnnotation(newann);
+            }
+          }
         }
+     }
+     if (!newAlignment) {
+       ///////
+       // ADD HISTORY ITEM
+       //
+       addHistoryItem(new EditCommand(
+               "Add sequences",
+               EditCommand.PASTE,
+               sequences,
+               0,
+               alignment.getWidth(),
+               alignment)
+              );
+     }
+     // Add any annotations attached to sequences
+     for (int i = 0; i < sequences.length; i++)
+     {
+       if (sequences[i].getAnnotation() != null)
+       {
+         for (int a = 0; a < sequences[i].getAnnotation().length; a++)
+         {
+           annotationAdded=true;
+           sequences[i].getAnnotation()[a].adjustForAlignment();
+           sequences[i].getAnnotation()[a].padAnnotation(alwidth);
+           alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation was duplicated earlier
+           alignment.setAnnotationIndex(sequences[i].getAnnotation()[a], a);
+         }
+       }
+     }
+     if (!newAlignment) {
+
+       // propagate alignment changed.
+       viewport.setEndSeq(alignment.getHeight());
+       if (annotationAdded)
+       {
+         // Duplicate sequence annotation in all views.
+         AlignmentI[] alview = this.getViewAlignments();
+         for (int i = 0; i < sequences.length; i++)
+         {
+           AlignmentAnnotation sann[] = sequences[i].getAnnotation();
+           if (sann == null)
+             continue;
+           for (int avnum=0;avnum<alview.length; avnum++)
+           {
+             if (alview[avnum]!=alignment)
+             {
+               // duplicate in a view other than the one with input focus
+               int avwidth = alview[avnum].getWidth()+1;
+               // this relies on sann being preserved after we 
+               // modify the sequence's annotation array for each duplication
+               for (int a=0; a<sann.length; a++)
+               {
+                 AlignmentAnnotation newann = new AlignmentAnnotation(sann[a]);
+                 sequences[i].addAlignmentAnnotation(newann);
+                 newann.padAnnotation(avwidth);
+                 alview[avnum].addAnnotation(newann); // annotation was duplicated earlier
+                 alview[avnum].setAnnotationIndex(newann, a);
+               }
+             }
+           }
+         }
+         buildSortByAnnotationScoresMenu();
+       }
+       viewport.firePropertyChange("alignment", null, alignment.getSequences());
+
+     } else {
+       AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH, DEFAULT_HEIGHT);
+       String newtitle = new String("Copied sequences");
+
+       if(Desktop.jalviewClipboard!=null && Desktop.jalviewClipboard[2]!=null)
+         {
+           Vector hc = (Vector)Desktop.jalviewClipboard[2];
+           for(int i=0; i<hc.size(); i++)
+           {
+             int [] region = (int[]) hc.elementAt(i);
+             af.viewport.hideColumns(region[0], region[1]);
+           }
+         }
+
+
+       //>>>This is a fix for the moment, until a better solution is found!!<<<
+       af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().transferSettings(
+           alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
+
+       // TODO: maintain provenance of an alignment, rather than just make the title a concatenation of operations.
+       if (!externalPaste) {
+         if (title.startsWith("Copied sequences"))
+         {
+           newtitle = title;
+         }
+         else
+         {
+           newtitle = newtitle.concat("- from " + title);
+         }
+       } else {
+         newtitle = new String("Pasted sequences");
+       }
+
+       Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
+                                DEFAULT_HEIGHT);
 
-        Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
-                                 DEFAULT_HEIGHT);
+     }
 
-      }
 
     }
     catch (Exception ex)
     {
       ex.printStackTrace();
-      System.out.println("Exception whilst pasting: " + ex);
-      // could be anything being pasted in here
+        System.out.println("Exception whilst pasting: "+ex);
+        // could be anything being pasted in here
     }
 
+
   }
 
   /**
@@ -1593,34 +1756,38 @@ public class AlignFrame
       seqs.addElement(seq);
     }
 
-    // If the cut affects all sequences, remove highlighted columns
-    if (sg.getSize() == viewport.alignment.getHeight())
-    {
-      viewport.getColumnSelection().removeElements(sg.getStartRes(),
-          sg.getEndRes() + 1);
-    }
 
-    SequenceI[] cut = new SequenceI[seqs.size()];
-    for (int i = 0; i < seqs.size(); i++)
+   // If the cut affects all sequences, remove highlighted columns
+   if (sg.getSize() == viewport.alignment.getHeight())
+   {
+     viewport.getColumnSelection().removeElements(sg.getStartRes(),
+         sg.getEndRes() + 1);
+   }
+
+
+    SequenceI [] cut = new SequenceI[seqs.size()];
+    for(int i=0; i<seqs.size(); i++)
     {
-      cut[i] = (SequenceI) seqs.elementAt(i);
+      cut[i] = (SequenceI)seqs.elementAt(i);
     }
 
+
     /*
-         //ADD HISTORY ITEM
-     */
+    //ADD HISTORY ITEM
+    */
     addHistoryItem(new EditCommand("Cut Sequences",
-                                   EditCommand.CUT,
-                                   cut,
-                                   sg.getStartRes(),
-                                   sg.getEndRes() - sg.getStartRes() + 1,
-                                   viewport.alignment));
+                                      EditCommand.CUT,
+                                      cut,
+                                      sg.getStartRes(),
+                                      sg.getEndRes()-sg.getStartRes()+1,
+                                      viewport.alignment));
+
 
     viewport.setSelectionGroup(null);
     viewport.alignment.deleteGroup(sg);
 
     viewport.firePropertyChange("alignment", null,
-                                viewport.getAlignment().getSequences());
+                                  viewport.getAlignment().getSequences());
 
     if (viewport.getAlignment().getHeight() < 1)
     {
@@ -1676,7 +1843,7 @@ public class AlignFrame
    */
   public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
   {
-    if (viewport.cursorMode)
+    if(viewport.cursorMode)
     {
       alignPanel.seqPanel.keyboardNo1 = null;
       alignPanel.seqPanel.keyboardNo2 = null;
@@ -1723,6 +1890,7 @@ public class AlignFrame
     alignPanel.paintAlignment(true);
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -1740,7 +1908,7 @@ public class AlignFrame
    */
   public void remove2RightMenuItem_actionPerformed(ActionEvent e)
   {
-    trimAlignment(false);
+      trimAlignment(false);
   }
 
   void trimAlignment(boolean trimLeft)
@@ -1750,7 +1918,7 @@ public class AlignFrame
 
     if (colSel.size() > 0)
     {
-      if (trimLeft)
+      if(trimLeft)
       {
         column = colSel.getMin();
       }
@@ -1759,8 +1927,8 @@ public class AlignFrame
         column = colSel.getMax();
       }
 
-      SequenceI[] seqs;
-      if (viewport.getSelectionGroup() != null)
+      SequenceI [] seqs;
+      if(viewport.getSelectionGroup()!=null)
       {
         seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
             hiddenRepSequences);
@@ -1770,30 +1938,32 @@ public class AlignFrame
         seqs = viewport.alignment.getSequencesArray();
       }
 
+
       TrimRegionCommand trimRegion;
-      if (trimLeft)
+      if(trimLeft)
       {
         trimRegion = new TrimRegionCommand("Remove Left",
-                                           TrimRegionCommand.TRIM_LEFT,
-                                           seqs,
-                                           column,
-                                           viewport.alignment,
-                                           viewport.colSel,
-                                           viewport.selectionGroup);
+                                    TrimRegionCommand.TRIM_LEFT,
+                                    seqs,
+                                    column,
+                                    viewport.alignment,
+                                    viewport.colSel,
+                                    viewport.selectionGroup);
         viewport.setStartRes(0);
       }
-      else
-      {
-        trimRegion = new TrimRegionCommand("Remove Right",
-                                           TrimRegionCommand.TRIM_RIGHT,
-                                           seqs,
-                                           column,
-                                           viewport.alignment,
-                                           viewport.colSel,
-                                           viewport.selectionGroup);
-      }
+     else
+     {
+       trimRegion = new TrimRegionCommand("Remove Right",
+                                   TrimRegionCommand.TRIM_RIGHT,
+                                   seqs,
+                                   column,
+                                   viewport.alignment,
+                                   viewport.colSel,
+                                   viewport.selectionGroup);
+     }
+
+     statusBar.setText("Removed "+trimRegion.getSize()+" columns.");
 
-      statusBar.setText("Removed " + trimRegion.getSize() + " columns.");
 
       addHistoryItem(trimRegion);
 
@@ -1822,7 +1992,7 @@ public class AlignFrame
    */
   public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
   {
-    int start = 0, end = viewport.alignment.getWidth() - 1;
+    int start = 0, end = viewport.alignment.getWidth()-1;
 
     SequenceI[] seqs;
     if (viewport.getSelectionGroup() != null)
@@ -1837,6 +2007,7 @@ public class AlignFrame
       seqs = viewport.alignment.getSequencesArray();
     }
 
+
     RemoveGapColCommand removeGapCols =
         new RemoveGapColCommand("Remove Gapped Columns",
                                 seqs,
@@ -1845,18 +2016,18 @@ public class AlignFrame
 
     addHistoryItem(removeGapCols);
 
-    statusBar.setText("Removed " + removeGapCols.getSize() + " empty columns.");
+    statusBar.setText("Removed "+removeGapCols.getSize()+" empty columns.");
 
     //This is to maintain viewport position on first residue
     //of first sequence
     SequenceI seq = viewport.alignment.getSequenceAt(0);
     int startRes = seq.findPosition(viewport.startRes);
-    // ShiftList shifts;
-    // viewport.getAlignment().removeGaps(shifts=new ShiftList());
-    // edit.alColumnChanges=shifts.getInverse();
-    // if (viewport.hasHiddenColumns)
-    //   viewport.getColumnSelection().compensateForEdits(shifts);
-    viewport.setStartRes(seq.findIndex(startRes) - 1);
+   // ShiftList shifts;
+   // viewport.getAlignment().removeGaps(shifts=new ShiftList());
+   // edit.alColumnChanges=shifts.getInverse();
+   // if (viewport.hasHiddenColumns)
+   //   viewport.getColumnSelection().compensateForEdits(shifts);
+   viewport.setStartRes(seq.findIndex(startRes)-1);
     viewport.firePropertyChange("alignment", null,
                                 viewport.getAlignment().getSequences());
 
@@ -1869,7 +2040,7 @@ public class AlignFrame
    */
   public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
   {
-    int start = 0, end = viewport.alignment.getWidth() - 1;
+    int start = 0, end = viewport.alignment.getWidth()-1;
 
     SequenceI[] seqs;
     if (viewport.getSelectionGroup() != null)
@@ -1894,7 +2065,7 @@ public class AlignFrame
                                          start, end,
                                          viewport.alignment));
 
-    viewport.setStartRes(seq.findIndex(startRes) - 1);
+    viewport.setStartRes(seq.findIndex(startRes)-1);
 
     viewport.firePropertyChange("alignment", null,
                                 viewport.getAlignment().getSequences());
@@ -1930,6 +2101,8 @@ public class AlignFrame
     AlignmentPanel newap =
         new Jalview2XML().copyAlignPanel(alignPanel, true);
 
+    newap.av.gatherViewsHere = false;
+
     if (viewport.viewName == null)
     {
       viewport.viewName = "Original";
@@ -1939,33 +2112,33 @@ public class AlignFrame
     newap.av.redoList = viewport.redoList;
 
     int index = Desktop.getViewCount(viewport.getSequenceSetId());
-    String newViewName = "View " + index;
+    String newViewName = "View " +index;
 
     Vector comps = (Vector) PaintRefresher.components.get(viewport.
         getSequenceSetId());
     Vector existingNames = new Vector();
-    for (int i = 0; i < comps.size(); i++)
+    for(int i=0; i<comps.size(); i++)
     {
-      if (comps.elementAt(i) instanceof AlignmentPanel)
+      if(comps.elementAt(i) instanceof AlignmentPanel)
       {
-        AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
-        if (!existingNames.contains(ap.av.viewName))
+        AlignmentPanel ap = (AlignmentPanel)comps.elementAt(i);
+        if(!existingNames.contains(ap.av.viewName))
         {
           existingNames.addElement(ap.av.viewName);
-        }
       }
     }
+    }
 
-    while (existingNames.contains(newViewName))
+    while(existingNames.contains(newViewName))
     {
-      newViewName = "View " + (++index);
+      newViewName = "View "+ (++index);
     }
 
     newap.av.viewName = newViewName;
 
     addAlignmentPanel(newap, false);
 
-    if (alignPanels.size() == 2)
+    if(alignPanels.size()==2)
     {
       viewport.gatherViewsHere = true;
     }
@@ -1974,7 +2147,7 @@ public class AlignFrame
 
   public void expandViews_actionPerformed(ActionEvent e)
   {
-    Desktop.instance.explodeViews(this);
+        Desktop.instance.explodeViews(this);
   }
 
   public void gatherViews_actionPerformed(ActionEvent e)
@@ -1982,6 +2155,8 @@ public class AlignFrame
     Desktop.instance.gatherViews(this);
   }
 
+
+
   /**
    * DOCUMENT ME!
    *
@@ -1992,6 +2167,7 @@ public class AlignFrame
     new FontChooser(alignPanel);
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -2011,6 +2187,8 @@ public class AlignFrame
     alignPanel.paintAlignment(true);
   }
 
+
+
   /**
    * DOCUMENT ME!
    *
@@ -2131,10 +2309,11 @@ public class AlignFrame
     alignPanel.paintAlignment(true);
   }
 
+
   public FeatureSettings featureSettings;
   public void featureSettings_actionPerformed(ActionEvent e)
   {
-    if (featureSettings != null)
+    if(featureSettings !=null )
     {
       featureSettings.close();
       featureSettings = null;
@@ -2168,6 +2347,65 @@ public class AlignFrame
     alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
   }
 
+  public void alignmentProperties()
+  {
+    JEditorPane editPane = new JEditorPane("text/html","");
+    editPane.setEditable(false);
+    StringBuffer contents = new StringBuffer("<html>");
+
+    float avg  = 0;
+    int min=Integer.MAX_VALUE, max=0;
+    for(int i=0; i<viewport.alignment.getHeight(); i++)
+    {
+      int size = viewport.alignment.getSequenceAt(i).getEnd()
+          -viewport.alignment.getSequenceAt(i).getStart();
+      avg += size;
+      if(size>max)
+        max = size;
+      if(size<min)
+        min = size;
+    }
+    avg = avg/(float)viewport.alignment.getHeight();
+
+    contents.append("<br>Sequences: "+ viewport.alignment.getHeight());
+    contents.append("<br>Minimum Sequence Length: "+min);
+    contents.append("<br>Maximum Sequence Length: "+max);
+    contents.append("<br>Average Length: "+(int)avg);
+
+    if (((Alignment)viewport.alignment).getProperties() != null)
+    {
+      Hashtable props = ((Alignment)viewport.alignment).getProperties();
+      Enumeration en = props.keys();
+      contents.append("<br><br><table border=\"1\">");
+      while(en.hasMoreElements())
+      {
+        String key = en.nextElement().toString();
+        StringBuffer val = new StringBuffer();
+        String vals = props.get(key).toString();
+        int pos=0, npos;
+        do {
+          npos = vals.indexOf("\n",pos);
+          if (npos==-1)
+          {
+            val.append(vals.substring(pos));
+          } else {
+            val.append(vals.substring(pos, npos));
+            val.append("<br>");
+          }
+          pos = npos+1;
+        } while (npos!=-1);
+        contents.append("<tr><td>"+key+"</td><td>"+val+"</td></tr>");
+      }
+      contents.append("</table>");
+    }
+    editPane.setText(contents.toString()+"</html>");
+    JInternalFrame frame = new JInternalFrame();
+    frame.getContentPane().add(new JScrollPane(editPane));
+
+    Desktop.instance.addInternalFrame(frame,"Alignment Properties: "+getTitle(),500,400);
+  }
+
+
   /**
    * DOCUMENT ME!
    *
@@ -2311,6 +2549,7 @@ public class AlignFrame
     new AnnotationColourChooser(viewport, alignPanel);
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -2330,12 +2569,12 @@ public class AlignFrame
   {
     int threshold = 0;
 
-    if (cs != null)
+    if(cs!=null)
     {
       if (viewport.getAbovePIDThreshold())
       {
         threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
-            "Background");
+                                                   "Background");
 
         cs.setThreshold(threshold,
                         viewport.getIgnoreGapsConsensus());
@@ -2412,18 +2651,19 @@ public class AlignFrame
             || cs instanceof PIDColourScheme
             || cs instanceof Blosum62ColourScheme)
         {
-          sg.cs.setThreshold(threshold,
-                             viewport.getIgnoreGapsConsensus());
+         sg.cs.setThreshold(threshold,
+                viewport.getIgnoreGapsConsensus());
 
-          sg.cs.setConsensus(AAFrequency.calculate(
-              sg.getSequences(viewport.hiddenRepSequences), sg.getStartRes(),
-              sg.getEndRes() + 1));
-        }
+         sg.cs.setConsensus(AAFrequency.calculate(
+             sg.getSequences(viewport.hiddenRepSequences), sg.getStartRes(),
+             sg.getEndRes()+1));
+       }
         else
         {
           sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
         }
 
+
         if (viewport.getConservationSelected())
         {
           Conservation c = new Conservation("Group",
@@ -2431,7 +2671,7 @@ public class AlignFrame
                                             sg.getSequences(viewport.
               hiddenRepSequences),
                                             sg.getStartRes(),
-                                            sg.getEndRes() + 1);
+                                            sg.getEndRes()+1);
           c.calculate();
           c.verdict(false, viewport.ConsPercGaps);
           sg.cs.setConservation(c);
@@ -2439,9 +2679,9 @@ public class AlignFrame
         else
         {
           sg.cs.setConservation(null);
-        }
       }
     }
+    }
 
     if (alignPanel.getOverviewPanel() != null)
     {
@@ -2461,7 +2701,7 @@ public class AlignFrame
    */
   protected void modifyPID_actionPerformed(ActionEvent e)
   {
-    if (viewport.getAbovePIDThreshold() && viewport.globalColourScheme != null)
+    if (viewport.getAbovePIDThreshold() && viewport.globalColourScheme!=null)
     {
       SliderPanel.setPIDSliderSource(alignPanel,
                                      viewport.getGlobalColourScheme(),
@@ -2477,7 +2717,7 @@ public class AlignFrame
    */
   protected void modifyConservation_actionPerformed(ActionEvent e)
   {
-    if (viewport.getConservationSelected() && viewport.globalColourScheme != null)
+    if (viewport.getConservationSelected() && viewport.globalColourScheme!=null)
     {
       SliderPanel.setConservationSlider(alignPanel,
                                         viewport.globalColourScheme,
@@ -2566,37 +2806,37 @@ public class AlignFrame
             nextElement().toString());
         radioItem.setName("USER_DEFINED");
         radioItem.addMouseListener(new MouseAdapter()
-        {
-          public void mousePressed(MouseEvent evt)
-          {
-            if (evt.isControlDown() || SwingUtilities.isRightMouseButton(evt))
             {
-              radioItem.removeActionListener(radioItem.getActionListeners()[0]);
+              public void mousePressed(MouseEvent evt)
+              {
+                if(evt.isControlDown() || SwingUtilities.isRightMouseButton(evt))
+                {
+                  radioItem.removeActionListener(radioItem.getActionListeners()[0]);
 
               int option = JOptionPane.showInternalConfirmDialog(jalview.gui.
                   Desktop.desktop,
-                  "Remove from default list?",
-                  "Remove user defined colour",
-                  JOptionPane.YES_NO_OPTION);
-              if (option == JOptionPane.YES_OPTION)
-              {
+                      "Remove from default list?",
+                      "Remove user defined colour",
+                      JOptionPane.YES_NO_OPTION);
+                  if(option == JOptionPane.YES_OPTION)
+                  {
                 jalview.gui.UserDefinedColours.removeColourFromDefaults(
                     radioItem.getText());
-                colourMenu.remove(radioItem);
-              }
-              else
-              {
-                radioItem.addActionListener(new ActionListener()
-                {
-                  public void actionPerformed(ActionEvent evt)
-                  {
-                    userDefinedColour_actionPerformed(evt);
+                    colourMenu.remove(radioItem);
                   }
-                });
+                  else
+              {
+                    radioItem.addActionListener(new ActionListener()
+                    {
+                      public void actionPerformed(ActionEvent evt)
+                      {
+                        userDefinedColour_actionPerformed(evt);
+                      }
+                    });
+                }
               }
-            }
           }
-        });
+            });
         radioItem.addActionListener(new ActionListener()
         {
           public void actionPerformed(ActionEvent evt)
@@ -2638,9 +2878,9 @@ public class AlignFrame
    */
   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
   {
-    SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
+    SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
     AlignmentSorter.sortByPID(viewport.getAlignment(),
-                              viewport.getAlignment().getSequenceAt(0));
+                              viewport.getAlignment().getSequenceAt(0), null);
     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
                                     viewport.alignment));
     alignPanel.paintAlignment(true);
@@ -2653,7 +2893,7 @@ public class AlignFrame
    */
   public void sortIDMenuItem_actionPerformed(ActionEvent e)
   {
-    SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
+    SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
     AlignmentSorter.sortByID(viewport.getAlignment());
     addHistoryItem(new OrderCommand("ID Sort", oldOrder, viewport.alignment));
     alignPanel.paintAlignment(true);
@@ -2666,13 +2906,12 @@ public class AlignFrame
    */
   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
   {
-    SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
+    SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
     AlignmentSorter.sortByGroup(viewport.getAlignment());
     addHistoryItem(new OrderCommand("Group Sort", oldOrder, viewport.alignment));
 
     alignPanel.paintAlignment(true);
   }
-
   /**
    * DOCUMENT ME!
    *
@@ -2683,6 +2922,7 @@ public class AlignFrame
     new RedundancyPanel(alignPanel, this);
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -2727,13 +2967,14 @@ public class AlignFrame
       return;
     }
 
-    new PCAPanel(alignPanel);
+     new PCAPanel(alignPanel);
   }
 
+
   public void autoCalculate_actionPerformed(ActionEvent e)
   {
     viewport.autoCalculateConsensus = autoCalculate.isSelected();
-    if (viewport.autoCalculateConsensus)
+    if(viewport.autoCalculateConsensus)
     {
       viewport.firePropertyChange("alignment",
                                   null,
@@ -2741,6 +2982,7 @@ public class AlignFrame
     }
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -2841,7 +3083,7 @@ public class AlignFrame
         return;
       }
 
-      if (viewport.alignment.getHeight() < 2)
+      if(viewport.alignment.getHeight()<2)
       {
         return;
       }
@@ -2851,9 +3093,9 @@ public class AlignFrame
 
     title += " from ";
 
-    if (viewport.viewName != null)
+    if(viewport.viewName!=null)
     {
-      title += viewport.viewName + " of ";
+      title+= viewport.viewName+" of ";
     }
 
     title += this.title;
@@ -2875,7 +3117,7 @@ public class AlignFrame
     {
       public void actionPerformed(ActionEvent e)
       {
-        SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
+        SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
 
         // TODO: JBPNote - have to map order entries to curent SequenceI pointers
         AlignmentSorter.sortBy(viewport.getAlignment(), order);
@@ -2887,6 +3129,73 @@ public class AlignFrame
       }
     });
   }
+  /**
+   * Add a new sort by annotation score menu item
+   * @param sort the menu to add the option to
+   * @param scoreLabel the label used to retrieve scores for each sequence on the alignment
+   */
+  public void addSortByAnnotScoreMenuItem(JMenu sort, final String scoreLabel)
+  {
+    final JMenuItem item = new JMenuItem(scoreLabel);
+    sort.add(item);
+    item.addActionListener(new java.awt.event.ActionListener()
+    {
+      public void actionPerformed(ActionEvent e)
+      {
+        SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
+        AlignmentSorter.sortByAnnotationScore(scoreLabel, viewport.getAlignment());//,viewport.getSelectionGroup());
+        addHistoryItem(new OrderCommand("Sort by "+scoreLabel, oldOrder, viewport.alignment));
+        alignPanel.paintAlignment(true);
+      }
+    });
+  }
+  /**
+   * last hash for alignment's annotation array - used to minimise cost of rebuild.
+   */
+  protected int _annotationScoreVectorHash;
+  /**
+   * search the alignment and rebuild the sort by annotation score submenu
+   * the last alignment annotation vector hash is stored to minimize
+   * cost of rebuilding in subsequence calls.
+   *
+   */
+  public void buildSortByAnnotationScoresMenu()
+  {
+    if(viewport.alignment.getAlignmentAnnotation()==null)
+    {
+      return;
+    }
+
+    if (viewport.alignment.getAlignmentAnnotation().hashCode()!=_annotationScoreVectorHash)
+    {
+      sortByAnnotScore.removeAll();
+      // almost certainly a quicker way to do this - but we keep it simple
+      Hashtable scoreSorts=new Hashtable();
+      AlignmentAnnotation aann[];
+      Enumeration sq = viewport.alignment.getSequences().elements();
+      while (sq.hasMoreElements())
+      {
+        aann = ((SequenceI) sq.nextElement()).getAnnotation();
+        for (int i=0;aann!=null && i<aann.length; i++)
+        {
+          if (aann[i].hasScore() && aann[i].sequenceRef!=null)
+          {
+            scoreSorts.put(aann[i].label, aann[i].label);
+          }
+        }
+      }
+      Enumeration labels = scoreSorts.keys();
+      while (labels.hasMoreElements())
+      {
+        addSortByAnnotScoreMenuItem(sortByAnnotScore, (String) labels.nextElement());
+      }
+      sortByAnnotScore.setVisible(scoreSorts.size()>0);
+      scoreSorts.clear();
+
+      _annotationScoreVectorHash =
+          viewport.alignment.getAlignmentAnnotation().hashCode();
+    }
+  }
 
   /**
    * Maintain the Order by->Displayed Tree menu.
@@ -2905,9 +3214,9 @@ public class AlignFrame
         getSequenceSetId());
     Vector treePanels = new Vector();
     int i, iSize = comps.size();
-    for (i = 0; i < iSize; i++)
+    for(i=0; i<iSize; i++)
     {
-      if (comps.elementAt(i) instanceof TreePanel)
+      if(comps.elementAt(i) instanceof TreePanel)
       {
         treePanels.add(comps.elementAt(i));
       }
@@ -2915,7 +3224,7 @@ public class AlignFrame
 
     iSize = treePanels.size();
 
-    if (iSize < 1)
+    if(iSize<1)
     {
       sortByTreeMenu.setVisible(false);
       return;
@@ -2923,11 +3232,11 @@ public class AlignFrame
 
     sortByTreeMenu.setVisible(true);
 
-    for (i = 0; i < treePanels.size(); i++)
+    for(i=0; i<treePanels.size(); i++)
     {
-      TreePanel tp = (TreePanel) treePanels.elementAt(i);
+      TreePanel tp = (TreePanel)treePanels.elementAt(i);
       final JMenuItem item = new JMenuItem(tp.getTitle());
-      final NJTree tree = ( (TreePanel) treePanels.elementAt(i)).getTree();
+      final NJTree tree = ((TreePanel)treePanels.elementAt(i)).getTree();
       item.addActionListener(new java.awt.event.ActionListener()
       {
         public void actionPerformed(ActionEvent e)
@@ -2962,27 +3271,28 @@ public class AlignFrame
     {
       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to some common interface!
       /*SequenceGroup seqs = viewport.getSelectionGroup();
-             int sz;
-             msa = new SequenceI[sz = seqs.getSize(false)];
+      int sz;
+      msa = new SequenceI[sz = seqs.getSize(false)];
 
-             for (int i = 0; i < sz; i++)
-             {
+      for (int i = 0; i < sz; i++)
+      {
         msa[i] = (SequenceI) seqs.getSequenceAt(i);
-             } */
+      } */
       msa = viewport.getAlignmentView(true);
     }
     else
     {
       /*Vector seqs = viewport.getAlignment().getSequences();
-             if (seqs.size() > 1)
-             {
+
+      if (seqs.size() > 1)
+      {
         msa = new SequenceI[seqs.size()];
 
         for (int i = 0; i < seqs.size(); i++)
         {
           msa[i] = (SequenceI) seqs.elementAt(i);
         }
-             }*/
+      }*/
       msa = viewport.getAlignmentView(false);
     }
     return msa;
@@ -2996,7 +3306,7 @@ public class AlignFrame
    */
   AlignmentView gatherSeqOrMsaForSecStrPrediction()
   {
-    AlignmentView seqs = null;
+   AlignmentView seqs = null;
 
     if ( (viewport.getSelectionGroup() != null) &&
         (viewport.getSelectionGroup().getSize() > 0))
@@ -3016,7 +3326,6 @@ public class AlignFrame
     }
     return seqs;
   }
-
   /**
    * DOCUMENT ME!
    *
@@ -3038,33 +3347,41 @@ public class AlignFrame
     {
       String choice = chooser.getSelectedFile().getPath();
       jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
-
+      jalview.io.NewickFile fin = null;
       try
       {
-        jalview.io.NewickFile fin = new jalview.io.NewickFile(choice,
+        fin = new jalview.io.NewickFile(choice,
             "File");
         viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
       }
       catch (Exception ex)
       {
         JOptionPane.showMessageDialog(Desktop.desktop,
-                                      "Problem reading tree file",
                                       ex.getMessage(),
+                                      "Problem reading tree file",
                                       JOptionPane.WARNING_MESSAGE);
         ex.printStackTrace();
       }
+      if (fin!=null && fin.hasWarningMessage())
+      {
+        JOptionPane.showMessageDialog(Desktop.desktop,
+                fin.getWarningMessage(),
+                "Possible problem with tree file",
+                JOptionPane.WARNING_MESSAGE);
+      }
     }
   }
 
+
   public TreePanel ShowNewickTree(NewickFile nf, String title)
   {
-    return ShowNewickTree(nf, title, 600, 500, 4, 5);
+    return ShowNewickTree(nf,title,600,500,4,5);
   }
 
   public TreePanel ShowNewickTree(NewickFile nf, String title,
                                   AlignmentView input)
   {
-    return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
+    return ShowNewickTree(nf,title, input, 600,500,4,5);
   }
 
   public TreePanel ShowNewickTree(NewickFile nf, String title, int w, int h,
@@ -3072,7 +3389,6 @@ public class AlignFrame
   {
     return ShowNewickTree(nf, title, null, w, h, x, y);
   }
-
   /**
    * Add a treeviewer for the tree extracted from a newick file object to the current alignment view
    *
@@ -3102,13 +3418,14 @@ public class AlignFrame
                            title,
                            nf, input);
 
-        tp.setSize(w, h);
+        tp.setSize(w,h);
 
-        if (x > 0 && y > 0)
+        if(x>0 && y>0)
         {
-          tp.setLocation(x, y);
+          tp.setLocation(x,y);
         }
 
+
         Desktop.addInternalFrame(tp, title, w, h);
       }
     }
@@ -3116,16 +3433,22 @@ public class AlignFrame
     {
       ex.printStackTrace();
     }
-
+    
     return tp;
   }
 
+
   /**
    * Generates menu items and listener event actions for web service clients
    *
    */
   public void BuildWebServiceMenu()
   {
+    // TODO: add support for context dependent disabling of services based on alignment and current selection
+    // TODO: refactor to allow list of AbstractName/Handler bindings to be stored or retrieved from elsewhere
+    // TODO: add additional serviceHandle parameter to specify abstract handler class independently of AbstractName
+    // TODO: add in rediscovery GUI function to restart discoverer
+    // TODO: group services by location as well as function and/or introduce object broker mechanism.
     if ( (Discoverer.services != null)
         && (Discoverer.services.size() > 0))
     {
@@ -3160,7 +3483,7 @@ public class AlignFrame
           if (sh.getName().indexOf("lustal") > -1)
           {
             // We know that ClustalWS can accept partial alignments for refinement.
-            final JMenuItem methodR = new JMenuItem(sh.getName() + " Realign");
+            final JMenuItem methodR = new JMenuItem(sh.getName()+" Realign");
             methodR.addActionListener(new ActionListener()
             {
               public void actionPerformed(ActionEvent e)
@@ -3205,7 +3528,7 @@ public class AlignFrame
                 {
                   // Sequence profile based prediction
                   new jalview.ws.JPredClient(sh,
-                                             title, true, msa, af, true);
+                      title, true, msa, af, true);
                 }
               }
             }
@@ -3214,7 +3537,7 @@ public class AlignFrame
         }
         wsmenu.add(secstrmenu);
       }
-      this.webService.removeAll();
+      resetWebServiceMenu();
       for (int i = 0, j = wsmenu.size(); i < j; i++)
       {
         webService.add( (JMenu) wsmenu.get(i));
@@ -3222,152 +3545,266 @@ public class AlignFrame
     }
     else
     {
-      this.webService.removeAll();
+      resetWebServiceMenu();
       this.webService.add(this.webServiceNoServices);
     }
-    // TODO: add in rediscovery function
-    // TODO: reduce code redundancy.
-    // TODO: group services by location as well as function.
   }
 
-  /* public void vamsasStore_actionPerformed(ActionEvent e)
-   {
-     JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
-         getProperty("LAST_DIRECTORY"));
 
-     chooser.setFileView(new JalviewFileView());
-     chooser.setDialogTitle("Export to Vamsas file");
-     chooser.setToolTipText("Export");
+  /**
+   * empty the web service menu and add any ad-hoc functions
+   * not dynamically discovered.
+   *
+   */
+  private void resetWebServiceMenu()
+  {
+    webService.removeAll();
+    // Temporary hack - DBRef Fetcher always top level ws entry.
+    JMenuItem rfetch = new JMenuItem("Fetch DB References");
+    rfetch.setToolTipText("Retrieve and parse uniprot records for the alignment or the currently selected sequences");
+    webService.add(rfetch);
+    rfetch.addActionListener(new ActionListener() {
 
-     int value = chooser.showSaveDialog(this);
+      public void actionPerformed(ActionEvent e)
+      {
+        new jalview.ws.DBRefFetcher(
+                alignPanel.av.getSequenceSelection(),
+                alignPanel.alignFrame).fetchDBRefs(false);
+      }
 
-     if (value == JalviewFileChooser.APPROVE_OPTION)
-     {
-   jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
-       //vs.store(chooser.getSelectedFile().getAbsolutePath()   );
-       vs.storeJalview( chooser.getSelectedFile().getAbsolutePath(), this);
-     }
-   }*/
+    });
+  }
 
+ /* public void vamsasStore_actionPerformed(ActionEvent e)
+  {
+    JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
+        getProperty("LAST_DIRECTORY"));
 
+    chooser.setFileView(new JalviewFileView());
+    chooser.setDialogTitle("Export to Vamsas file");
+    chooser.setToolTipText("Export");
 
+    int value = chooser.showSaveDialog(this);
 
-  public void showTranslation_actionPerformed(ActionEvent e)
+    if (value == JalviewFileChooser.APPROVE_OPTION)
+    {
+      jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
+      //vs.store(chooser.getSelectedFile().getAbsolutePath()   );
+      vs.storeJalview( chooser.getSelectedFile().getAbsolutePath(), this);
+    }
+  }*/
+  /**
+   * prototype of an automatically enabled/disabled analysis function
+   *
+   */
+  protected void setShowProductsEnabled()
   {
-    SequenceI[] selection = viewport.getSelectionAsNewSequence();
-    String[] seqstring = viewport.getViewAsString(true);
-
-    int s, sSize = selection.length;
-    SequenceI[] newSeq = new SequenceI[sSize];
+    SequenceI [] selection = viewport.getSequenceSelection();
+    if (canShowProducts(selection, viewport.getSelectionGroup()!=null, viewport.getAlignment().getDataset()))
+    {
+      showProducts.setEnabled(true);
+      
+    } else {
+      showProducts.setEnabled(false);
+    }
+  }
+  /**
+   * search selection for sequence xRef products and build the
+   * show products menu.
+   * @param selection
+   * @param dataset
+   * @return true if showProducts menu should be enabled.
+   */
+  public boolean canShowProducts(SequenceI[] selection, boolean isRegionSelection, Alignment dataset)
+  {
+    boolean showp=false;
+    try {
+      showProducts.removeAll();
+      final boolean dna = viewport.getAlignment().isNucleotide();
+      final Alignment ds = dataset;
+      String[] ptypes = CrossRef.findSequenceXrefTypes(dna, selection, dataset);
+      //Object[] prods = CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(), selection, dataset, true);
+      final SequenceI[] sel = selection;
+      for (int t=0; ptypes!=null && t<ptypes.length; t++)
+      {
+        showp=true;
+        final boolean isRegSel = isRegionSelection;
+        final AlignFrame af = this;
+        final String source = ptypes[t];
+        JMenuItem xtype = new JMenuItem(ptypes[t]);
+        xtype.addActionListener(new ActionListener() {
 
-    int res, resSize;
-    StringBuffer protein;
-    String seq;
-    for (s = 0; s < sSize; s++)
+          public void actionPerformed(ActionEvent e)
+          {
+            // TODO: new thread for this call with vis-delay
+            af.showProductsFor(sel, ds, isRegSel, dna, source);
+          }
+          
+        });
+        showProducts.add(xtype);
+      }
+      showProducts.setVisible(showp);
+      showProducts.setEnabled(showp);
+    } catch (Exception e)
     {
-      protein = new StringBuffer();
-      seq = AlignSeq.extractGaps("-. ", seqstring[s]);
-      resSize = seq.length();
-      resSize -= resSize % 3;
+      jalview.bin.Cache.log.warn("canTranslate threw an exception - please report to help@jalview.org",e);
+     return false;
+    }
+    return showp;
+  }
+protected void showProductsFor(SequenceI[] sel, Alignment ds, boolean isRegSel, boolean dna, String source)
+  {
+  final boolean fisRegSel = isRegSel;
+  final boolean fdna = dna;
+  final String fsrc = source;
+  final AlignFrame ths = this;
+  final SequenceI[] fsel = sel;
+  Runnable foo = new Runnable() {
 
-      for (res = 0; res < resSize; res += 3)
+    public void run()
+    {
+      final long sttime = System.currentTimeMillis();
+      ths.setProgressBar("Searching for sequences from "+fsrc, sttime);
+      try {
+        Alignment ds = ths.getViewport().alignment.getDataset(); // update our local dataset reference
+      Alignment prods = CrossRef.findXrefSequences(fsel, fdna, fsrc, ds);
+      if (prods!=null)
       {
-        String codon = seq.substring(res, res + 3);
-        codon = codon.replace('U', 'T');
-        String aa = ResidueProperties.codonTranslate(codon);
-        if (aa == null)
-        {
-          protein.append(viewport.getGapCharacter());
-        }
-        else if (aa.equals("STOP"))
+        SequenceI[] sprods = new SequenceI[prods.getHeight()];
+        for (int s=0; s<sprods.length;s++)
         {
-          protein.append("X");
+          sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
+          if (ds.getSequences()==null || !ds.getSequences().contains(sprods[s].getDatasetSequence()))
+            ds.addSequence(sprods[s].getDatasetSequence());
+          sprods[s].updatePDBIds();
         }
-        else
+        Alignment al = new Alignment(sprods);
+        AlignedCodonFrame[] cf = prods.getCodonFrames();
+        for (int s=0; cf!=null && s<cf.length; s++)
         {
-          protein.append(aa);
+          al.addCodonFrame(cf[s]);
+          cf[s] = null;
         }
+        al.setDataset(ds);
+        AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
+        String newtitle =""+((fdna) ? "Proteins " : "Nucleotides ") + " for "+((fisRegSel) ? "selected region of " : "")
+                + getTitle();
+        Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
+                DEFAULT_HEIGHT);
+      } else {
+        System.err.println("No Sequences generated for xRef type "+fsrc);
       }
-      newSeq[s] = new Sequence(selection[s].getName(),
-                               protein.toString());
-    }
-
-    AlignmentI al = new Alignment(newSeq);
-    al.setDataset(null);
-
-    ////////////////////////////////
-    // Copy annotations across
-    jalview.datamodel.AlignmentAnnotation[] annotations
-        = viewport.alignment.getAlignmentAnnotation();
-    int a, aSize;
-    if (annotations != null)
-    {
-      for (int i = 0; i < annotations.length; i++)
+      }
+      catch (Exception e)
       {
-        if (annotations[i] == viewport.quality ||
-            annotations[i] == viewport.conservation ||
-            annotations[i] == viewport.consensus)
-        {
-          System.out.println("COPT HERE");
-          continue;
-        }
-
-        aSize = viewport.alignment.getWidth() / 3;
-        jalview.datamodel.Annotation[] anots =
-            new jalview.datamodel.Annotation[aSize];
+        jalview.bin.Cache.log.error("Exception when finding crossreferences",e);
+      }
+      catch (Error e)
+      {
+        jalview.bin.Cache.log.error("Error when finding crossreferences",e);
+      }
+      ths.setProgressBar("Finished searching for sequences from "+fsrc, sttime);
+    }
+    
+  };
+  Thread frunner = new Thread(foo);
+  frunner.start();
+  }
 
-        for (a = 0; a < viewport.alignment.getWidth(); a++)
-        {
-          if (annotations[i].annotations[a] == null
-              || annotations[i].annotations[a] == null)
-          {
-            continue;
-          }
 
-          anots[a / 3] = new Annotation(
-              annotations[i].annotations[a].displayCharacter,
-              annotations[i].annotations[a].description,
-              annotations[i].annotations[a].secondaryStructure,
-              annotations[i].annotations[a].value,
-              annotations[i].annotations[a].colour);
-        }
+public boolean canShowTranslationProducts(SequenceI[] selection, AlignmentI alignment)
+{
+  // old way
+  try {
+      return (jalview.analysis.Dna.canTranslate(selection, viewport.getViewAsVisibleContigs(true)));
+  } catch (Exception e)
+  {
+    jalview.bin.Cache.log.warn("canTranslate threw an exception - please report to help@jalview.org",e);
+   return false;
+  }
+}
 
-        jalview.datamodel.AlignmentAnnotation aa
-            = new jalview.datamodel.AlignmentAnnotation(annotations[i].label,
-            annotations[i].description, anots);
-        al.addAnnotation(aa);
-      }
+public void showProducts_actionPerformed(ActionEvent e)
+{
+  ///////////////////////////////
+  // Collect Data to be translated/transferred
+  
+  SequenceI [] selection = viewport.getSequenceSelection();
+  AlignmentI al  = null;
+  try {
+      al = jalview.analysis.Dna.CdnaTranslate(selection, viewport.getViewAsVisibleContigs(true),
+          viewport.getGapCharacter(), viewport.getAlignment().getDataset());
+    } catch (Exception ex) {
+      al = null;
+      jalview.bin.Cache.log.debug("Exception during translation.",ex);
+    }
+    if (al==null)
+    {
+      JOptionPane.showMessageDialog(Desktop.desktop,
+          "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
+          "Translation Failed",
+          JOptionPane.WARNING_MESSAGE);
+    } else {
+      AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
+      Desktop.addInternalFrame(af, "Translation of "+this.getTitle(),
+                               DEFAULT_WIDTH,
+                               DEFAULT_HEIGHT);
     }
+  }
 
+public void showTranslation_actionPerformed(ActionEvent e)
+{
+  ///////////////////////////////
+  // Collect Data to be translated/transferred
+
+  SequenceI [] selection = viewport.getSequenceSelection();
+  String [] seqstring = viewport.getViewAsString(true);
+  AlignmentI al  = null;
+  try {
+    al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring, viewport.getViewAsVisibleContigs(true),
+        viewport.getGapCharacter(), viewport.alignment.getAlignmentAnnotation(),
+        viewport.alignment.getWidth(), viewport.getAlignment().getDataset());
+  } catch (Exception ex) {
+    al = null;
+    jalview.bin.Cache.log.debug("Exception during translation.",ex);
+  }
+  if (al==null)
+  {
+    JOptionPane.showMessageDialog(Desktop.desktop,
+        "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
+        "Translation Failed",
+        JOptionPane.WARNING_MESSAGE);
+  } else {
     AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
-    Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
+    Desktop.addInternalFrame(af, "Translation of "+this.getTitle(),
                              DEFAULT_WIDTH,
                              DEFAULT_HEIGHT);
-
   }
+}
 
-  /**
-   * DOCUMENT ME!
-   *
-   * @param String DOCUMENT ME!
-   */
-  public boolean parseFeaturesFile(String file, String type)
-  {
+/**
+ * Try to load a features file onto the alignment.
+ * @param file contents or path to retrieve file 
+ * @param type access mode of file (see jalview.io.AlignFile)
+ * @return true if features file was parsed corectly.
+ */
+public boolean parseFeaturesFile(String file, String type)
+{
     boolean featuresFile = false;
     try
     {
       featuresFile = new FeaturesFile(file,
           type).parse(viewport.alignment.getDataset(),
-                      alignPanel.seqPanel.seqCanvas.
-                      getFeatureRenderer().featureColours,
-                      false);
+                                         alignPanel.seqPanel.seqCanvas.
+                                         getFeatureRenderer().featureColours,
+                                         false);
     }
-    catch (Exception ex)
+    catch(Exception ex)
     {
       ex.printStackTrace();
     }
 
-    if (featuresFile)
+    if(featuresFile)
     {
       viewport.showSequenceFeatures = true;
       showSeqFeatures.setSelected(true);
@@ -3375,22 +3812,22 @@ public class AlignFrame
     }
 
     return featuresFile;
-  }
+}
 
-  public void dragEnter(DropTargetDragEvent evt)
-  {}
+public void dragEnter(DropTargetDragEvent evt)
+{}
 
-  public void dragExit(DropTargetEvent evt)
-  {}
+public void dragExit(DropTargetEvent evt)
+{}
 
-  public void dragOver(DropTargetDragEvent evt)
-  {}
+public void dragOver(DropTargetDragEvent evt)
+{}
 
-  public void dropActionChanged(DropTargetDragEvent evt)
-  {}
+public void dropActionChanged(DropTargetDragEvent evt)
+{}
 
-  public void drop(DropTargetDropEvent evt)
-  {
+public void drop(DropTargetDropEvent evt)
+{
     Transferable t = evt.getTransferable();
     java.util.List files = null;
 
@@ -3448,14 +3885,17 @@ public class AlignFrame
         ex.printStackTrace();
       }
     }
-  }
+}
 
-  // This method will attempt to load a "dropped" file first by testing
-  // whether its and Annotation file, then features file. If both are
-  // false then the user may have dropped an alignment file onto this
-  // AlignFrame
-  public void loadJalviewDataFile(String file)
-  {
+  /**     
+   * Attempt to load a "dropped" file: First by testing
+   * whether it's and Annotation file, then a JNet file, and finally a features file. If all are
+   * false then the user may have dropped an alignment file onto this
+   * AlignFrame.
+   * @param file either a filename or a URL string.
+   */
+   public void loadJalviewDataFile(String file)
+   {
     try
     {
       String protocol = "File";
@@ -3470,33 +3910,37 @@ public class AlignFrame
 
       if (!isAnnotation)
       {
-        boolean isGroupsFile = parseFeaturesFile(file, protocol);
-        if (!isGroupsFile)
+        // try to see if its a JNet 'concise' style annotation file *before* we try to parse it as a features file
+        String format = new IdentifyFile().Identify(file, protocol);
+        if(format.equalsIgnoreCase("JnetFile"))
         {
-          String format = new IdentifyFile().Identify(file, protocol);
-
-          if (format.equalsIgnoreCase("JnetFile"))
-          {
-            jalview.io.JPredFile predictions = new jalview.io.JPredFile(
-                file, protocol);
-            new JnetAnnotationMaker().add_annotation(predictions,
+          jalview.io.JPredFile predictions = new jalview.io.JPredFile(
+                  file, protocol);
+          new JnetAnnotationMaker().add_annotation(predictions,
                 viewport.getAlignment(),
                 0, false);
-            alignPanel.adjustAnnotationHeight();
-            alignPanel.paintAlignment(true);
-          }
-          else
+          isAnnotation=true;
+        }
+        else
+        {
+          // try to parse it as a features file
+          boolean isGroupsFile = parseFeaturesFile(file,protocol);
+          // if it wasn't a features file then we just treat it as a general alignment file to load into the current view.
+          if (!isGroupsFile)
           {
             new FileLoader().LoadFile(viewport, file, protocol, format);
+          } else {
+            alignPanel.paintAlignment(true);
           }
         }
       }
-      else
+      if (isAnnotation)
       {
-        // (isAnnotation)
+        
         alignPanel.adjustAnnotationHeight();
+        buildSortByAnnotationScoresMenu();
+        alignPanel.paintAlignment(true);
       }
-
     }
     catch (Exception ex)
     {
@@ -3516,7 +3960,7 @@ public class AlignFrame
 
   public void tabbedPane_mousePressed(MouseEvent e)
   {
-    if (SwingUtilities.isRightMouseButton(e))
+    if(SwingUtilities.isRightMouseButton(e))
     {
       String reply = JOptionPane.showInternalInputDialog(this,
           "Enter View Name",
@@ -3526,15 +3970,29 @@ public class AlignFrame
       if (reply != null)
       {
         viewport.viewName = reply;
-        tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
+        tabbedPane.setTitleAt( tabbedPane.getSelectedIndex() ,reply);
       }
     }
   }
 
+
   public AlignViewport getCurrentView()
   {
     return viewport;
   }
+
+
+  /**
+   * Open the dialog for regex description parsing.
+   */
+  protected void extractScores_actionPerformed(ActionEvent e)
+  {
+    ParseProperties pp = new jalview.analysis.ParseProperties(viewport.alignment);
+    if (pp.getScoresFromDescription("col", "score column ", "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)", true)>0)
+    {
+      buildSortByAnnotationScoresMenu();
+    }
+  }
 }
 
 class PrintThread
@@ -3543,9 +4001,8 @@ class PrintThread
   AlignmentPanel ap;
   public PrintThread(AlignmentPanel ap)
   {
-    this.ap = ap;
+   this.ap = ap;
   }
-
   static PageFormat pf;
   public void run()
   {