ensure current dataset reference is passed to the crossReference search method
[jalview.git] / src / jalview / gui / AlignFrame.java
index b2d41e8..6302efb 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,13 @@ public class AlignFrame
 
   Vector alignPanels = new Vector();
 
+
   /** DOCUMENT ME!! */
   String currentFileFormat = null;
 
   String fileName = null;
 
+
   /**
    * Creates a new AlignFrame object.
    *
@@ -72,6 +75,7 @@ public class AlignFrame
     this(al, null, width, height);
   }
 
+
   /**
    * new alignment window with hidden columns
    * @param al AlignmentI
@@ -85,7 +89,7 @@ public class AlignFrame
 
     alignPanel = new AlignmentPanel(this, viewport);
 
-    if (al.getDataset() == null)
+    if(al.getDataset()==null)
     {
       al.setDataset(null);
     }
@@ -109,16 +113,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,252 +135,272 @@ public class AlignFrame
     }
 
     if (Desktop.desktop != null)
-    {
-      addServiceListeners();
-      setGUINucleotide(viewport.alignment.isNucleotide());
-    }
-
-    setMenusFromViewport(viewport);
-
-    if (viewport.wrapAlignment)
-    {
-      wrapMenuItem_actionPerformed(null);
-    }
+   {
+     this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
+     addServiceListeners();
+     setGUINucleotide(viewport.alignment.isNucleotide());
+   }
+
+   setMenusFromViewport(viewport);
+   buildSortByAnnotationScoresMenu();
+   if (viewport.wrapAlignment)
+   {
+     wrapMenuItem_actionPerformed(null);
+   }
 
     if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW",false))
     {
       this.overviewMenuItem_actionPerformed(null);
     }
 
-    addKeyListener();
+   addKeyListener();
 
   }
 
   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:
-            if (viewport.cursorMode)
-            {
-              alignPanel.seqPanel.moveCursor(0, 1);
-            }
-            else
-            {
+            case KeyEvent.VK_DOWN:
+             if (evt.isAltDown() || !viewport.cursorMode)
               moveSelectedSequences(false);
-            }
-            break;
+              if (viewport.cursorMode)
+                alignPanel.seqPanel.moveCursor(0, 1);
+              break;
 
-          case KeyEvent.VK_UP:
-            if (viewport.cursorMode)
-            {
-              alignPanel.seqPanel.moveCursor(0, -1);
-            }
-            else
-            {
+            case KeyEvent.VK_UP:
+            if (evt.isAltDown() || !viewport.cursorMode)
               moveSelectedSequences(true);
-            }
-            break;
+              if (viewport.cursorMode)
+                alignPanel.seqPanel.moveCursor(0, -1);
 
-          case KeyEvent.VK_LEFT:
-            if (viewport.cursorMode)
-            {
-              alignPanel.seqPanel.moveCursor( -1, 0);
-            }
-            break;
+              break;
 
-          case KeyEvent.VK_RIGHT:
-            if (viewport.cursorMode)
-            {
-              alignPanel.seqPanel.moveCursor(1, 0);
-            }
-            break;
+            case KeyEvent.VK_LEFT:
+            if (evt.isAltDown() || !viewport.cursorMode)
+              slideSequences(false,
+                             alignPanel.seqPanel.getKeyboardNo1());
+            else
+                alignPanel.seqPanel.moveCursor( -1, 0);
 
-          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);
-            }
+              break;
+
+            case KeyEvent.VK_RIGHT:
+            if (evt.isAltDown() || !viewport.cursorMode)
+              slideSequences(true,
+                             alignPanel.seqPanel.getKeyboardNo1());
             else
-            {
-              alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
-                  || evt.isShiftDown()
-                  || evt.isAltDown());
-            }
+                alignPanel.seqPanel.moveCursor(1, 0);
+              break;
 
-            break;
+            case KeyEvent.VK_SPACE:
+              if (viewport.cursorMode)
+              {
+                alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
+                                           || evt.isShiftDown()
+                                           || evt.isAltDown());
+              }
+              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)
+            case KeyEvent.VK_DELETE:
+            case KeyEvent.VK_BACK_SPACE:
+              if (!viewport.cursorMode)
+              {
+                cut_actionPerformed(null);
+              }
+              else
             {
-              alignPanel.seqPanel.setCursorPosition();
+                alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
+                                           || evt.isShiftDown()
+                                           || evt.isAltDown());
             }
-            break;
 
-          case KeyEvent.VK_ENTER:
-          case KeyEvent.VK_COMMA:
-            if (viewport.cursorMode)
-            {
-              alignPanel.seqPanel.setCursorRowAndColumn();
-            }
-            break;
+              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_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_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_ENTER:
+            case KeyEvent.VK_COMMA:
+              if (viewport.cursorMode)
+              {
+                alignPanel.seqPanel.setCursorRowAndColumn();
+              }
+              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_Q:
+              if (viewport.cursorMode)
+              {
+                alignPanel.seqPanel.setSelectionAreaAtCursor(true);
+              }
+              break;
+            case KeyEvent.VK_M:
+              if (viewport.cursorMode)
+              {
+                alignPanel.seqPanel.setSelectionAreaAtCursor(false);
+              }
+              break;
 
-              javax.help.HelpBroker hb = hs.createHelpBroker();
-              hb.setCurrentID("home");
-              hb.setDisplayed(true);
-            }
-            catch (Exception ex)
-            {
-              ex.printStackTrace();
-            }
-            break
-                ;
-          case KeyEvent.VK_H:
-          {
-            boolean toggleSeqs = !evt.isControlDown();
-            boolean toggleCols = !evt.isShiftDown();
+            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;
 
-            boolean hide = false;
+            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);
 
-            SequenceGroup sg = viewport.getSelectionGroup();
-            if (toggleSeqs)
-            {
-              if (sg != null && sg.getSize() != viewport.alignment.getHeight())
+                javax.help.HelpBroker hb = hs.createHelpBroker();
+                hb.setCurrentID("home");
+                hb.setDisplayed(true);
+              }
+              catch (Exception ex)
               {
-                hideSelSequences_actionPerformed(null);
-                hide = true;
+                ex.printStackTrace();
               }
+              break
+                  ;
+            case KeyEvent.VK_H:
+            {
+              boolean toggleSeqs = !evt.isControlDown();
+              boolean toggleCols = !evt.isShiftDown();
+
+              boolean hide = false;
+
+              SequenceGroup sg = viewport.getSelectionGroup();
+              if (toggleSeqs)
+              {
+                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;
+          }
+        }
+
+      public void keyReleased(KeyEvent evt)
+      {
+        switch(evt.getKeyCode())
+        {
+          case KeyEvent.VK_LEFT:
+            if (evt.isAltDown() || !viewport.cursorMode)
+              viewport.firePropertyChange("alignment", null,
+                                          viewport.getAlignment().getSequences());
+            break;
+
+          case KeyEvent.VK_RIGHT:
+            if (evt.isAltDown() || !viewport.cursorMode)
+              viewport.firePropertyChange("alignment", null,
+                                          viewport.getAlignment().getSequences());
             break;
         }
       }
-    });
+      });
   }
 
+
   public void addAlignmentPanel(final AlignmentPanel ap,
                                 boolean newPanel)
   {
@@ -390,9 +412,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);
     }
@@ -410,7 +432,7 @@ public class AlignFrame
       ap.setVisible(false);
     }
 
-    if (newPanel)
+    if(newPanel)
     {
       if (ap.av.padGaps)
       {
@@ -427,10 +449,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;
@@ -472,17 +495,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
@@ -515,29 +541,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));
@@ -557,12 +584,15 @@ public class AlignFrame
     validate();
   }
 
+
+
+
   /*
    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()
@@ -570,6 +600,7 @@ public class AlignFrame
     return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
   }
 
+
   public void fetchSequence_actionPerformed(ActionEvent e)
   {
     new SequenceFetcher(this);
@@ -582,12 +613,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
@@ -597,7 +628,7 @@ public class AlignFrame
             {
               frames[i].setSelected(true);
               Desktop.instance.closeAssociatedWindows();
-            }
+          }
             catch (java.beans.PropertyVetoException ex)
             {}
           }
@@ -605,6 +636,9 @@ public class AlignFrame
         }
         Desktop.instance.closeAssociatedWindows();
 
+        FileLoader loader = new FileLoader();
+        String protocol = fileName.startsWith("http:")? "URL":"File";
+        loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
       }
       else
       {
@@ -622,6 +656,7 @@ public class AlignFrame
     }
   }
 
+
   public void addFromText_actionPerformed(ActionEvent e)
   {
     Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
@@ -632,11 +667,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
+       || fileName.startsWith("http")
         )
     {
       saveAs_actionPerformed(null);
@@ -644,7 +680,7 @@ public class AlignFrame
     else
     {
       saveAlignment(fileName, currentFileFormat);
-    }
+  }
   }
 
   /**
@@ -655,14 +691,15 @@ public class AlignFrame
   public void saveAs_actionPerformed(ActionEvent e)
   {
     JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
-        getProperty("LAST_DIRECTORY"),
+        getProperty( "LAST_DIRECTORY"),
         new String[]
-        {"fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc", "jar"},
+        { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc","amsa","jar" },
         new String[]
-        {"Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "Jalview"},
+        { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview" },
         currentFileFormat,
         false);
 
+
     chooser.setFileView(new JalviewFileView());
     chooser.setDialogTitle("Save Alignment to file");
     chooser.setToolTipText("Save");
@@ -671,25 +708,25 @@ 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);
 
-      saveAlignment(fileName, currentFileFormat);
+      saveAlignment(fileName, currentFileFormat.substring(0,currentFileFormat.indexOf(" ")));
     }
   }
 
@@ -710,8 +747,8 @@ 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
@@ -730,13 +767,14 @@ public class AlignFrame
         if (reply == JOptionPane.YES_OPTION)
         {
           omitHidden = viewport.getViewAsString(false);
-        }
       }
+      }
+      FormatAdapter f = new FormatAdapter();
 
-      String output = new FormatAdapter().formatSequences(
+      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));
 
       if (output == null)
       {
@@ -782,17 +820,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);
       }
@@ -804,9 +842,10 @@ public class AlignFrame
                              "Alignment output - " + e.getActionCommand(), 600,
                              500);
 
+
     cap.setText(new FormatAdapter().formatSequences(
         e.getActionCommand(),
-        viewport.alignment.getSequencesArray(),
+        viewport.alignment,
         omitHidden));
   }
 
@@ -817,9 +856,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)
@@ -847,6 +886,7 @@ public class AlignFrame
     alignPanel.makeEPS(f);
   }
 
+
   public void pageSetup_actionPerformed(ActionEvent e)
   {
     PrinterJob printJob = PrinterJob.getPrinterJob();
@@ -870,15 +910,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
@@ -900,6 +943,7 @@ public class AlignFrame
 
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -907,23 +951,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
@@ -934,15 +981,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);
@@ -952,7 +1000,7 @@ public class AlignFrame
       if (closeAllTabs)
       {
         this.setClosed(true);
-      }
+    }
     }
     catch (Exception ex)
     {
@@ -960,6 +1008,7 @@ public class AlignFrame
     }
   }
 
+
   /**
    * DOCUMENT ME!
    */
@@ -992,9 +1041,10 @@ public class AlignFrame
     }
   }
 
+
   public void addHistoryItem(CommandI command)
   {
-    if (command.getSize() > 0)
+    if(command.getSize()>0)
     {
       viewport.historyList.push(command);
       viewport.redoList.clear();
@@ -1004,20 +1054,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",
@@ -1033,19 +1107,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",
@@ -1058,9 +1132,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;
@@ -1155,9 +1229,102 @@ public class AlignFrame
       }
     }
 
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
+  }
+
+
+
+
+  synchronized void slideSequences(boolean right, int size)
+  {
+    Vector sg = new Vector();
+    if(viewport.cursorMode)
+    {
+      sg.addElement(viewport.alignment.getSequenceAt(
+          alignPanel.seqPanel.seqCanvas.cursorY));
+    }
+    else if(viewport.getSelectionGroup()!=null
+        && viewport.getSelectionGroup().getSize()!=viewport.alignment.getHeight())
+   {
+     sg = viewport.getSelectionGroup().getSequences(
+         viewport.hiddenRepSequences);
+   }
+
+    if(sg.size()<1)
+    {
+      return;
+    }
+
+    Vector invertGroup = new Vector();
+
+    for (int i = 0; i < viewport.alignment.getHeight(); i++)
+    {
+      if(!sg.contains(viewport.alignment.getSequenceAt(i)))
+         invertGroup.add(viewport.alignment.getSequenceAt(i));
+    }
+
+    SequenceI[] seqs1 = new SequenceI[sg.size()];
+    for (int i = 0; i < sg.size(); i++)
+      seqs1[i] = (SequenceI) sg.elementAt(i);
+
+    SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
+    for (int i = 0; i < invertGroup.size(); i++)
+      seqs2[i] = (SequenceI) invertGroup.elementAt(i);
+
+    SlideSequencesCommand ssc;
+    if (right)
+      ssc = new SlideSequencesCommand("Slide Sequences",
+                                      seqs2, seqs1, size,
+                                      viewport.getGapCharacter()
+          );
+    else
+      ssc = new SlideSequencesCommand("Slide Sequences",
+                                      seqs1, seqs2, size,
+                                      viewport.getGapCharacter()
+          );
+
+    int groupAdjustment = 0;
+    if (ssc.getGapsInsertedBegin() && right)
+    {
+      if (viewport.cursorMode)
+        alignPanel.seqPanel.moveCursor(size, 0);
+      else
+        groupAdjustment = size;
+    }
+    else if (!ssc.getGapsInsertedBegin() && !right)
+    {
+      if (viewport.cursorMode)
+        alignPanel.seqPanel.moveCursor( -size, 0);
+      else
+        groupAdjustment = -size;
+    }
+
+    if (groupAdjustment != 0)
+    {
+      viewport.getSelectionGroup().setStartRes(
+          viewport.getSelectionGroup().getStartRes() + groupAdjustment);
+      viewport.getSelectionGroup().setEndRes(
+          viewport.getSelectionGroup().getEndRes() + groupAdjustment);
+    }
+
+
+    boolean appendHistoryItem = false;
+    if(viewport.historyList!=null
+       && viewport.historyList.size()>0
+      && viewport.historyList.peek() instanceof SlideSequencesCommand)
+    {
+      appendHistoryItem = ssc.appendSlideCommand(
+          (SlideSequencesCommand)viewport.historyList.peek())
+          ;
+    }
+
+    if(!appendHistoryItem)
+      addHistoryItem(ssc);
+
+    repaint();
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -1170,8 +1337,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)
@@ -1201,25 +1368,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++)
@@ -1229,7 +1396,7 @@ public class AlignFrame
 
         hiddenColumns.addElement(new int[]
                                  {region[0] - hiddenOffset,
-                                 region[1] - hiddenOffset});
+                          region[1]-hiddenOffset});
       }
     }
 
@@ -1238,7 +1405,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.");
   }
 
   /**
@@ -1268,6 +1435,7 @@ public class AlignFrame
    */
   void paste(boolean newAlignment)
   {
+    boolean externalPaste=true;
     try
     {
       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
@@ -1310,137 +1478,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)
+          {
+            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
           {
-            int[] region = (int[]) hc.elementAt(i);
-            af.viewport.hideColumns(region[0], region[1]);
+            // 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
     }
 
+
   }
 
   /**
@@ -1476,34 +1729,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)
     {
@@ -1528,7 +1785,7 @@ public class AlignFrame
     viewport.sequenceColours = null;
     viewport.setSelectionGroup(null);
     PaintRefresher.Refresh(this, viewport.getSequenceSetId());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -1548,7 +1805,7 @@ public class AlignFrame
 
     sg.setEndRes(viewport.alignment.getWidth() - 1);
     viewport.setSelectionGroup(sg);
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
   }
 
@@ -1559,7 +1816,7 @@ public class AlignFrame
    */
   public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
   {
-    if (viewport.cursorMode)
+    if(viewport.cursorMode)
     {
       alignPanel.seqPanel.keyboardNo1 = null;
       alignPanel.seqPanel.keyboardNo2 = null;
@@ -1569,7 +1826,7 @@ public class AlignFrame
     viewport.setSelectionGroup(null);
     alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
     alignPanel.idPanel.idCanvas.searchResults = null;
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
   }
 
@@ -1595,7 +1852,7 @@ public class AlignFrame
       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
     }
 
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
 
     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
   }
@@ -1603,9 +1860,10 @@ public class AlignFrame
   public void invertColSel_actionPerformed(ActionEvent e)
   {
     viewport.invertColumnSelection();
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -1623,7 +1881,7 @@ public class AlignFrame
    */
   public void remove2RightMenuItem_actionPerformed(ActionEvent e)
   {
-    trimAlignment(false);
+      trimAlignment(false);
   }
 
   void trimAlignment(boolean trimLeft)
@@ -1633,7 +1891,7 @@ public class AlignFrame
 
     if (colSel.size() > 0)
     {
-      if (trimLeft)
+      if(trimLeft)
       {
         column = colSel.getMin();
       }
@@ -1642,8 +1900,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);
@@ -1653,30 +1911,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);
 
@@ -1705,7 +1965,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)
@@ -1720,6 +1980,7 @@ public class AlignFrame
       seqs = viewport.alignment.getSequencesArray();
     }
 
+
     RemoveGapColCommand removeGapCols =
         new RemoveGapColCommand("Remove Gapped Columns",
                                 seqs,
@@ -1728,18 +1989,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());
 
@@ -1752,7 +2013,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)
@@ -1777,7 +2038,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());
@@ -1813,6 +2074,8 @@ public class AlignFrame
     AlignmentPanel newap =
         new Jalview2XML().copyAlignPanel(alignPanel, true);
 
+    newap.av.gatherViewsHere = false;
+
     if (viewport.viewName == null)
     {
       viewport.viewName = "Original";
@@ -1822,33 +2085,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;
     }
@@ -1857,7 +2120,7 @@ public class AlignFrame
 
   public void expandViews_actionPerformed(ActionEvent e)
   {
-    Desktop.instance.explodeViews(this);
+        Desktop.instance.explodeViews(this);
   }
 
   public void gatherViews_actionPerformed(ActionEvent e)
@@ -1865,6 +2128,8 @@ public class AlignFrame
     Desktop.instance.gatherViews(this);
   }
 
+
+
   /**
    * DOCUMENT ME!
    *
@@ -1875,6 +2140,7 @@ public class AlignFrame
     new FontChooser(alignPanel);
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -1885,15 +2151,17 @@ public class AlignFrame
     viewport.setShowJVSuffix(seqLimits.isSelected());
 
     alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel.calculateIdWidth());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   public void idRightAlign_actionPerformed(ActionEvent e)
   {
     viewport.rightAlignIds = idRightAlign.isSelected();
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
+
+
   /**
    * DOCUMENT ME!
    *
@@ -1902,7 +2170,7 @@ public class AlignFrame
   protected void colourTextMenuItem_actionPerformed(ActionEvent e)
   {
     viewport.setColourText(colourTextMenuItem.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -1933,13 +2201,13 @@ public class AlignFrame
   public void hideSelSequences_actionPerformed(ActionEvent e)
   {
     viewport.hideAllSelectedSeqs();
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   public void hideSelColumns_actionPerformed(ActionEvent e)
   {
     viewport.hideSelectedColumns();
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   public void hiddenMarkers_actionPerformed(ActionEvent e)
@@ -1956,7 +2224,7 @@ public class AlignFrame
   protected void scaleAbove_actionPerformed(ActionEvent e)
   {
     viewport.setScaleAboveWrapped(scaleAbove.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -1967,7 +2235,7 @@ public class AlignFrame
   protected void scaleLeft_actionPerformed(ActionEvent e)
   {
     viewport.setScaleLeftWrapped(scaleLeft.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -1978,7 +2246,7 @@ public class AlignFrame
   protected void scaleRight_actionPerformed(ActionEvent e)
   {
     viewport.setScaleRightWrapped(scaleRight.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -1989,7 +2257,7 @@ public class AlignFrame
   public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
   {
     viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -2000,7 +2268,7 @@ public class AlignFrame
   public void viewTextMenuItem_actionPerformed(ActionEvent e)
   {
     viewport.setShowText(viewTextMenuItem.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -2011,13 +2279,14 @@ public class AlignFrame
   protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
   {
     viewport.setRenderGaps(renderGapsMenuItem.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
+
   public FeatureSettings featureSettings;
   public void featureSettings_actionPerformed(ActionEvent e)
   {
-    if (featureSettings != null)
+    if(featureSettings !=null )
     {
       featureSettings.close();
       featureSettings = null;
@@ -2033,7 +2302,7 @@ public class AlignFrame
   public void showSeqFeatures_actionPerformed(ActionEvent evt)
   {
     viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
     if (alignPanel.getOverviewPanel() != null)
     {
       alignPanel.getOverviewPanel().updateOverviewImage();
@@ -2051,6 +2320,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!
    *
@@ -2194,6 +2522,7 @@ public class AlignFrame
     new AnnotationColourChooser(viewport, alignPanel);
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -2213,12 +2542,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());
@@ -2295,18 +2624,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",
@@ -2314,7 +2644,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);
@@ -2322,16 +2652,19 @@ public class AlignFrame
         else
         {
           sg.cs.setConservation(null);
-        }
       }
     }
+    }
 
     if (alignPanel.getOverviewPanel() != null)
     {
       alignPanel.getOverviewPanel().updateOverviewImage();
     }
 
-    alignPanel.repaint();
+
+
+
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -2341,7 +2674,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(),
@@ -2357,7 +2690,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,
@@ -2446,37 +2779,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)
@@ -2518,12 +2851,12 @@ 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));
     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
                                     viewport.alignment));
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -2533,10 +2866,10 @@ 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.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -2546,13 +2879,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.repaint();
+    alignPanel.paintAlignment(true);
   }
-
   /**
    * DOCUMENT ME!
    *
@@ -2563,6 +2895,7 @@ public class AlignFrame
     new RedundancyPanel(alignPanel, this);
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -2607,13 +2940,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,
@@ -2621,6 +2955,7 @@ public class AlignFrame
     }
   }
 
+
   /**
    * DOCUMENT ME!
    *
@@ -2721,7 +3056,7 @@ public class AlignFrame
         return;
       }
 
-      if (viewport.alignment.getHeight() < 2)
+      if(viewport.alignment.getHeight()<2)
       {
         return;
       }
@@ -2731,9 +3066,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;
@@ -2755,7 +3090,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);
@@ -2763,10 +3098,77 @@ public class AlignFrame
         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
                                         viewport.alignment));
 
-        alignPanel.repaint();
+        alignPanel.paintAlignment(true);
       }
     });
   }
+  /**
+   * 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());
+        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.
@@ -2785,9 +3187,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));
       }
@@ -2795,7 +3197,7 @@ public class AlignFrame
 
     iSize = treePanels.size();
 
-    if (iSize < 1)
+    if(iSize<1)
     {
       sortByTreeMenu.setVisible(false);
       return;
@@ -2803,11 +3205,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)
@@ -2819,7 +3221,7 @@ public class AlignFrame
                                           oldOrder,
                                           viewport.alignment));
 
-          alignPanel.repaint();
+          alignPanel.paintAlignment(true);
         }
       });
 
@@ -2842,27 +3244,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;
@@ -2876,7 +3279,7 @@ public class AlignFrame
    */
   AlignmentView gatherSeqOrMsaForSecStrPrediction()
   {
-    AlignmentView seqs = null;
+   AlignmentView seqs = null;
 
     if ( (viewport.getSelectionGroup() != null) &&
         (viewport.getSelectionGroup().getSize() > 0))
@@ -2896,7 +3299,6 @@ public class AlignFrame
     }
     return seqs;
   }
-
   /**
    * DOCUMENT ME!
    *
@@ -2936,15 +3338,16 @@ public class AlignFrame
     }
   }
 
+
   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,
@@ -2952,7 +3355,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
    *
@@ -2982,13 +3384,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);
       }
     }
@@ -3000,6 +3403,7 @@ public class AlignFrame
     return tp;
   }
 
+
   /**
    * Generates menu items and listener event actions for web service clients
    *
@@ -3040,7 +3444,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)
@@ -3085,7 +3489,7 @@ public class AlignFrame
                 {
                   // Sequence profile based prediction
                   new jalview.ws.JPredClient(sh,
-                                             title, true, msa, af, true);
+                      title, true, msa, af, true);
                 }
               }
             }
@@ -3094,7 +3498,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));
@@ -3102,7 +3506,7 @@ public class AlignFrame
     }
     else
     {
-      this.webService.removeAll();
+      resetWebServiceMenu();
       this.webService.add(this.webServiceNoServices);
     }
     // TODO: add in rediscovery function
@@ -3110,167 +3514,254 @@ public class AlignFrame
     // 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");
-
-     int value = chooser.showSaveDialog(this);
-
-     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);
-     }
-   }*/
 
+  /**
+   * 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() {
 
+      public void actionPerformed(ActionEvent e)
+      {
+        new jalview.ws.DBRefFetcher(
+                alignPanel.av.getSequenceSelection(),
+                alignPanel.alignFrame).fetchDBRefs(false);
+      }
 
+    });
+  }
 
-  public void showTranslation_actionPerformed(ActionEvent e)
+ /* public void vamsasStore_actionPerformed(ActionEvent e)
   {
-    SequenceI[] selection = viewport.getSelectionAsNewSequence();
-    String[] seqstring = viewport.getViewAsString(true);
+    JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
+        getProperty("LAST_DIRECTORY"));
 
-    int s, sSize = selection.length;
-    SequenceI[] newSeq = new SequenceI[sSize];
+    chooser.setFileView(new JalviewFileView());
+    chooser.setDialogTitle("Export to Vamsas file");
+    chooser.setToolTipText("Export");
 
-    int res, resSize;
-    StringBuffer protein;
-    String seq;
-    for (s = 0; s < sSize; s++)
-    {
-      protein = new StringBuffer();
-      seq = AlignSeq.extractGaps("-. ", seqstring[s]);
-      resSize = seq.length();
-      resSize -= resSize % 3;
+    int value = chooser.showSaveDialog(this);
 
-      for (res = 0; res < resSize; res += 3)
-      {
-        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"))
-        {
-          protein.append("X");
-        }
-        else
-        {
-          protein.append(aa);
-        }
-      }
-      newSeq[s] = new Sequence(selection[s].getName(),
-                               protein.toString());
+    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);
     }
-
-    AlignmentI al = new Alignment(newSeq);
-    al.setDataset(null);
-
-    ////////////////////////////////
-    // Copy annotations across
-    jalview.datamodel.AlignmentAnnotation[] annotations
-        = viewport.alignment.getAlignmentAnnotation();
-    int a, aSize;
-    if (annotations != null)
+  }*/
+  /**
+   * prototype of an automatically enabled/disabled analysis function
+   *
+   */
+  protected void setShowProductsEnabled()
+  {
+    SequenceI [] selection = viewport.getSequenceSelection();
+    if (canShowProducts(selection, viewport.getSelectionGroup()!=null, viewport.getAlignment().getDataset()))
     {
-      for (int i = 0; i < annotations.length; i++)
+      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++)
       {
-        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];
+        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() {
 
-        for (a = 0; a < viewport.alignment.getWidth(); a++)
-        {
-          if (annotations[i].annotations[a] == null
-              || annotations[i].annotations[a] == null)
+          public void actionPerformed(ActionEvent e)
           {
-            continue;
+            af.showProductsFor(sel, ds, isRegSel, dna, source);
           }
+          
+        });
+        showProducts.add(xtype);
+      }
+      showProducts.setVisible(showp);
+      showProducts.setEnabled(showp);
+    } catch (Exception e)
+    {
+      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)
+  {
+  ds = this.getViewport().alignment.getDataset(); // update our local dataset reference
+  Alignment prods = CrossRef.findXrefSequences(sel, dna, source, ds);
+  if (prods!=null)
+  {
+    SequenceI[] sprods = new SequenceI[prods.getHeight()];
+    for (int s=0; s<sprods.length;s++)
+    {
+      sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
+      if (ds.getSequences()==null || !ds.getSequences().contains(sprods[s].getDatasetSequence()))
+        ds.addSequence(sprods[s].getDatasetSequence());
+    }
+    Alignment al = new Alignment(sprods);
+    AlignedCodonFrame[] cf = prods.getCodonFrames();
+    for (int s=0; cf!=null && s<cf.length; s++)
+    {
+      al.addCodonFrame(cf[s]);
+      cf[s] = null;
+    }
+    al.setDataset(ds);
+    AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
+    String newtitle =""+((dna) ? "Proteins " : "Nucleotides ") + " for "+((isRegSel) ? "selected region of " : "")
+            + getTitle();
+    Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
+            DEFAULT_HEIGHT);
+  } else {
+    System.err.println("No Sequences generated for xRef type "+source);
+  }
+  }
 
-          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);
-        }
 
-        jalview.datamodel.AlignmentAnnotation aa
-            = new jalview.datamodel.AlignmentAnnotation(annotations[i].label,
-            annotations[i].description, anots);
-        al.addAnnotation(aa);
-      }
+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;
+  }
+}
+
+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)
-  {
+/**
+ * DOCUMENT ME!
+ *
+ * @param String DOCUMENT ME!
+ */
+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);
-      alignPanel.repaint();
+      alignPanel.paintAlignment(true);
     }
 
     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;
 
@@ -3328,13 +3819,13 @@ 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)
+   public void loadJalviewDataFile(String file)
   {
     try
     {
@@ -3350,12 +3841,12 @@ public class AlignFrame
 
       if (!isAnnotation)
       {
-        boolean isGroupsFile = parseFeaturesFile(file, protocol);
+        boolean isGroupsFile = parseFeaturesFile(file,protocol);
         if (!isGroupsFile)
         {
           String format = new IdentifyFile().Identify(file, protocol);
 
-          if (format.equalsIgnoreCase("JnetFile"))
+          if(format.equalsIgnoreCase("JnetFile"))
           {
             jalview.io.JPredFile predictions = new jalview.io.JPredFile(
                 file, protocol);
@@ -3363,18 +3854,19 @@ public class AlignFrame
                 viewport.getAlignment(),
                 0, false);
             alignPanel.adjustAnnotationHeight();
-            alignPanel.repaint();
+            alignPanel.paintAlignment(true);
           }
           else
           {
             new FileLoader().LoadFile(viewport, file, protocol, format);
-          }
         }
       }
+      }
       else
       {
         // (isAnnotation)
         alignPanel.adjustAnnotationHeight();
+        buildSortByAnnotationScoresMenu();
       }
 
     }
@@ -3396,7 +3888,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",
@@ -3406,15 +3898,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*)")>0)
+    {
+      buildSortByAnnotationScoresMenu();
+    }
+  }
 }
 
 class PrintThread
@@ -3423,9 +3929,8 @@ class PrintThread
   AlignmentPanel ap;
   public PrintThread(AlignmentPanel ap)
   {
-    this.ap = ap;
+   this.ap = ap;
   }
-
   static PageFormat pf;
   public void run()
   {