Source code for MSQuant: frmProteinValidation.vb, MSQuant/msquant/src/GUI/forms/frmProteinValidation.vb.

Table of contents page.

Home page for MSQuant.

'****************************************************************************
'* Copyright (C) 2004 Peter Mortensen and Matthias Mann                     *
'* This file is part of MSQuant.                                            *
'*                                                                          *
'* MSQuant is distributed under the terms of                                *
'* the GNU General Public License. See src/COPYING.TXT or                   *
'* <http://www.gnu.org/licenses/gpl.txt> for details.                       *
'*                                                                          *
'* MSQuant is free software; you can redistribute it                        *
'* and/or modify it under the terms of the GNU                              *
'* General Public License as published by the Free                          *
'* Software Foundation; either version 2 of the                             *
'* License, or (at your option) any later version.                          *
'*                                                                          *
'* MSQuant is distributed in the hope that it will be                       *
'* useful, but WITHOUT ANY WARRANTY; without even the                       *
'* implied warranty of MERCHANTABILITY or FITNESS FOR                       *
'* A PARTICULAR PURPOSE.  See the GNU General Public                        *
'* License for more details.                                                *
'*                                                                          *
'* You should have received a copy of the GNU General                       *
'* Public License along with MSQuant; if not, write to                      *
'* the Free Software Foundation, Inc., 59 Temple                            *
'* Place, Suite 330, Boston, MA  02111-1307  USA                            *
'*                                                                          *
'* Purpose: GUI, Protein validation window. User can inspect                *
'*          the MS-MS spectra for the identified (and                       *
'*          inserted) peptides and check/uncheck the                        *
'*          peptides (validated/not validated)                              *
'*          Holds Class frmProtValidation,                                  *
'*                                                                          *
'****************************************************************************

'****************************************************************************
'*                               CEBI                                       *
'*                    Software Development Group                            *
'*                         Peter Mortensen                                  *
'*                E-mail: NUKESPAMMERSdrmortensen@get2netZZZZZZ.dk          *
'*                 WWW: http://www.cebi.sdu.dk/                             *
'*                                                                          *
'*  Program for post-processing of result from search in mass               *
'*    spectrometric data.                                                   *
'*                                                                          *
'*    FILENAME:   frmProteinValidation.vb                                   *
'*    TYPE:  VISUAL_BASIC                                                   *
'*                                                                          *
'* CREATED: PM 2002-04-01   Vrs 1.0.  Estimated..                           *
'* UPDATED: PM 2004-02-06   Embedding of Finnegan spectra.                  *
'*                                                                          *
'****************************************************************************

'Future:
'  1. Check and reduce redundancy of lines that includes:
'       Dim qNumStr As String =
'
'  2. Delete design-time lsvPeptides.Columns (as it is deleted anyway
'     at runtime).
'  3. (Visual) tabbing to allow more on the screen, e.g. 2 spectra at
'     the same time.
'  4.

'Navigation:
'  1. MS3 scoring:
'       Function MS3_NextSpecAndCalcExtraScore
'  2. Fragments:
'       Sub displayBAndYions


Option Strict On
Option Explicit On  'Changed PM_OPTIONEXPLICIT 2003-02-13

Imports System.Text.RegularExpressions
Imports System.IO

Imports System.Text  'For StringBuilder

Imports System.Collections.Generic 'For Dictionary

'Changed PM_SPECTRUMDISPLAY_ZEDGRAPH 2007-09-19
Imports ZedGraph

'Changed PM_REFERENCES 2004-07-20
Imports AxXCALIBURDISPLAYSLib '\Xcalibur\system\programs\XcaliburDisplays.dll
'Requires using ActiveX Control:
'
'      (or browse to 'D:\Program Files\Xcalibur\system\programs\XcaliburDisplays.dll')
'      Open. OK.
'  2. Drag 'XSpecDisplay Class' to some form in order to have the
'     references 'AxXCALIBURDISPLAYSLib' and 'XCALIBURDISPLAYSLib'
'     added to References.
'  3. Delete the added control (the reference will stay)
'
'  Typical objects are:
'    XCALIBURDISPLAYSLib.XSpecPlot
'    AxXCALIBURDISPLAYSLib.AxXSpecDisplay
'    AxXCALIBURDISPLAYSLib._IXSpecDisplayEvents_MouseMoveEvent
'    AxXCALIBURDISPLAYSLib._IXSpecDisplayEvents_MouseUpEvent
'    XCALIBURDISPLAYSLib.XSpecPlottingStyles.XSpecPoint_To_Point
'    XCALIBURDISPLAYSLib.XSpecPlottingStyles.XSpecAutomatic

Imports SDUPutility

Imports CEBI_generalGUI 'For ListViewColumnSorter

Imports massSpectrometryBase
Imports massSpectrometryBase.quantitation

Imports MolecularSharedStructures


Imports App 'For class quantApplication

Imports PILplaceholder


'Note: this class MUST be in the beginning of the file, as in other
'      form classes. This is a strange Microsoft thing. Otherwise
'      you will get this very misleading error message:
'        "Error: System.Resources.MissingManifestResourceException: Could
'         not find any resources appropriate for the specified
'         culture (or the neutral culture) in the given assembly.
'         Make sure "frmProtValidation.resources" was correctly
'         embedded or linked into assembly "<application name>""
'
'      From: <http://www.codeproject.com/KB/dotnet/clipsend.aspx>:
'       "... class defined above the form in the source file. ...
'       the Form must be defined first in the source file.
'       According to Microsoft, this is by design, Q318603,
'       <http://support.microsoft.com/default.aspx?scid=kb;en-us;Q318603>."


'****************************************************************************
'*    <placeholder for header>                                              *
'****************************************************************************
Public Class frmProtValidation
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call
    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    Friend WithEvents Sequence As System.Windows.Forms.ColumnHeader
    Friend WithEvents ToolTip1 As System.Windows.Forms.ToolTip
    Friend WithEvents lblProtInfo As System.Windows.Forms.Label
    Friend WithEvents mnuContextProtVal As System.Windows.Forms.ContextMenu
    Friend WithEvents mnuSelectFirstPept As System.Windows.Forms.MenuItem
    Friend WithEvents mnuMarkPeptVerifiedAndMoveToNext As System.Windows.Forms.MenuItem
    Friend WithEvents mnuProteinNotCorrectandMoveToNextProtein As System.Windows.Forms.MenuItem
    Friend WithEvents mnuMarkPeptNotVerifAndMoveNext As System.Windows.Forms.MenuItem
    Friend WithEvents mnuClose As System.Windows.Forms.MenuItem
    Friend WithEvents cmdSelectNextPeptide As System.Windows.Forms.MenuItem
    Friend WithEvents mnuShowMS1 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuShowNextMS1 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuShowPrevMS1 As System.Windows.Forms.MenuItem
    Friend WithEvents btnRejProtAndMoveNext As System.Windows.Forms.Button
    Friend WithEvents btnVerifyAndNext As System.Windows.Forms.Button
    Friend WithEvents btnRejectAndNext As System.Windows.Forms.Button
    Friend WithEvents btnZoomPrev As System.Windows.Forms.Button
    Friend WithEvents btnAccProtAndMoveNext As System.Windows.Forms.Button
    Friend WithEvents btnQuantitate As System.Windows.Forms.Button
    Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu
    Friend WithEvents mnuQuantitation As System.Windows.Forms.MenuItem
    Friend WithEvents btnCycleTopSequences As System.Windows.Forms.Button
    Friend WithEvents mnuClose1 As System.Windows.Forms.MenuItem
    Friend WithEvents ProgressBar1 As System.Windows.Forms.ProgressBar
    Friend WithEvents btnFindTag As System.Windows.Forms.Button
    Friend WithEvents mnuExportProteinInfo As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem1 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSaveProteinInfo As System.Windows.Forms.MenuItem
    Friend WithEvents SaveFileDialog1 As System.Windows.Forms.SaveFileDialog
    Friend WithEvents mnuSaveFragments As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExportFragments As System.Windows.Forms.MenuItem
    Friend WithEvents yLevelForMarkers As System.Windows.Forms.Label
    Friend WithEvents btnStopMS3Scoring As System.Windows.Forms.Button
    Friend WithEvents lsvPeptides As System.Windows.Forms.ListView
    Friend WithEvents lblExtraInfo As System.Windows.Forms.Label
    Friend WithEvents MenuItem6 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem13 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuTeachPeakShape As System.Windows.Forms.MenuItem
    Friend WithEvents mnuFindTag As System.Windows.Forms.MenuItem
    Friend WithEvents mnuScanAllMSMS As System.Windows.Forms.MenuItem
    Friend WithEvents mnuQuantComparative As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSaveSpectrumDataPoints As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExportSpectrumDataPoints As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem7 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSaveReducedPeakList As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExportReducedPeakList As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem2 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExportMS3dumpInformation As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSaveMS3dumpInformation As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem4 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuAcceptProtein As System.Windows.Forms.MenuItem
    Friend WithEvents mnuRejectProtein As System.Windows.Forms.MenuItem
    Friend WithEvents mnuView As System.Windows.Forms.MenuItem
    Friend WithEvents mnuZoom As System.Windows.Forms.MenuItem
    Friend WithEvents mnuAcceptPeptide As System.Windows.Forms.MenuItem
    Friend WithEvents mnuRejectPeptide As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem5 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuUpSpectrumLevel As System.Windows.Forms.MenuItem
    Friend WithEvents mnuDownSpectrumLevel As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem9 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem10 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuNextPTMposition As System.Windows.Forms.MenuItem
    Friend WithEvents mnuPrevPTMposition As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSetPTMparameters As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem11 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuOpenQuantitaionWindow As System.Windows.Forms.MenuItem
    Friend WithEvents mnuProteinCorrectAndMoveToNextProtein As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem12 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuStopMS3Scoring As System.Windows.Forms.MenuItem
    Friend WithEvents mnuStopPTMScoring As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem15 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuScoreMS3 As System.Windows.Forms.MenuItem
    Friend WithEvents staSpectrumInfoEtc As System.Windows.Forms.StatusBar
    Friend WithEvents clbPTMcombinations As System.Windows.Forms.CheckedListBox
    Friend WithEvents StatusBarPanel1 As System.Windows.Forms.StatusBarPanel
    Friend WithEvents StatusBarPanelPTM As System.Windows.Forms.StatusBarPanel
    Friend WithEvents mnuCommitPTMchanges As System.Windows.Forms.MenuItem
    Friend WithEvents mnuOpenToolbar As System.Windows.Forms.MenuItem
    Friend WithEvents mnuScorePTM_Old As System.Windows.Forms.MenuItem
    Friend WithEvents mnuScorePTM2 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem14 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSaveAsPNG As System.Windows.Forms.MenuItem
    Friend WithEvents chkShowMatchedIonsOnly As System.Windows.Forms.CheckBox
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents MenuItem3 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem16 As System.Windows.Forms.MenuItem
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmProtValidation))
        Me.lsvPeptides = New System.Windows.Forms.ListView
        Me.Sequence = New System.Windows.Forms.ColumnHeader
        Me.mnuContextProtVal = New System.Windows.Forms.ContextMenu
        Me.mnuSelectFirstPept = New System.Windows.Forms.MenuItem
        Me.cmdSelectNextPeptide = New System.Windows.Forms.MenuItem
        Me.mnuMarkPeptVerifiedAndMoveToNext = New System.Windows.Forms.MenuItem
        Me.mnuMarkPeptNotVerifAndMoveNext = New System.Windows.Forms.MenuItem
        Me.mnuShowMS1 = New System.Windows.Forms.MenuItem
        Me.mnuShowNextMS1 = New System.Windows.Forms.MenuItem
        Me.mnuShowPrevMS1 = New System.Windows.Forms.MenuItem
        Me.mnuProteinCorrectAndMoveToNextProtein = New System.Windows.Forms.MenuItem
        Me.mnuProteinNotCorrectandMoveToNextProtein = New System.Windows.Forms.MenuItem
        Me.mnuClose = New System.Windows.Forms.MenuItem
        Me.staSpectrumInfoEtc = New System.Windows.Forms.StatusBar
        Me.StatusBarPanel1 = New System.Windows.Forms.StatusBarPanel
        Me.StatusBarPanelPTM = New System.Windows.Forms.StatusBarPanel
        Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components)
        Me.btnVerifyAndNext = New System.Windows.Forms.Button
        Me.btnRejectAndNext = New System.Windows.Forms.Button
        Me.btnZoomPrev = New System.Windows.Forms.Button
        Me.btnCycleTopSequences = New System.Windows.Forms.Button
        Me.btnAccProtAndMoveNext = New System.Windows.Forms.Button
        Me.btnRejProtAndMoveNext = New System.Windows.Forms.Button
        Me.btnQuantitate = New System.Windows.Forms.Button
        Me.btnFindTag = New System.Windows.Forms.Button
        Me.lblProtInfo = New System.Windows.Forms.Label
        Me.MainMenu1 = New System.Windows.Forms.MainMenu(Me.components)
        Me.mnuQuantitation = New System.Windows.Forms.MenuItem
        Me.mnuSaveProteinInfo = New System.Windows.Forms.MenuItem
        Me.mnuSaveFragments = New System.Windows.Forms.MenuItem
        Me.mnuSaveSpectrumDataPoints = New System.Windows.Forms.MenuItem
        Me.mnuSaveReducedPeakList = New System.Windows.Forms.MenuItem
        Me.MenuItem1 = New System.Windows.Forms.MenuItem
        Me.mnuExportProteinInfo = New System.Windows.Forms.MenuItem
        Me.mnuExportFragments = New System.Windows.Forms.MenuItem
        Me.mnuExportSpectrumDataPoints = New System.Windows.Forms.MenuItem
        Me.mnuExportReducedPeakList = New System.Windows.Forms.MenuItem
        Me.MenuItem2 = New System.Windows.Forms.MenuItem
        Me.mnuSaveMS3dumpInformation = New System.Windows.Forms.MenuItem
        Me.mnuExportMS3dumpInformation = New System.Windows.Forms.MenuItem
        Me.MenuItem14 = New System.Windows.Forms.MenuItem
        Me.mnuSaveAsPNG = New System.Windows.Forms.MenuItem
        Me.MenuItem7 = New System.Windows.Forms.MenuItem
        Me.mnuClose1 = New System.Windows.Forms.MenuItem
        Me.mnuView = New System.Windows.Forms.MenuItem
        Me.mnuZoom = New System.Windows.Forms.MenuItem
        Me.MenuItem5 = New System.Windows.Forms.MenuItem
        Me.mnuUpSpectrumLevel = New System.Windows.Forms.MenuItem
        Me.mnuDownSpectrumLevel = New System.Windows.Forms.MenuItem
        Me.MenuItem3 = New System.Windows.Forms.MenuItem
        Me.MenuItem4 = New System.Windows.Forms.MenuItem
        Me.mnuOpenToolbar = New System.Windows.Forms.MenuItem
        Me.MenuItem16 = New System.Windows.Forms.MenuItem
        Me.mnuAcceptProtein = New System.Windows.Forms.MenuItem
        Me.mnuRejectProtein = New System.Windows.Forms.MenuItem
        Me.MenuItem9 = New System.Windows.Forms.MenuItem
        Me.mnuAcceptPeptide = New System.Windows.Forms.MenuItem
        Me.mnuRejectPeptide = New System.Windows.Forms.MenuItem
        Me.MenuItem11 = New System.Windows.Forms.MenuItem
        Me.mnuSetPTMparameters = New System.Windows.Forms.MenuItem
        Me.MenuItem10 = New System.Windows.Forms.MenuItem
        Me.mnuScoreMS3 = New System.Windows.Forms.MenuItem
        Me.MenuItem15 = New System.Windows.Forms.MenuItem
        Me.mnuScorePTM_Old = New System.Windows.Forms.MenuItem
        Me.mnuScorePTM2 = New System.Windows.Forms.MenuItem
        Me.mnuNextPTMposition = New System.Windows.Forms.MenuItem
        Me.mnuPrevPTMposition = New System.Windows.Forms.MenuItem
        Me.mnuCommitPTMchanges = New System.Windows.Forms.MenuItem
        Me.MenuItem12 = New System.Windows.Forms.MenuItem
        Me.mnuStopMS3Scoring = New System.Windows.Forms.MenuItem
        Me.mnuStopPTMScoring = New System.Windows.Forms.MenuItem
        Me.MenuItem6 = New System.Windows.Forms.MenuItem
        Me.mnuTeachPeakShape = New System.Windows.Forms.MenuItem
        Me.mnuFindTag = New System.Windows.Forms.MenuItem
        Me.mnuScanAllMSMS = New System.Windows.Forms.MenuItem
        Me.MenuItem13 = New System.Windows.Forms.MenuItem
        Me.mnuOpenQuantitaionWindow = New System.Windows.Forms.MenuItem
        Me.mnuQuantComparative = New System.Windows.Forms.MenuItem
        Me.ProgressBar1 = New System.Windows.Forms.ProgressBar
        Me.SaveFileDialog1 = New System.Windows.Forms.SaveFileDialog
        Me.yLevelForMarkers = New System.Windows.Forms.Label
        Me.btnStopMS3Scoring = New System.Windows.Forms.Button
        Me.lblExtraInfo = New System.Windows.Forms.Label
        Me.clbPTMcombinations = New System.Windows.Forms.CheckedListBox
        Me.chkShowMatchedIonsOnly = New System.Windows.Forms.CheckBox
        Me.Label1 = New System.Windows.Forms.Label
        CType(Me.StatusBarPanel1, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.StatusBarPanelPTM, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'lsvPeptides
        '
        Me.lsvPeptides.Alignment = System.Windows.Forms.ListViewAlignment.Left
        Me.lsvPeptides.AutoArrange = False
        Me.lsvPeptides.CheckBoxes = True
        Me.lsvPeptides.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.Sequence})
        Me.lsvPeptides.ContextMenu = Me.mnuContextProtVal
        Me.lsvPeptides.FullRowSelect = True
        Me.lsvPeptides.HideSelection = False
        Me.lsvPeptides.Location = New System.Drawing.Point(0, 24)
        Me.lsvPeptides.MultiSelect = False
        Me.lsvPeptides.Name = "lsvPeptides"
        Me.lsvPeptides.Size = New System.Drawing.Size(654, 176)
        Me.lsvPeptides.TabIndex = 0
        Me.lsvPeptides.UseCompatibleStateImageBehavior = False
        Me.lsvPeptides.View = System.Windows.Forms.View.Details
        '
        'Sequence
        '
        Me.Sequence.Text = "Sequence"
        Me.Sequence.Width = 200
        '
        'mnuContextProtVal
        '
        Me.mnuContextProtVal.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuSelectFirstPept, Me.cmdSelectNextPeptide, Me.mnuMarkPeptVerifiedAndMoveToNext, Me.mnuMarkPeptNotVerifAndMoveNext, Me.mnuShowMS1, Me.mnuShowNextMS1, Me.mnuShowPrevMS1, Me.mnuProteinCorrectAndMoveToNextProtein, Me.mnuProteinNotCorrectandMoveToNextProtein, Me.mnuClose})
        '
        'mnuSelectFirstPept
        '
        Me.mnuSelectFirstPept.Index = 0
        Me.mnuSelectFirstPept.Text = "Select first peptide"
        '
        'cmdSelectNextPeptide
        '
        Me.cmdSelectNextPeptide.Index = 1
        Me.cmdSelectNextPeptide.Text = "Select Next Peptide"
        '
        'mnuMarkPeptVerifiedAndMoveToNext
        '
        Me.mnuMarkPeptVerifiedAndMoveToNext.Index = 2
        Me.mnuMarkPeptVerifiedAndMoveToNext.Text = "Mark peptide as verified (and move to next)"
        '
        'mnuMarkPeptNotVerifAndMoveNext
        '
        Me.mnuMarkPeptNotVerifAndMoveNext.Index = 3
        Me.mnuMarkPeptNotVerifAndMoveNext.Text = "Peptide not verified (and move to next)"
        '
        'mnuShowMS1
        '
        Me.mnuShowMS1.Index = 4
        Me.mnuShowMS1.Text = "Show MS1 spectrum"
        '
        'mnuShowNextMS1
        '
        Me.mnuShowNextMS1.Index = 5
        Me.mnuShowNextMS1.Text = "Show next MS1 spectrum"
        '
        'mnuShowPrevMS1
        '
        Me.mnuShowPrevMS1.Index = 6
        Me.mnuShowPrevMS1.Text = "Show previous MS1 spectrum"
        '
        'mnuProteinCorrectAndMoveToNextProtein
        '
        Me.mnuProteinCorrectAndMoveToNextProtein.Index = 7
        Me.mnuProteinCorrectAndMoveToNextProtein.Text = "Protein correct (and move to next protein)"
        '
        'mnuProteinNotCorrectandMoveToNextProtein
        '
        Me.mnuProteinNotCorrectandMoveToNextProtein.Index = 8
        Me.mnuProteinNotCorrectandMoveToNextProtein.Text = "Protein incorrect(and move to next protein)"
        '
        'mnuClose
        '
        Me.mnuClose.Index = 9
        Me.mnuClose.Text = "Close"
        '
        'staSpectrumInfoEtc
        '
        Me.staSpectrumInfoEtc.Location = New System.Drawing.Point(0, 673)
        Me.staSpectrumInfoEtc.Name = "staSpectrumInfoEtc"
        Me.staSpectrumInfoEtc.Panels.AddRange(New System.Windows.Forms.StatusBarPanel() {Me.StatusBarPanel1, Me.StatusBarPanelPTM})
        Me.staSpectrumInfoEtc.ShowPanels = True
        Me.staSpectrumInfoEtc.Size = New System.Drawing.Size(882, 22)
        Me.staSpectrumInfoEtc.TabIndex = 3
        '
        'StatusBarPanel1
        '
        Me.StatusBarPanel1.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring
        Me.StatusBarPanel1.Name = "StatusBarPanel1"
        Me.StatusBarPanel1.Width = 586
        '
        'StatusBarPanelPTM
        '
        Me.StatusBarPanelPTM.Name = "StatusBarPanelPTM"
        Me.StatusBarPanelPTM.Width = 280
        '
        'ToolTip1
        '
        Me.ToolTip1.ShowAlways = True
        '
        'btnVerifyAndNext
        '
        Me.btnVerifyAndNext.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.btnVerifyAndNext.Location = New System.Drawing.Point(704, -106)
        Me.btnVerifyAndNext.Name = "btnVerifyAndNext"
        Me.btnVerifyAndNext.Size = New System.Drawing.Size(88, 24)
        Me.btnVerifyAndNext.TabIndex = 12
        Me.btnVerifyAndNext.Text = "Acc Pept>>"
        Me.ToolTip1.SetToolTip(Me.btnVerifyAndNext, "Check peptide and move to next")
        Me.btnVerifyAndNext.Visible = False
        '
        'btnRejectAndNext
        '
        Me.btnRejectAndNext.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.btnRejectAndNext.Location = New System.Drawing.Point(704, -75)
        Me.btnRejectAndNext.Name = "btnRejectAndNext"
        Me.btnRejectAndNext.Size = New System.Drawing.Size(88, 24)
        Me.btnRejectAndNext.TabIndex = 13
        Me.btnRejectAndNext.Text = "Reject Pept>>"
        Me.ToolTip1.SetToolTip(Me.btnRejectAndNext, "Reject Peptide and move to next")
        Me.btnRejectAndNext.Visible = False
        '
        'btnZoomPrev
        '
        Me.btnZoomPrev.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.btnZoomPrev.Location = New System.Drawing.Point(704, -44)
        Me.btnZoomPrev.Name = "btnZoomPrev"
        Me.btnZoomPrev.Size = New System.Drawing.Size(88, 24)
        Me.btnZoomPrev.TabIndex = 16
        Me.btnZoomPrev.Text = "Zoom<<"
        Me.ToolTip1.SetToolTip(Me.btnZoomPrev, "Zoom to previous marked peak")
        Me.btnZoomPrev.Visible = False
        '
        'btnCycleTopSequences
        '
        Me.btnCycleTopSequences.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.btnCycleTopSequences.Location = New System.Drawing.Point(704, -261)
        Me.btnCycleTopSequences.Name = "btnCycleTopSequences"
        Me.btnCycleTopSequences.Size = New System.Drawing.Size(88, 24)
        Me.btnCycleTopSequences.TabIndex = 18
        Me.btnCycleTopSequences.Text = "Cycle Seq"
        Me.ToolTip1.SetToolTip(Me.btnCycleTopSequences, "Cycles to rank 2 or 1 sequence")
        Me.btnCycleTopSequences.Visible = False
        '
        'btnAccProtAndMoveNext
        '
        Me.btnAccProtAndMoveNext.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.btnAccProtAndMoveNext.Location = New System.Drawing.Point(704, -230)
        Me.btnAccProtAndMoveNext.Name = "btnAccProtAndMoveNext"
        Me.btnAccProtAndMoveNext.Size = New System.Drawing.Size(88, 24)
        Me.btnAccProtAndMoveNext.TabIndex = 19
        Me.btnAccProtAndMoveNext.Text = "Acc Prot>>"
        Me.ToolTip1.SetToolTip(Me.btnAccProtAndMoveNext, "Accept protein and load next")
        Me.btnAccProtAndMoveNext.Visible = False
        '
        'btnRejProtAndMoveNext
        '
        Me.btnRejProtAndMoveNext.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.btnRejProtAndMoveNext.Location = New System.Drawing.Point(704, -199)
        Me.btnRejProtAndMoveNext.Name = "btnRejProtAndMoveNext"
        Me.btnRejProtAndMoveNext.Size = New System.Drawing.Size(88, 24)
        Me.btnRejProtAndMoveNext.TabIndex = 20
        Me.btnRejProtAndMoveNext.Text = "Reject Prot>>"
        Me.ToolTip1.SetToolTip(Me.btnRejProtAndMoveNext, "Reject protein and move to next")
        Me.btnRejProtAndMoveNext.Visible = False
        '
        'btnQuantitate
        '
        Me.btnQuantitate.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.btnQuantitate.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnQuantitate.Location = New System.Drawing.Point(704, -168)
        Me.btnQuantitate.Name = "btnQuantitate"
        Me.btnQuantitate.Size = New System.Drawing.Size(88, 24)
        Me.btnQuantitate.TabIndex = 22
        Me.btnQuantitate.Text = "Quantitate"
        Me.ToolTip1.SetToolTip(Me.btnQuantitate, "Counts the parent MCR within +- 0.1 Da over - 1 and + 2 min")
        Me.btnQuantitate.Visible = False
        '
        'btnFindTag
        '
        Me.btnFindTag.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.btnFindTag.Location = New System.Drawing.Point(704, -13)
        Me.btnFindTag.Name = "btnFindTag"
        Me.btnFindTag.Size = New System.Drawing.Size(88, 24)
        Me.btnFindTag.TabIndex = 24
        Me.btnFindTag.Text = "Find &Tag"
        Me.ToolTip1.SetToolTip(Me.btnFindTag, "Check peptide and move to next")
        Me.btnFindTag.Visible = False
        '
        'lblProtInfo
        '
        Me.lblProtInfo.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.lblProtInfo.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblProtInfo.Location = New System.Drawing.Point(16, 0)
        Me.lblProtInfo.Name = "lblProtInfo"
        Me.lblProtInfo.Size = New System.Drawing.Size(346, 16)
        Me.lblProtInfo.TabIndex = 5
        '
        'MainMenu1
        '
        Me.MainMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuQuantitation, Me.mnuView, Me.MenuItem4, Me.MenuItem12, Me.MenuItem6, Me.MenuItem13})
        '
        'mnuQuantitation
        '
        Me.mnuQuantitation.Index = 0
        Me.mnuQuantitation.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuSaveProteinInfo, Me.mnuSaveFragments, Me.mnuSaveSpectrumDataPoints, Me.mnuSaveReducedPeakList, Me.MenuItem1, Me.mnuExportProteinInfo, Me.mnuExportFragments, Me.mnuExportSpectrumDataPoints, Me.mnuExportReducedPeakList, Me.MenuItem2, Me.mnuSaveMS3dumpInformation, Me.mnuExportMS3dumpInformation, Me.MenuItem14, Me.mnuSaveAsPNG, Me.MenuItem7, Me.mnuClose1})
        Me.mnuQuantitation.Text = "&File"
        '
        'mnuSaveProteinInfo
        '
        Me.mnuSaveProteinInfo.Index = 0
        Me.mnuSaveProteinInfo.Text = "Save Protein Information As..."
        '
        'mnuSaveFragments
        '
        Me.mnuSaveFragments.Index = 1
        Me.mnuSaveFragments.Text = "Save Current Fragments As..."
        '
        'mnuSaveSpectrumDataPoints
        '
        Me.mnuSaveSpectrumDataPoints.Index = 2
        Me.mnuSaveSpectrumDataPoints.Text = "Save Current Spectrum Data Points As..."
        '
        'mnuSaveReducedPeakList
        '
        Me.mnuSaveReducedPeakList.Index = 3
        Me.mnuSaveReducedPeakList.Text = "Save Reduced Peak List As..."
        '
        'MenuItem1
        '
        Me.MenuItem1.Index = 4
        Me.MenuItem1.Text = "-"
        '
        'mnuExportProteinInfo
        '
        Me.mnuExportProteinInfo.Index = 5
        Me.mnuExportProteinInfo.Text = "&Export Protein Information"
        '
        'mnuExportFragments
        '
        Me.mnuExportFragments.Index = 6
        Me.mnuExportFragments.Text = "Export Current Fragments"
        '
        'mnuExportSpectrumDataPoints
        '
        Me.mnuExportSpectrumDataPoints.Index = 7
        Me.mnuExportSpectrumDataPoints.Text = "Export Current Spectrum Data Points"
        '
        'mnuExportReducedPeakList
        '
        Me.mnuExportReducedPeakList.Index = 8
        Me.mnuExportReducedPeakList.Text = "Export Reduced Peak List"
        '
        'MenuItem2
        '
        Me.MenuItem2.Index = 9
        Me.MenuItem2.Text = "-"
        '
        'mnuSaveMS3dumpInformation
        '
        Me.mnuSaveMS3dumpInformation.Index = 10
        Me.mnuSaveMS3dumpInformation.Text = "Save ms3 dump information"
        '
        'mnuExportMS3dumpInformation
        '
        Me.mnuExportMS3dumpInformation.Index = 11
        Me.mnuExportMS3dumpInformation.Text = "Export ms3 dump information"
        '
        'MenuItem14
        '
        Me.MenuItem14.Index = 12
        Me.MenuItem14.Text = "-"
        '
        'mnuSaveAsPNG
        '
        Me.mnuSaveAsPNG.Index = 13
        Me.mnuSaveAsPNG.Shortcut = System.Windows.Forms.Shortcut.CtrlP
        Me.mnuSaveAsPNG.Text = "Save as .PNG"
        '
        'MenuItem7
        '
        Me.MenuItem7.Index = 14
        Me.MenuItem7.Text = "-"
        '
        'mnuClose1
        '
        Me.mnuClose1.Index = 15
        Me.mnuClose1.Text = "Close"
        '
        'mnuView
        '
        Me.mnuView.Index = 1
        Me.mnuView.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuZoom, Me.MenuItem5, Me.mnuUpSpectrumLevel, Me.mnuDownSpectrumLevel, Me.MenuItem3})
        Me.mnuView.Text = "&View"
        '
        'mnuZoom
        '
        Me.mnuZoom.Index = 0
        Me.mnuZoom.Text = "Zoom..."
        '
        'MenuItem5
        '
        Me.MenuItem5.Index = 1
        Me.MenuItem5.Text = "-"
        '
        'mnuUpSpectrumLevel
        '
        Me.mnuUpSpectrumLevel.Index = 2
        Me.mnuUpSpectrumLevel.Shortcut = System.Windows.Forms.Shortcut.F5
        Me.mnuUpSpectrumLevel.Text = "&Up one spectrum level"
        '
        'mnuDownSpectrumLevel
        '
        Me.mnuDownSpectrumLevel.Index = 3
        Me.mnuDownSpectrumLevel.Shortcut = System.Windows.Forms.Shortcut.CtrlF5
        Me.mnuDownSpectrumLevel.Text = "&Down one spectrum level"
        '
        'MenuItem3
        '
        Me.MenuItem3.Index = 4
        Me.MenuItem3.Text = "-"
        '
        'MenuItem4
        '
        Me.MenuItem4.Index = 2
        Me.MenuItem4.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuOpenToolbar, Me.MenuItem16, Me.mnuAcceptProtein, Me.mnuRejectProtein, Me.MenuItem9, Me.mnuAcceptPeptide, Me.mnuRejectPeptide, Me.MenuItem11, Me.mnuSetPTMparameters, Me.MenuItem10, Me.mnuScoreMS3, Me.MenuItem15, Me.mnuScorePTM_Old, Me.mnuScorePTM2, Me.mnuNextPTMposition, Me.mnuPrevPTMposition, Me.mnuCommitPTMchanges})
        Me.MenuItem4.Text = "&Proteins and Peptides"
        '
        'mnuOpenToolbar
        '
        Me.mnuOpenToolbar.Index = 0
        Me.mnuOpenToolbar.Text = "Open Toolbar"
        '
        'MenuItem16
        '
        Me.MenuItem16.Index = 1
        Me.MenuItem16.Text = "-"
        '
        'mnuAcceptProtein
        '
        Me.mnuAcceptProtein.Index = 2
        Me.mnuAcceptProtein.Shortcut = System.Windows.Forms.Shortcut.Ins
        Me.mnuAcceptProtein.Text = "&Accept Protein"
        '
        'mnuRejectProtein
        '
        Me.mnuRejectProtein.Index = 3
        Me.mnuRejectProtein.Shortcut = System.Windows.Forms.Shortcut.Del
        Me.mnuRejectProtein.Text = "&Reject Protein"
        '
        'MenuItem9
        '
        Me.MenuItem9.Index = 4
        Me.MenuItem9.Text = "-"
        '
        'mnuAcceptPeptide
        '
        Me.mnuAcceptPeptide.Index = 5
        Me.mnuAcceptPeptide.Shortcut = System.Windows.Forms.Shortcut.F8
        Me.mnuAcceptPeptide.Text = "Accept P&eptide"
        '
        'mnuRejectPeptide
        '
        Me.mnuRejectPeptide.Index = 6
        Me.mnuRejectPeptide.Shortcut = System.Windows.Forms.Shortcut.CtrlF8
        Me.mnuRejectPeptide.Text = "Reject Pe&ptide"
        '
        'MenuItem11
        '
        Me.MenuItem11.Index = 7
        Me.MenuItem11.Text = "-"
        '
        'mnuSetPTMparameters
        '
        Me.mnuSetPTMparameters.Index = 8
        Me.mnuSetPTMparameters.Text = "Spectrum reduction parameters..."
        '
        'MenuItem10
        '
        Me.MenuItem10.Index = 9
        Me.MenuItem10.Text = "-"
        '
        'mnuScoreMS3
        '
        Me.mnuScoreMS3.Index = 10
        Me.mnuScoreMS3.Shortcut = System.Windows.Forms.Shortcut.F6
        Me.mnuScoreMS3.Text = "Score MS3"
        '
        'MenuItem15
        '
        Me.MenuItem15.Index = 11
        Me.MenuItem15.Text = "-"
        '
        'mnuScorePTM_Old
        '
        Me.mnuScorePTM_Old.Enabled = False
        Me.mnuScorePTM_Old.Index = 12
        Me.mnuScorePTM_Old.Text = "Score PTM"
        '
        'mnuScorePTM2
        '
        Me.mnuScorePTM2.Index = 13
        Me.mnuScorePTM2.Shortcut = System.Windows.Forms.Shortcut.CtrlF9
        Me.mnuScorePTM2.Text = "Score PTM - &broader"
        '
        'mnuNextPTMposition
        '
        Me.mnuNextPTMposition.Index = 14
        Me.mnuNextPTMposition.Shortcut = System.Windows.Forms.Shortcut.F10
        Me.mnuNextPTMposition.Text = "Next PTM position"
        '
        'mnuPrevPTMposition
        '
        Me.mnuPrevPTMposition.Index = 15
        Me.mnuPrevPTMposition.Shortcut = System.Windows.Forms.Shortcut.CtrlF10
        Me.mnuPrevPTMposition.Text = "Previous PTM position"
        '
        'mnuCommitPTMchanges
        '
        Me.mnuCommitPTMchanges.Index = 16
        Me.mnuCommitPTMchanges.Shortcut = System.Windows.Forms.Shortcut.F12
        Me.mnuCommitPTMchanges.Text = "Commit PTM changes"
        '
        'MenuItem12
        '
        Me.MenuItem12.Index = 3
        Me.MenuItem12.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuStopMS3Scoring, Me.mnuStopPTMScoring})
        Me.MenuItem12.Text = "Automation"
        '
        'mnuStopMS3Scoring
        '
        Me.mnuStopMS3Scoring.Index = 0
        Me.mnuStopMS3Scoring.Text = "Stop MS3 scoring!"
        '
        'mnuStopPTMScoring
        '
        Me.mnuStopPTMScoring.Index = 1
        Me.mnuStopPTMScoring.Text = "Stop PTM scoring!"
        '
        'MenuItem6
        '
        Me.MenuItem6.Index = 4
        Me.MenuItem6.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuTeachPeakShape, Me.mnuFindTag, Me.mnuScanAllMSMS})
        Me.MenuItem6.Text = "&Spectrum"
        '
        'mnuTeachPeakShape
        '
        Me.mnuTeachPeakShape.Enabled = False
        Me.mnuTeachPeakShape.Index = 0
        Me.mnuTeachPeakShape.Text = "Teach &peak shape"
        '
        'mnuFindTag
        '
        Me.mnuFindTag.Enabled = False
        Me.mnuFindTag.Index = 1
        Me.mnuFindTag.Text = "Find Tag"
        '
        'mnuScanAllMSMS
        '
        Me.mnuScanAllMSMS.Enabled = False
        Me.mnuScanAllMSMS.Index = 2
        Me.mnuScanAllMSMS.Text = "Scan all MSMS"
        '
        'MenuItem13
        '
        Me.MenuItem13.Index = 5
        Me.MenuItem13.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuOpenQuantitaionWindow, Me.mnuQuantComparative})
        Me.MenuItem13.Text = "&Quantitation"
        '
        'mnuOpenQuantitaionWindow
        '
        Me.mnuOpenQuantitaionWindow.Index = 0
        Me.mnuOpenQuantitaionWindow.Shortcut = System.Windows.Forms.Shortcut.F2
        Me.mnuOpenQuantitaionWindow.Text = "Open Quantitation Window..."
        '
        'mnuQuantComparative
        '
        Me.mnuQuantComparative.Enabled = False
        Me.mnuQuantComparative.Index = 1
        Me.mnuQuantComparative.Text = "Quantitate comparative"
        Me.mnuQuantComparative.Visible = False
        '
        'ProgressBar1
        '
        Me.ProgressBar1.Location = New System.Drawing.Point(440, 0)
        Me.ProgressBar1.Name = "ProgressBar1"
        Me.ProgressBar1.Size = New System.Drawing.Size(488, 16)
        Me.ProgressBar1.TabIndex = 23
        '
        'SaveFileDialog1
        '
        Me.SaveFileDialog1.FileName = "prot1"
        '
        'yLevelForMarkers
        '
        Me.yLevelForMarkers.BackColor = System.Drawing.Color.Red
        Me.yLevelForMarkers.Location = New System.Drawing.Point(368, 520)
        Me.yLevelForMarkers.Name = "yLevelForMarkers"
        Me.yLevelForMarkers.Size = New System.Drawing.Size(16, 34)
        Me.yLevelForMarkers.TabIndex = 25
        '
        'btnStopMS3Scoring
        '
        Me.btnStopMS3Scoring.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnStopMS3Scoring.ForeColor = System.Drawing.Color.FromArgb(CType(CType(192, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer))
        Me.btnStopMS3Scoring.Location = New System.Drawing.Point(704, 245)
        Me.btnStopMS3Scoring.Name = "btnStopMS3Scoring"
        Me.btnStopMS3Scoring.Size = New System.Drawing.Size(88, 24)
        Me.btnStopMS3Scoring.TabIndex = 29
        Me.btnStopMS3Scoring.Text = "Stop! - MS3"
        Me.btnStopMS3Scoring.Visible = False
        '
        'lblExtraInfo
        '
        Me.lblExtraInfo.Location = New System.Drawing.Point(440, 603)
        Me.lblExtraInfo.Name = "lblExtraInfo"
        Me.lblExtraInfo.Size = New System.Drawing.Size(430, 60)
        Me.lblExtraInfo.TabIndex = 30
        Me.lblExtraInfo.Text = "xyz"
        '
        'clbPTMcombinations
        '
        Me.clbPTMcombinations.Items.AddRange(New Object() {"asda", "gfhert"})
        Me.clbPTMcombinations.Location = New System.Drawing.Point(0, 584)
        Me.clbPTMcombinations.Name = "clbPTMcombinations"
        Me.clbPTMcombinations.Size = New System.Drawing.Size(432, 79)
        Me.clbPTMcombinations.TabIndex = 32
        '
        'chkShowMatchedIonsOnly
        '
        Me.chkShowMatchedIonsOnly.AutoSize = True
        Me.chkShowMatchedIonsOnly.Location = New System.Drawing.Point(442, 583)
        Me.chkShowMatchedIonsOnly.Name = "chkShowMatchedIonsOnly"
        Me.chkShowMatchedIonsOnly.Size = New System.Drawing.Size(141, 17)
        Me.chkShowMatchedIonsOnly.TabIndex = 33
        Me.chkShowMatchedIonsOnly.Text = "Show only matched ions"
        Me.chkShowMatchedIonsOnly.UseVisualStyleBackColor = True
        '
        'Label1
        '
        Me.Label1.AutoSize = True
        Me.Label1.Location = New System.Drawing.Point(701, 287)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(229, 13)
        Me.Label1.TabIndex = 34
        Me.Label1.Text = "Phos loss ions are fixed to modification ID 5048"
        Me.Label1.Visible = False
        '
        'frmProtValidation
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(882, 695)
        Me.ContextMenu = Me.mnuContextProtVal
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.chkShowMatchedIonsOnly)
        Me.Controls.Add(Me.clbPTMcombinations)
        Me.Controls.Add(Me.lblExtraInfo)
        Me.Controls.Add(Me.btnStopMS3Scoring)
        Me.Controls.Add(Me.yLevelForMarkers)
        Me.Controls.Add(Me.btnFindTag)
        Me.Controls.Add(Me.ProgressBar1)
        Me.Controls.Add(Me.btnQuantitate)
        Me.Controls.Add(Me.btnRejProtAndMoveNext)
        Me.Controls.Add(Me.btnAccProtAndMoveNext)
        Me.Controls.Add(Me.btnCycleTopSequences)
        Me.Controls.Add(Me.btnZoomPrev)
        Me.Controls.Add(Me.btnRejectAndNext)
        Me.Controls.Add(Me.btnVerifyAndNext)
        Me.Controls.Add(Me.lblProtInfo)
        Me.Controls.Add(Me.staSpectrumInfoEtc)
        Me.Controls.Add(Me.lsvPeptides)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.MaximumSize = New System.Drawing.Size(888, 740)
        Me.Menu = Me.MainMenu1
        Me.MinimumSize = New System.Drawing.Size(888, 740)
        Me.Name = "frmProtValidation"
        Me.Text = " "
        CType(Me.StatusBarPanel1, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.StatusBarPanelPTM, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

#End Region


    'One place to change the column assignment for sorting etc
    'sequence is the main item (0),.
    Private Enum peptideColEnum2

        enumSequence = 263
        enumMascotScore 'Zeros subitem.
        enumMascotDeltaScore
        enumNumSeqOcc 'Alias unique.
        enumMascorCheckBoxChecked
        enumMascotRank
        enumMissedCleavages
        enumMeasuredMCR2
        enumCalculatedMass
        enumRelativeError 'Should that not be relative error instead
        '            of delta ????,e.g. enumRelativeMassError
        '            Or are we outputting the wrong quantity???

        'Some old: enumDeltaMass. Did the interface have the absolute
        '          mass error (in Da) in the past?

        enumModStr
        enumQueryNumber
        enumRetentionTime
        enumPeriod
        enumExperiment
        enumCycle

        enumMS3precursorIon
        enumScoreWithMS3

        enumScoreWithPTM

        'Changed PM_PHOSPHO_SCORING_DISPLAY 2005-10-19
        enumPTMinfo

        enumLeftFlankingAA
        enumRightFlankingAA

        'Changed PM_CHARGE_IN_PROTVAL 2008-05-20
        enumCharge

        'Changed PM_ID_SILACDISH 2008-07-15
        enumID_SILACdish 'In which SILAC dish was the peptide
        '  identified. If it always the first then the SILAC
        '  modifications are not recognised by the application or the
        '  wrong quantitation mode has been chosen - e.g. one for v.2.1. for a v.2.2 Mascot result file.

    End Enum 'peptideColEnum2


    Private mProt As ProteinHitStructure

    'Changed PM_SEVERALWIFFS_EXPORT 2003-08-29
    'Copy from somewhere else.
    Private mRawFiles() As massSpectrometryBase.fileSpecStructure

    'Changed PM_MANUAL_PEPTIDEQUANTSTATUSUPDATE 2003-05-06
    Private mProteinListIndex As Integer

    Private mFrmProteinList As frmProteinList

    Private mCurrentlySelectedPeptIdx As Integer ''Note: ***is*** visual index.

    Private mCurrSelPept As PeptideHitStructure
    Private mCurrSelPeptMod As String

    Private mWiffFileName As String
    Private mWiffInfo As rawFileInfoStruct
    'To map sorted table to underlying data struct: key is query
    '  number and value is index in mProt.pepts

    'Changed PM_TYPESAFE 2008-12-02
    'Private mQueryNum2PeptTokenHash As New Hashtable
    Private mQueryNum2PeptTokenHash2 As Dictionary(Of Integer, Integer)

    Private mDeltaMass As Double = 0.15 'look in a .15 Da width (should
    '  be 0.1 Da??? put in options)

    'Changed PM_REFACTOR 2005-02-25. Now in class peptideFragments.
    'private mCurrentlyZoomedFrag As Integer

    'Changed PM_REFACTOR 2005-02-24. Seems not to be used.
    'private mDisplItmArr2() As pDisplItmStructure    'The display items
    '  for the second sequence. Does


    Private mCurrCycle As Integer 'Cycle for current tandem spectrum.
    Private mFirstMS1 As Boolean = True 'Is it the first time that we are
    '  displaying the MS1 spectrum.

    'Changed PM_REFACTOR 2007-10-24
    'Private mA As Double 'Recalibration constants from the master form;
    'Private mB As Double ' as in yCorrected = mA + mB*yMeasured .
    Private mRecalibrator2 As SDUPrecalibrator

    'Changed PM_MARKER_FINDPEAK 2004-01-07

    'Changed PM_QUANTMODE 2003-02-18. Part of getting quantitation
    '  mode to class frmQuantWindow/QuantWindow.vb......
    Private mOptions As OptionsStruct2 'const/read-only.

    'Changed PM_VARIABLE_XIC_WINDOW 2003-11-27
    Private mApplication As quantApplication

    Private mCurrentQuantWindow As frmQuantWindow
    Private mStartingUp As Boolean = True

    'Changed PM_REFACTOR_FINNEGAN 2003-07-13
    Private mRawDataFileHandling As massSpectrometryBase.rawDataFileHandling

    'Changed PM_DOUBLE_OFFCLICK 2003-12-16
    Const STATE_DBL_WAITINGCLICKS As Integer = 1
    Const STATE_DBL_SINGLECLICK As Integer = 2
    Const STATE_DBL_DOUBLECLICK As Integer = 3
    Private mStateDbl As Integer = STATE_DBL_WAITINGCLICKS
    Private mRecentCheckedStatus As Boolean
    Private mAvoidHandlingPeptideCheckedEvent As Boolean

    ''Changed PM_BACK_TO_NORMAL 2003-07-29
    'private mTempIsAnalyst As Boolean = True

    'Changed PM_REFACTOR 2007-09-19
    ''Changed PM_FINNEGAN_MSMS_DISPLAY 2004-02-04
    'Private mFinneganMSMS As frmFinneganSpectra
    Private mMSMSdisplay As frmSpectrumDisplay


    'The diamond will only appear at the height of the peak if the
    'mass is within 0.15 Da


    'Changed PM_REFACTOR 2006-10-12
    'private mLastMSMSSignal As ArrayList 'Datapoints used by last
    ''  call of displayBAndYions().
    Private mLastMSMSSignal As _
      List(Of massSpectrometryBase.signalStructure)
    '  Datapoints used by last call of displayBAndYions().

    Private mLastMSMSSignalInfo As dataPointsInfoStructure2

    'Changed PM_XY_EXPORT 2005-01-05
    Private mLastPeptHit As PeptideHitStructure 'Remember
    '  the last peptide for e.g. XY export.

    'Changed PM_MS3INTEGRATION 2004-06-03
    Private mStop As Boolean

    'Changed PM_REFACTOR 2005-02-24
    Private mMSMSFragments As peptideFragments

    'Changed PM_ALWAYSSHOW_BEST_MS3_MATCH 2006-03-03
    Private mWorkingFragments As peptideFragments

    'Changed PM_REFACTOR 2005-02-28.
    'Old. Delete at any time.
    ''Changed PM_PROTVAL_COLUMNS 2005-02-28
    'private mColumnPeptideMap As Hashtable

    'Changed PM_PROTVAL_COLUMNS 2005-02-28
    Private mColumnMapper As listviewColumnMapper

    'Changed PM_VISUAL_COLUMNSORT 2006-02-23
    Private mListViewColumnSorter As ListViewColumnSorter

    'Changed PM_COLUMNSORT_BY_KEYBOARD 2008-11-11
    ''Changed PM_TYPESAFE_HASH 2006-11-06
    ''Private mColumnSortSpecificationHash As Hashtable 'Collection 
    ' ''  of key lists, one list per column to be sorted. Key is 
    ' ''  the ID for a column, e.g. peptideColEnum2.enumMascotScore
    'Private mColumnSortSpecificationHash As Dictionary( _
    '  Of Integer, List(Of sortKeyStructure))

    'Changed PM_SPECTRUM_BROWSE 2005-08-02
    Private mSpectrumTree As spectrumTree

    'Changed PM_PHOSPHO_SCORING 2005-08-09
    Private mPTMscorer As PTMscorer

    'Changed PM_REFACTOR 2005-08-11
    Private mMS3scorer As MS3scoring

    'Old. Delete
    'private mSpectrumLevelDisplayInfo As spectrumLevelDisplayInfoStruct

    'Changed PM_MANNREDUCTION_LEVEL 2005-09-05
    Private mReductionParameters2 As reductionParametersStructure

    'Changed PM_REFACTOR 2006-12-17
    'Private mSortedPTMIndices As ArrayList
    Private mSortedPTMIndices2 As List(Of Integer)

    'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-05
    Private mPTMcombinationsCycler As SDUPcycler

    'Changed PM_COMB_FOR_MS3 2006-08-01
    Private mCurrentComb As ionSetStruct

    'Changed PM_BROADER_PTMSCORE 2007-04-04
    Private mPTMversionMarker As String

    'Changed PM_AUTODOCUMENTATION 2007-04-17
    Private mSaveCounter As Integer


    'Changed PM_GENERALISED_IONSERIES 2008-05-08
    Private mGeneralisedIonSeries As PILgeneralisedIonSeries


    'Changed PM_DISPLAY_SCORE 2008-06-25
    Private mScratchSB As StringBuilder


    'Changed PM_TWOLEVEL_WINDOWNUMBERING_PREFIX 2008-08-21
    Private mParseIDnumber As Integer


    'Changed PM_HIGHER_LEVEL_PROCESSING 2008-09-04
    Private mExperimentSettings As experimentSettingsStruct


    '   PM 2003-03-12. Was by ByVal: aProtHitStru.
    '****************************************************************************
    '*  Parameters:                                                             *
    '*      aDisplayQueryNumber   A value of zero means that this parameter     *
    '*                            will be ignored. Instead the first peptide    *
    '*                            in whatever sort order is set (e.g.           *
    '*                            descending after score) will be displayed     *
    '*                            instead.                                      *
    '*                                                                          *
    '****************************************************************************
    Public Sub New( _
      ByRef aProtHitStru As ProteinHitStructure, _
      ByVal aWiffFileName As String, _
      ByVal aWiffCompQuantFileName As String, _
      ByRef aProteinListForm As frmProteinList, _
      ByVal aWiffFileInfo As rawFileInfoStruct, _
      ByRef aOptions As OptionsStruct2, _
      ByVal aProteinListIndex As Integer, _
      ByRef anInRawFiles() As massSpectrometryBase.fileSpecStructure, _
      ByRef anInApplication As quantApplication, _
      ByRef aRawDataFileHandling As massSpectrometryBase.rawDataFileHandling, _
      ByRef aRecalibrator As SDUPrecalibrator, _
      ByVal aDisplayQueryNumber As Integer, _
      ByVal aParseIDnumber As Integer, _
      ByVal anInExperimentSettings As experimentSettingsStruct _
      )
        'aOptions: const ref
        '  ByVal anA As Double, ByVal aB As Double, _

        Me.New() 'Why?


        'Changed PM_MANUAL_PEPTIDEQUANTSTATUSUPDATE 2003-05-06
        mProteinListIndex = -1 'For error detection

        'Changed PM_AUTODOCUMENTATION 2007-04-17
        Dim tickCount1 As Integer = Environment.TickCount
        mSaveCounter = tickCount1

        Dim settings As miscSettingsStructure2Struct = _
          anInApplication.getMiscSettings()
        Dim shv1b As Boolean = True
        If False AndAlso (settings.option1b And 1) = 0 Then
            shv1b = False
        End If

        'Changed PM_DOUBLE_OFFCLICK 2003-12-16
        mAvoidHandlingPeptideCheckedEvent = False

        yLevelForMarkers.Visible = False

        'Changed PM_PROTVALWINDOW_VERTICALSIZE 2006-01-02
        Dim spectrumDisplayOffset As Integer = 30 + 12 'Depends on size of
        '  lsvPeptides. It would be better instead to let loc be dependent
        '  on the size of lsvPeptides.

        'Changed PM_FINNEGAN_LABELS 2004-05-04
        Dim locFromLabel As Point = yLevelForMarkers.Location
        'Dim yFromLavel As Integer = locFromLabel.Y + yLevelForMarkers.Height
        Dim yFromLabel As Integer = locFromLabel.Y

        'Changed PM_PROTVALWINDOW_VERTICALSIZE 2006-01-02
        yFromLabel -= spectrumDisplayOffset

        If True Then 'Add spectrum control, but only the one corresponding to 
            '  the raw file mode.
            '  Note: in contrast to using the Designer this does not
            '        create dependencies as to what software needs to
            '        be installed on the target system. E.g. Finnegan and 
            '        Analyst software no longer needs to be installed at 
            '        the same time, only Analyst is needed for 
            '        analysing Analyst data....
            'Changed PM_FINNEGAN_MSMS_DISPLAY 2004-02-04
            'Changed PM_PROTVALWINDOW_VERTICALSIZE 2006-01-02
            Dim loc2 As System.Drawing.Point = _
              New System.Drawing.Point(8, 248 - spectrumDisplayOffset)

            Dim size2 As System.Drawing.Size = _
              New System.Drawing.Size(920, 312)

            Select Case aOptions.rawFileMode
                Case rawFileModeEnum.enumAnalyst

                    Dim obj As Object = Nothing 'Keep compiler happy.
                    quantApplication.addSpectrumControl( _
                      Me, GetType(frmProtValidation), _
                      obj, _
                      "AxGraphControl_ANALYSTCOM_2", _
                      displayModeEnum.enumQS, _
                      loc2, size2, _
                      aOptions.COMversion)

                    Dim comObj As AnalystCOM = _
                      DirectCast(obj, AnalystCOM)
                    Trace.Assert(Not comObj Is Nothing, _
                      "PIL ASSERT. " & _
                      "Instance of AnalystCOM, comObj,  was not created....")
                    Dim marker As AnalystSpectrumMarking = _
                      New AnalystSpectrumMarking( _
                        comObj, aRawDataFileHandling)

                    'Changed PM_QSTAR_BROKEN 2007-10-03. Was missing!
                    mMSMSdisplay = _
                      New frmAnalystSpectraWithLabelMarkers( _
                        aRawDataFileHandling, _
                        comObj, _
                        aRawDataFileHandling, _
                        DirectCast(marker, SDUPspectrumMarking))
                    '  SDUPspectrumMarking is base class.

                Case rawFileModeEnum.enumFinnegan

                    If True Then 'False: ZedGraph test.
                        Dim obj As Object = Nothing 'Keep compiler happy.
                        quantApplication.addSpectrumControl( _
                          Me, GetType(frmProtValidation), _
                          obj, _
                          "AxXSpecDisplayForProtVal_XCALIBURCOM_2", _
                          displayModeEnum.enumXCalibur, _
                          loc2, size2, _
                          aOptions.COMversion)
                        Dim AxXSpecDisplay_XCALIBURCOM As AxXSpecDisplay = _
                          DirectCast(obj, AxXSpecDisplay)

                        Trace.Assert( _
                          Not AxXSpecDisplay_XCALIBURCOM Is Nothing, _
                          "PIL ASSERT. AxXSpecDisplay_XCALIBURCOM was not created....")

                        Dim marker As overlaySpectrumMarking = _
                          New overlaySpectrumMarking( _
                            Me, ToolTip1)

                        mMSMSdisplay = _
                          New frmFinneganSpectra( _
                            aRawDataFileHandling, _
                            AxXSpecDisplay_XCALIBURCOM, _
                            aRawDataFileHandling, _
                            DirectCast(marker, SDUPspectrumMarking))

                        Dim xOffsetForMarkers As Integer = _
                          mMSMSdisplay.xOffsetForMarkers()
                        Dim xOffsetFromRightEdge As Integer = _
                          mMSMSdisplay.xOffsetFromRightEdge()
                        marker.init2( _
                          xOffsetForMarkers, xOffsetFromRightEdge, _
                          yFromLabel, yLevelForMarkers.Height)

                    Else
                        Dim obj As Object = Nothing 'Keep compiler happy.
                        quantApplication.addSpectrumControl( _
                          Me, GetType(frmProtValidation), _
                          obj, _
                          "mZedGraphControl", _
                          displayModeEnum.enumZedGraph, _
                          loc2, size2, _
                          aOptions.COMversion)
                        Dim someZedGraphControl As ZedGraphControl = _
                          DirectCast(obj, ZedGraphControl)
                        Trace.Assert( _
                          Not someZedGraphControl Is Nothing, _
                          "PIL ASSERT. mZedGraphControl was not created....")

                        Dim marker2 As overlaySpectrumMarking = _
                          New overlaySpectrumMarking( _
                            Me, ToolTip1)

                        mMSMSdisplay = _
                          New frmZedSpectra( _
                            aRawDataFileHandling, _
                            someZedGraphControl, _
                            aRawDataFileHandling, _
                            DirectCast(marker2, SDUPspectrumMarking))

                        Dim xOffsetForMarkers As Integer = _
                          mMSMSdisplay.xOffsetForMarkers()
                        Dim xOffsetFromRightEdge As Integer = _
                          mMSMSdisplay.xOffsetFromRightEdge()
                        Dim yOffsetForMarkers As Integer = _
                          mMSMSdisplay.yOffsetForMarkers()
                        marker2.init2( _
                          xOffsetForMarkers, xOffsetFromRightEdge, _
                          yFromLabel, yOffsetForMarkers)
                    End If


                Case rawFileModeEnum.enumMicromass
                    Dim obj As Object = Nothing 'Keep compiler happy.
                    quantApplication.addSpectrumControl( _
                      Me, GetType(frmProtValidation), _
                      obj, _
                      "mZedGraphControl", _
                      displayModeEnum.enumZedGraph, _
                      loc2, size2, _
                      aOptions.COMversion)
                    Dim someZedGraphControl As ZedGraphControl = _
                      DirectCast(obj, ZedGraphControl)
                    Trace.Assert( _
                      Not someZedGraphControl Is Nothing, _
                      "PIL ASSERT. someZedGraphControl was not created....")

                    Dim marker2 As overlaySpectrumMarking = _
                      New overlaySpectrumMarking( _
                        Me, ToolTip1)

                    mMSMSdisplay = _
                      New frmZedSpectra( _
                        aRawDataFileHandling, _
                        someZedGraphControl, _
                        aRawDataFileHandling, _
                        DirectCast(marker2, SDUPspectrumMarking))

                    Dim xOffsetForMarkers As Integer = _
                      mMSMSdisplay.xOffsetForMarkers()
                    Dim xOffsetFromRightEdge As Integer = _
                      mMSMSdisplay.xOffsetFromRightEdge()
                    Dim yOffsetForMarkers As Integer = _
                      mMSMSdisplay.yOffsetForMarkers()
                    marker2.init2( _
                      xOffsetForMarkers, xOffsetFromRightEdge, _
                      yFromLabel, yOffsetForMarkers)

                Case Else
                    Trace.Assert(False, _
                      "PIL ASSERT. Select Case never fall-through")
            End Select
        End If

        'Changed PM_GENERALISED_IONSERIES 2008-05-08
        mGeneralisedIonSeries = anInApplication.getIonSeriesDefinitions()

        'Changed PM_ALSO_PRECURSOR_FOR_MS3 2006-10-31. Two more parameters.
        ''Changed PM_REFACTOR 2005-02-24
        Dim quantitationModesObject As QuantitationModes_moreGeneral = _
          anInApplication.getQuantModes()
        mMSMSFragments = _
          New peptideFragments( _
            aRecalibrator, quantitationModesObject, _
            aOptions.quantModeCode, mGeneralisedIonSeries)

        'Changed PM_ALWAYSSHOW_BEST_MS3_MATCH 2006-03-03
        mWorkingFragments = _
          New peptideFragments( _
            aRecalibrator, quantitationModesObject, _
            aOptions.quantModeCode, mGeneralisedIonSeries)

        mColumnMapper = New listviewColumnMapper(lsvPeptides)

        'Changed PM_VISUAL_COLUMNSORT 2006-02-23
        mListViewColumnSorter = _
          New ListViewColumnSorter(mColumnMapper)

        'Changed PM_COLUMNSORT_BY_KEYBOARD 2008-11-11. Delete at any time.
        ''Changed PM_TYPESAFE_HASH 2006-11-06
        'mColumnSortSpecificationHash = New Dictionary( _
        '  Of Integer, List(Of sortKeyStructure))

        'Changed PM_PROTVAL_COLUMNS 2005-02-28
        Me.setPeptideListViewColumns(anInApplication)

        'Changed PM_SPECTRUM_BROWSE 2005-08-02
        mSpectrumTree = New spectrumTree(aRawDataFileHandling)

        'Changed PM_EXTERNAL_SMARTPICKING_PARAMETERS 2008-10-08. Now the 
        '  values are from the XML settings file and the defaults are set in
        '  defaultMiscSettings().
        ' 'Default, unless overrriden by client (not yet)
        ' mReductionParameters.smartPickingLevel2 = 8
        ' mReductionParameters.MannReductionLevel2 = 4
        ' 
        ' 'Changed PM_USERSET_MS3_MATCHING_TOLERANCE 2007-07-13
        ' mReductionParameters.smartPickingMassWindow = 100.0 'Was default
        ' '  in reducePeakList().
        ' mReductionParameters.matchingMassTolerance = 0.3
        mReductionParameters2 = _
          anInApplication.getMiscSettings().smartPickingParameters

        If True Then
            MenuItem10.Visible = shv1b
            mnuScorePTM_Old.Visible = shv1b
            mnuNextPTMposition.Visible = shv1b
            mnuPrevPTMposition.Visible = shv1b
            'mnuSetPTMparameters.Visible = shv

            mnuCommitPTMchanges.Visible = shv1b

            mnuStopPTMScoring.Visible = shv1b

            clbPTMcombinations.Visible = shv1b
        End If

        'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-03
        If True Then
            staSpectrumInfoEtc.BringToFront()
            clbPTMcombinations.BringToFront()
        End If

        'Visual sorting
        If True Then

            'Sequence
            mListViewColumnSorter.addColumnPrimaryKey( _
              peptideColEnum2.enumSequence, _
              datatypeEnum.enumText, _
              sortingDirectionEnum.enumAscendingSort, _
              True)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumMascotScore, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumDescendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumMeasuredMCR2, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumAscendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumQueryNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort)

            'Changed PM_SORT_MODCOLUMN 2006-05-08
            'Modifications. Descending (to list them first)
            mListViewColumnSorter.addColumnPrimaryKey( _
              peptideColEnum2.enumModStr, _
              datatypeEnum.enumText, _
              sortingDirectionEnum.enumDescendingSort, _
              True)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumSequence, _
              datatypeEnum.enumText, _
              sortingDirectionEnum.enumAscendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumMascotScore, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumDescendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumMeasuredMCR2, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumAscendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumQueryNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort)

            'Query
            mListViewColumnSorter.addColumnPrimaryKey( _
              peptideColEnum2.enumQueryNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort, _
              True)

            'Mascot score
            mListViewColumnSorter.addColumnPrimaryKey( _
              peptideColEnum2.enumMascotScore, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumDescendingSort, _
              True)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumMissedCleavages, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumMeasuredMCR2, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumAscendingSort)

            'Changed PM_ID_SILACDISH 2008-07-15
            'Peptide identification SILAC dish number.
            'Minimum for defined sort order. Should we add to usual
            'secondary keys.
            '
            'SILAC dish number.
            mListViewColumnSorter.addColumnPrimaryKey( _
              peptideColEnum2.enumID_SILACdish, _
              datatypeEnum.enumText, _
              sortingDirectionEnum.enumDescendingSort, _
              True)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumMascotScore, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumDescendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumQueryNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort)

            'MS3 score (actually Mascot score + MS score)
            mListViewColumnSorter.addColumnPrimaryKey( _
              peptideColEnum2.enumScoreWithMS3, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumDescendingSort, _
              False)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumMeasuredMCR2, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumAscendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumQueryNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort)

            'MS3 precursor
            mListViewColumnSorter.addColumnPrimaryKey( _
              peptideColEnum2.enumMS3precursorIon, _
              datatypeEnum.enumText, _
              sortingDirectionEnum.enumDescendingSort, _
              False)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumMeasuredMCR2, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumAscendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumQueryNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort)

            'PTM score. Descending
            mListViewColumnSorter.addColumnPrimaryKey( _
              peptideColEnum2.enumScoreWithPTM, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumDescendingSort, _
              False)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumSequence, _
              datatypeEnum.enumText, _
              sortingDirectionEnum.enumAscendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumQueryNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort)

            'MCR
            mListViewColumnSorter.addColumnPrimaryKey( _
              peptideColEnum2.enumMeasuredMCR2, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumAscendingSort, _
              False)
            mListViewColumnSorter.addColumnSecondaryKey( _
              peptideColEnum2.enumQueryNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort)


        End If 'Visual sorting, columns in the peptide list.

        'Changed PM_DISPLAY_SCORE 2008-06-25
        mScratchSB = New StringBuilder(50)

        'Note: mOptions is set Init() while this is set here. Which is correct.
        'Changed PM_HIGHER_LEVEL_PROCESSING 2008-09-04
        mExperimentSettings = anInExperimentSettings

        Init( _
          aProtHitStru, aWiffFileName, aWiffCompQuantFileName, _
          aProteinListForm, _
          aWiffFileInfo, aOptions, _
          aProteinListIndex, anInRawFiles, anInApplication, _
          aRawDataFileHandling, _
          aRecalibrator, _
          aDisplayQueryNumber, _
          aParseIDnumber)
    End Sub 'New()


    'Changed PM_REFACTOR 2003-03-11
    'Outfactored to allow re-initialisation after the initial creation.
    '****************************************************************************
    '*                                                                          *
    '*  Parameters:                                                             *
    '*      aDisplayQueryNumber   A value of zero means that this parameter     *
    '*                            will be ignored. Instead the first peptide    *
    '*                            in whatever sort order is set (e.g.           *
    '*                            descending after score) will be displayed     *
    '*                            instead.                                      *
    '*                                                                          *
    '****************************************************************************
    Public Sub Init( _
      ByRef aProtHitStru As ProteinHitStructure, _
      ByVal aWiffFileName As String, _
      ByVal aWiffCompQuantFileName As String, _
      ByRef aProteinListForm As frmProteinList, _
      ByVal aWiffFileInfo As rawFileInfoStruct, _
      ByRef aOptions As OptionsStruct2, _
      ByVal aProteinListIndex As Integer, _
      ByRef anInRawFiles() As massSpectrometryBase.fileSpecStructure, _
      ByRef anInApplication As quantApplication, _
      ByRef aRawDataFileHandling As massSpectrometryBase.rawDataFileHandling, _
      ByRef aRecalibrator As SDUPrecalibrator, _
      ByVal aDisplayQueryNumber As Integer, _
      ByVal aParseIDnumber As Integer _
      )
        '  ByVal anA As Double, ByVal aB As Double, _
        'aOptions: const ref

        mStartingUp = True

        'Changed PM_ID_SILACDISH 2008-07-15
        clearOrangMessageBox() 'Clear any design time value...

        'Changed PM_MS3INTEGRATION 2004-06-03
        mStop = False

        'Changed PM_REFACTOR 2005-08-16
        'mMS3signalForBestScore = Nothing 'To be explicit

        mWiffInfo = aWiffFileInfo

        'Changed PM_REFACTOR 2007-10-30
        'mA = anA
        'mB = aB
        mRecalibrator2 = aRecalibrator

        mProt = aProtHitStru

        'Changed PM_SEVERALWIFFS_EXPORT 2003-08-29
        mRawFiles = anInRawFiles

        'Changed PM_MANUAL_PEPTIDEQUANTSTATUSUPDATE 2003-05-06
        mProteinListIndex = aProteinListIndex

        mFrmProteinList = aProteinListForm

        mOptions = aOptions 'For use in quantArgLabeledProtein() where the
        '                    quatitation window is created and displayed.

        'Changed PM_VARIABLE_XIC_WINDOW 2003-11-27
        mApplication = anInApplication



        'Changed PM_TWOLEVEL_WINDOWNUMBERING_PREFIX 2008-08-21
        mParseIDnumber = aParseIDnumber


        mWiffFileName = aWiffFileName

        If mWiffFileName <> "" Then
            'todo: this doesn't really seem to work.
            If File.GetAttributes(mWiffFileName) = FileAttributes.ReadOnly Then
                MsgBox( _
                  "The wiff file and/or enclosing windows are 'read only'. " & _
                  "Please go to the property windows and uncheck " & _
                  "the 'read only' attribute.")
                Exit Sub
            End If

            'Don't create a raw file object for each protein. Let the client
            'create it and reuse the object for each protein.
            ''Changed PM_REFACTOR 2003-11-21
            'quantApplication.createAndInitRawFileObject( _
            '  mOptions.rawFileMode, aRawFiles, mRawDataFileHandling, _
            '  mWiffInfo.sampleNumberInRawFile)
            mRawDataFileHandling = aRawDataFileHandling
            Trace.Assert(Not mRawDataFileHandling Is Nothing, _
              "PIL ASSERT. mRawDataFileHandling is Nothing!.")
        Else
            staSpectrumInfoEtc.Text = "No valid raw data file (.wiff, .raw of .idx) open)"
        End If

        'Changed PM_ALSO_PRECURSOR_FOR_MS3 2006-10-31. Two more parameters.
        ''Changed PM_REFACTOR 2005-08-11. In init()
        Dim quantitationModesObject As QuantitationModes_moreGeneral = _
          anInApplication.getQuantModes()
        mMS3scorer = _
          New MS3scoring( _
            mRawDataFileHandling, aRecalibrator, _
            quantitationModesObject, _
            aOptions.quantModeCode, mGeneralisedIonSeries)

        'This is necessary if this object has already been used.
        Me.ResetMembers() 'E.g. will clear lsvPeptides and mQueryNumHash.

        'Changed PM_ION_SERIES_DISPLAYOPTION 2008-05-26
        chkShowMatchedIonsOnly.Checked = anInApplication.getShowOnlyMatchedIons()

        Me.DisplayProtInfo() 'This is protein!
        Me.DisplayPeptInfo() 'And this is peptide!

        'Changed PM_ALWAYS_DISPLAY_FIRST_PEPTIDE 2004-11-10
        'Display the first peptide...
        DisplayNthPeptide(0, "", aDisplayQueryNumber)

        'Changed PM_ID_SILACDISH 2008-07-15
        'Moved after DisplayNthPeptide(). Is this a problem?
        mStartingUp = False
    End Sub 'Init()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub DisplayProtInfo()

        'Display the protein info in the title and the text box.

        'Changed PM_TWOLEVEL_WINDOWNUMBERING_PREFIX 2008-08-21
        ''Changed PM_CONSISTENCY 2004-08-06
        ''Me.Text = "Protein Information for:  Hit: " & mProt.hitNumber & _
        ''  "   " & mProt.accNum & "   " & mProt.protName
        'Me.Text = "Protein Validation. Hit: " & mProt.hitNumber & _
        '  "   " & mProt.accNum & "   " & mProt.description2
        Me.Text = _
          "#" & mParseIDnumber & ", " & _
          " hit " & mProt.hitNumber & _
          ". Protein Validation. " & mProt.accNum & _
          ". " & mProt.description3

        'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-27
        Dim pepIter As peptideListIterator = _
          New peptideListIterator(mProt.peptides)
        Dim token As Integer = pepIter.getIterToken()


        'Changed PM_REFACTOR 2006-03-15
        'Dim protPeptides As Integer = mProt.pepts.Count
        Dim protPeptides As Integer = mProt.peptides.peptideCount2(token)

        Dim str As String = _
          "Out of " & protPeptides & " peptides: " & _
          mProt.peptsInABC & " in A,B,C."

        str &= "          Score in A,B,C: " & mProt.scoreInABC
        str &= "         MW: " & (mProt.monoIsotopicMass / 1000.0).ToString("###.00")

        lblProtInfo.Text = str
    End Sub 'DisplayProtInfo


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub patchRetentionTimes( _
      ByRef aProtHitStru As ProteinHitStructure)

        Dim pept As PeptideHitStructure = _
          PeptideHitStructure.blankPeptide() 'Keep compiler happy.

        Dim pepIter As peptideListIterator = _
          New peptideListIterator(aProtHitStru.peptides)
        While Not pepIter.nextPeptide(pept)

            'We use this as a flag to see if we have already patched....
            If pept.retentionTimeEndMinutes < 0.00001 AndAlso _
               pept.retentionTimeEndMinutes > -0.00001 Then

                'This actually a spectrum number divided by 60 and perhaps rounded...
                Dim retT As Double = pept.retentionTimeStartMinutes

                'Note: CInt actually ****rounds**** so we should NOT add 0.5......
                Dim spectrumNum As Integer = CInt(retT * 60.0)

                Dim realRetentionTime_Seconds As Double = _
                  mRawDataFileHandling.SpectrumNumber2RetentionTime( _
                    spectrumNum, 0)
                Dim realRetentionTime_Minutes As Double = _
                  realRetentionTime_Seconds / 60.0

                Dim factor As Double = _
                  realRetentionTime_Minutes / pept.retentionTimeStartMinutes

                pept.retentionTimeStartMinutes = realRetentionTime_Minutes
                pept.retentionTimeEndMinutes = 7777.7777777777774 'Flag that we have patched....
            Else
                Dim peter9 As Integer = 9
            End If

            pepIter.updateCurrentPeptide(pept)
        End While 'Through peptides.

    End Sub 'patchRetentionTimes


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub patchRetentionTimesFromSpectrumNumber( _
      ByRef aProtHitStru As ProteinHitStructure, _
      ByRef aRawDataFile As massSpectrometryBase.rawDataFileHandling _
      )

        Dim pept As PeptideHitStructure = _
          PeptideHitStructure.blankPeptide() 'Keep compiler happy.

        Dim pepIter As peptideListIterator = _
          New peptideListIterator(aProtHitStru.peptides)

        While Not pepIter.nextPeptide(pept)
            Dim specNum As Integer = pept.spectrumNumber
            Trace.Assert(specNum <> 0, "PIL ASSERT. Spectrum number not initialised.")

            If specNum > 0 Then
                Dim realRetentionTime_Seconds As Double = _
                  aRawDataFile.SpectrumNumber2RetentionTime(specNum, 0)

                Dim realRetentionTime_Minutes As Double = _
                  realRetentionTime_Seconds / 60.0

                pept.retentionTimeStartMinutes = realRetentionTime_Minutes
                pept.retentionTimeEndMinutes = 7777.7777777777774 'Flag that we have patched....

                'Changed PM_FINNEGAN_RETENTION_TIME 2003-11-20
                'This is different from the other patch function,
                pept.MSMSretentionTimeMinutes = realRetentionTime_Minutes

                pepIter.updateCurrentPeptide(pept)
            End If
        End While 'Through peptides.

    End Sub 'patchRetentionTimesFromSpectrumNumber


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub DisplayPeptInfo()

        'Changed PM_VISUAL_COLUMNSORT_TROUBLE 2006-03-01
        'This is may or may not be required to avoid getting into trouble
        'when we are re-using this window.
        'Sorting may be done at arbitrary times while building up rows for
        'the list, resulting in comparing in-complete rows with
        'complete rows. The result may be exceptions in the Compare() function.
        lsvPeptides.ListViewItemSorter() = Nothing

        'Changed PM_GENERALISED_QUANT_MODE 2003-12-09
        Dim quantitationModesObject As QuantitationModes_moreGeneral = _
          mApplication.getQuantModes()


        'Changed PM_ID_SILACDISH 2008-07-15
        Dim addedPeptideLines As Integer = 0
        Dim addedPeptideLinesInDish1 As Integer = 0

        'Collect all the peptides, and put them as items in a listView table
        'which is sorted by Mascot score (without parens). Use the original
        'colour for the item and have a checked column.


        'Changed PM_PROTEINVALIDATION_SPEEDUP 2008-10-01
        mApplication.startStopWatch() 'Internal timing for testing.

        'Changed PM_PROTEINVALIDATION_SPEEDUP 2008-10-01
        lsvPeptides.BeginUpdate()


        Dim pept As PeptideHitStructure = _
          PeptideHitStructure.blankPeptide() 'Keep compiler happy.

        Dim pepIter As peptideListIterator = _
          New peptideListIterator(mProt.peptides)

        'Changed PM_TYPESAFE 2008-12-02. Creation moved close to 
        '  where we need it the first time. We now also properly
        '  preallocate the hash...
        Dim pLen As Integer = _
          mProt.peptides.peptideCount2(pepIter.getIterToken()) 'Is there
        '   a hidden cost here??
        mQueryNum2PeptTokenHash2 = _
          New Dictionary(Of Integer, Integer)(pLen)

        Dim peptideToken As Integer
        While Not pepIter.nextPeptide(pept, peptideToken)
            'Changed PM_ACCEPTNEXTPROTEIN_CRASH 2003-04-23
            Dim oldStartingUp As Boolean = mStartingUp
            mStartingUp = True 'To prevent side-effects when the Add() just
            '  below is executed. For instance the event XYZ will be send
            '  resulting in an attempt to read from the not yet
            '  finished (visual view).....

            If True Then
                Dim newItem As ListViewItem = _
                  lsvPeptides.Items.Add(pept.AASequence)
                With newItem

                    Dim columns As Integer = mColumnMapper.columnCount()
                    Dim j As Integer
                    For j = 1 To columns
                        .SubItems.Add("...")
                    Next j

                    'Changed PM_ID_SILACDISH 2008-07-15
                    addedPeptideLines += 1

                    Trace.Assert(pept.MSMSretentionTimeMinutes > 0.0, _
                      "PIL ASSERT. MSMSretentionTimeMinutes is negative or zero: ." & _
                      pept.MSMSretentionTimeMinutes)
                    If pept.verified Then
                        .Checked = True
                    End If
                    If pept.counted Then
                        .BackColor = Color.LightGray

                        'Gray is a color, Grey is a *colour*.
                    End If
                    If pept.MascotColour = _
                         mascotColourEnum.enumBoldRed Or _
                       pept.MascotColour = _
                          mascotColourEnum.enumLightRed Then

                        .ForeColor = Color.Red
                    Else
                        .ForeColor = Color.Black
                    End If

                    If pept.MascotColour = _
                         mascotColourEnum.enumBoldBlack Or _
                       pept.MascotColour = _
                         mascotColourEnum.enumBoldRed Then

                        .Font = New Font(Me.Font, FontStyle.Bold)
                    End If

                    Dim toAdd As String
                    If pept.scoreInParens Then
                        toAdd = "(" & pept.MascotScore2.ToString("0.0") & ")"
                    Else
                        toAdd = pept.MascotScore2.ToString("0.0")
                    End If
                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumMascotScore, toAdd)

                    'Changed PM_ID_SILACDISH 2008-07-15
                    Dim indexOneBased As Integer = pept.SILACdishIndex + 1
                    If indexOneBased = 1 Then
                        addedPeptideLinesInDish1 += 1
                    End If
                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumID_SILACdish, _
                      indexOneBased.ToString)

                    'Now add the delta score. This is between the first and second
                    'rank, so if rank is 2 is is negative.
                    If True Then
                        Dim deltaScoreStr As String = _
                          (pept.firstScore - pept.secScore).ToString("0")
                        If Not pept.rank = 1 Then
                            deltaScoreStr = "-" & deltaScoreStr
                        End If
                        mColumnMapper.updateListItem( _
                          newItem, peptideColEnum2.enumMascotDeltaScore, _
                          deltaScoreStr)
                    End If

                    If pept.seq1Unique Then
                        toAdd = "Y"
                    Else
                        toAdd = "N"
                    End If
                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumNumSeqOcc, toAdd)

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumMascorCheckBoxChecked, _
                      pept.checkboxChecked.ToString)

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumMascotRank, _
                      pept.rank.ToString)

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumMissedCleavages, _
                      pept.missedCleavages.ToString)

                    'Changed PM_CHARGE_IN_PROTVAL 2008-05-20
                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumCharge, _
                      pept.charge.ToString())

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumMeasuredMCR2, _
                      pept.calibratedMeasuredMCR.ToString("####.000"))

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumCalculatedMass, _
                      pept.MascotCalculatedMass.ToString("####.000"))

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumRelativeError, _
                      pept.relativeErrorForPeptideMass_PPM.ToString("F1"))

                    Dim str As String = _
                      MascotResultParser.formatMods( _
                        pept, quantitationModesObject)
                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumModStr, _
                      str)

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumQueryNumber, _
                      pept.queryNumber.ToString)

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumRetentionTime, _
                      pept.MSMSretentionTimeMinutes.ToString("##.00"))

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumPeriod, _
                      pept.period2.ToString)

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumExperiment, _
                      pept.experimentNumber.ToString)

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumCycle, _
                      pept.cycle.ToString)

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumMS3precursorIon, _
                      PILInputOutput.emptyForNothing(pept.MS3precursorStr))

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumScoreWithMS3, _
                      pept.MascotScorePlusMS3Score.ToString("F1"))

                    'Later: refactor these 3 lines.
                    Dim PTMinfoSB As StringBuilder = New StringBuilder
                    Dim highestPTMscore As Double
                    PTMscorer.formatSomeCombinations( _
                      pept.AASequence, pept.PTMs2, True, quantitationModesObject, _
                      PTMinfoSB, _
                      highestPTMscore)
                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumPTMinfo, _
                      PTMinfoSB.ToString)

                    Dim PTMscore As Double = highestPTMscore
                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumScoreWithPTM, _
                      PTMscore.ToString("F1"))

                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumLeftFlankingAA, _
                      ChrW(pept.leftFlankAA))
                    mColumnMapper.updateListItem( _
                      newItem, peptideColEnum2.enumRightFlankingAA, _
                      ChrW(pept.rightFlankAA))

                    'Now add this item to hash table to later retrieve
                    'the index using the query number.

                    mQueryNum2PeptTokenHash2.Add(pept.queryNumber, peptideToken)
                End With
            End If

            'Changed PM_ACCEPTNEXTPROTEIN_CRASH 2003-04-23
            mStartingUp = oldStartingUp

            'Changed PM_UNNECESSARY_PEPTIDELISTR_UPDATE 2006-03-17. Disabled. There
            'seems to be no change of the peptide...
            ''Changed PM_REFACTOR 2006-03-15
            'd$ Changed PM_MSWINDOW 2003-03-27
            ''mProt.pepts(i) = peptHit 'Write-back. Why is this necessary? Because
            'd$   a side-effect of the above is to set some fields, e.g. MascotColor.
            'pepIter.updateCurrentPeptide(pept)
        End While 'Through peptides.

        If True Then
            'Changed PM_COLUMNSORT_BY_KEYBOARD 2008-11-11
            mListViewColumnSorter.menuItemsForSortableColumns( _
              mnuView, _
              AddressOf arrangeProteinsMenuSubItemsOnClick)

            'Changed PM_COLUMNSORT_BY_KEYBOARD 2008-11-11
            'Dim keylist As List(Of sortKeyStructure) = _
            '  mColumnSortSpecificationHash(peptideColEnum2.enumMascotScore)
            'mListViewColumnSorter.prepareSort(keylist)
            mListViewColumnSorter.prepareSortAndSort( _
              peptideColEnum2.enumMascotScore, Nothing)

            lsvPeptides.ListViewItemSorter() = mListViewColumnSorter
        End If

        'lsvPeptides.Sort()  Not needed. Happens by the assignment above.

        'Changed PM_PROTEINVALIDATION_SPEEDUP 2008-10-01
        lsvPeptides.EndUpdate()

        'Changed PM_PROTEINVALIDATION_SPEEDUP 2008-10-01
        If True Then 'Block. Internal timing for testing.
            Dim memDiff_MB As Double
            Dim parseTimeSecs As Double = _
              mApplication.stopStopWatch(memDiff_MB)

            Dim peter2 As Integer = 2
        End If

        'Now select the top peptide to be displayed.  ???

        'Issue warning if it appears the wrong quantitation mode
        'has been selected or if the SILAC modifications have
        'not been recognised.
        '
        'Rules:
        '
        '  more than 90 percent of the peptides are in the
        '  first SILAC dish.
        '
        '    and
        '
        '  more than 10 peptides in the peptide list
        '
        '    and
        '
        '  there is more than 1 SILAC dish
        '
        If True Then
            'Changed PM_ID_SILACDISH 2008-07-15
            Dim fractionInFirstDish As Double = _
              addedPeptideLinesInDish1 / addedPeptideLines

            'Refactoring opportunity: should we instead require number
            '  of dishes when an instance of this class in created. We
            '  have copied from the constructor of file frmProteinList.vb.
            Dim dishes As Integer
            If True Then
                Dim curQuantMode As generalisedQuantModeStructure = _
                  quantitationModesObject.getQuantitationMode( _
                    mOptions.quantModeCode)
                dishes = _
                  curQuantMode.dishes_StartingFromDish2.Count + 1
            End If

            If fractionInFirstDish > 0.9 AndAlso _
               addedPeptideLines > 10 AndAlso _
               dishes > 1 Then

                Dim msgStr As String = _
                  "1. SILAC modifications have not been " & _
                  "recognised or 2. quantitation mode " & _
                  "does not match the content of Mascot result file " & _
                  "(e.g. using a v2.1 mode for a Mascot v2.2 file). or " & _
                  "3. is not SILAC labeled (e.g. keratin)."

                lblExtraInfo.BackColor = Color.Salmon
                lblExtraInfo.Text = msgStr 'Note: it cleared when a peptide
            Else
                Dim peter2 As Integer = 2 'OK...
            End If

        End If

    End Sub 'DisplayPeptInfo()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub lsvPepts_ColumnClick( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.Windows.Forms.ColumnClickEventArgs) _
      Handles lsvPeptides.ColumnClick

        Dim physicalIndex As Integer = anEvent.Column
        Dim ID As peptideColEnum2 = _
          CType( _
            mColumnMapper.columnIndex2itemID(physicalIndex), peptideColEnum2)

        'Changed PM_COLUMNSORT_BY_KEYBOARD 2008-11-11
        'Dim keylist As List(Of sortKeyStructure) = Nothing
        'If mColumnSortSpecificationHash.TryGetValue(ID, keylist) Then
        '    mListViewColumnSorter.prepareSort(keylist)
        '    lsvPeptides.Sort()
        '    lsvPeptides.Refresh()
        'Else
        '    'We have not defined sorting for the column in question.
        '    'Simply ignore the request.
        '    Dim peter1 As Integer = 1
        'End If
        mListViewColumnSorter.prepareSortAndSort(ID, lsvPeptides)

        'As a response to a column click we sort the column in the
        'appropriate(order). Don't do this now because we don't keep
        'the datastruct and the table in sync.
    End Sub 'lsvPepts_ColumnClick


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuClose1_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuClose.Click

        Me.Close()
    End Sub 'mnuClose1_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSelectFirstPept_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuSelectFirstPept.Click

        DisplayNthPeptide(0, "", 0)
    End Sub 'mnuSelectFirstPept_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub cmdSelectNextPeptide_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles cmdSelectNextPeptide.Click

        If mCurrentlySelectedPeptIdx < 0 Then
            mCurrentlySelectedPeptIdx = 0
        Else
            If mCurrentlySelectedPeptIdx >= lsvPeptides.Items.Count - 1 Then
                mCurrentlySelectedPeptIdx = mCurrentlySelectedPeptIdx '????
            Else
                mCurrentlySelectedPeptIdx += 1
            End If
        End If

        Me.UpdateCurrSelPept()
        DisplayNthPeptide(mCurrentlySelectedPeptIdx, "", 0)
    End Sub 'cmdSelectNextPeptide_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub lsvPepts_ItemCheck( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.Windows.Forms.ItemCheckEventArgs) _
      Handles lsvPeptides.ItemCheck

        If Not mStartingUp Then
            If Not mAvoidHandlingPeptideCheckedEvent Then
                synchronizeVerifiedAndCheckedStatus( _
                  anEvent.Index, CBool(anEvent.NewValue))
            Else
                Dim peter9 As Integer = 9
            End If
        End If
    End Sub 'lsvPepts_ItemCheck


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub lsvPepts_DoubleClick( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles lsvPeptides.DoubleClick

        Dim visualIndex As Integer = lsvPeptides.SelectedIndices.Item(0)

        If mStateDbl = STATE_DBL_SINGLECLICK Then
            'Re-establish check status - it
            'was changed in lstProtHits_ItemCheck().
            Dim savedHandleStatus As Boolean = mAvoidHandlingPeptideCheckedEvent
            mAvoidHandlingPeptideCheckedEvent = True
            lsvPeptides.Items(visualIndex).Checked = mRecentCheckedStatus
            mAvoidHandlingPeptideCheckedEvent = savedHandleStatus

            'Also set underlying datastructure just in case.
            'Dim idx As Integer
            Dim token As Integer
            Dim pept2 As PeptideHitStructure = _
              getPeptideFromVisualIndex(visualIndex, token)
            pept2.verified = mRecentCheckedStatus

            'Changed PM_REFACTOR 2006-03-15
            'mProt.pepts(idx) = thePept2 'write-back
            mProt.peptides.updatePeptideByToken(token, pept2)
        Else
            Dim peter4 As Integer = 4
        End If

        synchronizeVerifiedAndCheckedStatus( _
          visualIndex, lsvPeptides.Items(visualIndex).Checked)
        Me.DisplayNthPeptide(visualIndex, "", 0)

        'Changed PM_DOUBLE_OFFCLICK 2003-12-16
        mStateDbl = STATE_DBL_WAITINGCLICKS
    End Sub 'lsvPepts_DoubleClick


    'Changed PM_MOUSE_IS_BAD 2004-05-04
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub lsvPepts_KeyUp( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.Windows.Forms.KeyEventArgs) _
      Handles lsvPeptides.KeyUp

        If anEvent.KeyCode = Keys.Enter Or anEvent.KeyCode = Keys.Return Then
            If lsvPeptides.SelectedIndices.Count > 0 Then
                Dim visualIndex As Integer = lsvPeptides.SelectedIndices.Item(0)
                Me.DisplayNthPeptide(visualIndex, "", 0)
            Else
                Dim peter63 As Integer = 63
            End If
        Else
            Dim peter92 As Integer = 92
        End If
    End Sub 'lsvPepts_KeyUp


    'Changed PM_REFACTOR 2008-03-12
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function readOffQueryNumber( _
      ByVal aVisualIndex As Integer) _
      As Integer

        Dim rowToRead As ListViewItem = lsvPeptides.Items(aVisualIndex)
        Dim qNumStr As String = _
          mColumnMapper.readOffListItem( _
            rowToRead, _
            peptideColEnum2.enumQueryNumber)

        Dim qNum As Integer = -1
        If IsNumeric(qNumStr) Then
            qNum = CInt(qNumStr)
        Else
            MsgBox( _
              "Could not extract query number from table. Visual index: " & _
              aVisualIndex & ".")
        End If

        Return qNum
    End Function 'readOffQueryNumber


    'Changed PM_REFACTOR 2005-10-26
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function getPeptideTokenFromVisualIndex( _
      ByVal aVisualIndex As Integer) _
      As Integer

        Dim toReturn As Integer = -1

        'Dim rowToRead As ListViewItem = lsvPeptides.Items(aVisualIndex)
        'Dim qNumStr As String = _
        '  mColumnMapper.readOffListItem( _
        '    rowToRead, _
        '    peptideColEnum2.enumQueryNumber)

        'Dim qNum As Integer
        'If IsNumeric(qNumStr) Then
        '    qNum = CInt(qNumStr)
        'Else
        '    MsgBox("Could not extract query number from table")
        'End If
        Dim qNum As Integer = readOffQueryNumber(aVisualIndex)

        Trace.Assert(mQueryNum2PeptTokenHash2.Count > 0, _
          "PIL ASSERT. mQueryNumHash is empty!.")
        toReturn = mQueryNum2PeptTokenHash2(qNum)

        Return toReturn
    End Function 'getPeptideTokenFromVisualIndex


    'Changed PM_REFACTOR 2003-12-16
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function getPeptideFromVisualIndex( _
      ByVal aVisualIndex As Integer, _
      ByRef anOutPeptideToken As Integer) _
      As PeptideHitStructure

        Dim peptideToken As Integer = _
          Me.getPeptideTokenFromVisualIndex(aVisualIndex)

        Dim pept2 As PeptideHitStructure = _
          PeptideHitStructure.blankPeptide() 'Keep compiler happy.

        mProt.peptides.peptideByToken(peptideToken, pept2)

        anOutPeptideToken = peptideToken
        Return pept2
    End Function 'getPeptideFromVisualIndex


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub synchronizeVerifiedAndCheckedStatus( _
      ByVal aIndex As Integer, ByVal aChecked As Boolean)

        'We need to syncronize on three occasions:
        '1. User verified or rejected the peptide using the button
        '2. User double clicked the row
        '3. User clicked directly into the checkbox Todo: implement this. (How??)
        UpdateCurrSelPept()

        Dim token As Integer
        Dim pept1 As PeptideHitStructure = _
          getPeptideFromVisualIndex(aIndex, token)

        'Changed PM_DOUBLE_OFFCLICK 2003-12-16
        mRecentCheckedStatus = pept1.verified
        mStateDbl = STATE_DBL_SINGLECLICK

        pept1.verified = aChecked

        'Changed PM_REFACTOR 2006-03-16
        'mProt.pepts(idx) = thePept1 'write-back
        mProt.peptides.updatePeptideByToken(token, pept1)
    End Sub 'synchronizeVerifiedAndCheckedStatus


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub frmProtValidation_KeyDown( _
      ByVal aSender As Object, _
      ByVal anEvent As System.Windows.Forms.KeyEventArgs) _
      Handles MyBase.KeyDown

        'Here we trap the arrow keys. Right or down means advance to 
        'the next in the list. Up or left means go back to the 
        'previous.
        '<alt> right arrow means verify peptide and advance.
        '<alt shift> right arrow verifies the protein and moves to the next.

        If anEvent.KeyCode = Keys.Right Or anEvent.KeyCode = Keys.Down Then
            If anEvent.Shift Then
                'move to the next protein and ask about protein verification
                'mFrmProteinList.checkProteinandSelectNext()
            Else
                If anEvent.Modifiers = Keys.Alt Then
                    'check current peptide and move to next
                Else
                    'just move to next peptide. Move to first after the last
                    If lsvPeptides.Items.Count - 1 = _
                      lsvPeptides.SelectedIndices(0) Then

                        lsvPeptides.Items(0).Selected = True
                    End If
                    lsvPeptides.Items( _
                      lsvPeptides.SelectedIndices(0) + 1).Selected = True
                End If
            End If
        End If
    End Sub 'frmProtValidation_KeyDown


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuProteinCorrectAndMoveToNextProtein_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuProteinCorrectAndMoveToNextProtein.Click

        proteinMoveToNextProtein(True)
    End Sub 'mnuProteinCorrectAndMoveToNextProtein_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuProteinNotCorrectandMoveToNextProtein_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuProteinNotCorrectandMoveToNextProtein.Click

        proteinMoveToNextProtein(False)
    End Sub 'mnuProteinNotCorrectandMoveToNextProtein_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub MoveNextProtein()
        Dim protNum As Integer = mProt.hitNumber

        Dim atTheEnd As Boolean = _
          Not (mFrmProteinList.GetNextProtein(mProt, mProteinListIndex))

        If atTheEnd Then
            MsgBox("Arrived at last protein in the list")
        End If
    End Sub 'MoveNextProtein


    'Outfactored from ResetValues() to be used from Init().
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub ResetMembers()
        mCurrentlySelectedPeptIdx = 0

        If Not mQueryNum2PeptTokenHash2 Is Nothing Then
            mQueryNum2PeptTokenHash2.Clear()
        End If

        'Changed PM_REFACTOR 2005-02-25
        'mCurrentlyZoomedFrag = 0
        mMSMSFragments.reset()

        'Changed PM_REFACTOR 2005-08-16
        'mMS3Fragments.reset()
        mMS3scorer.reset2()

        lsvPeptides.Items.Clear()
        lsvPeptides.ListViewItemSorter = Nothing  'This is crucial otherwise
        '  the table will still try to sort with the sorter it had last 
        '  time and with the incorrect number of sortable items!!!

        clearPTMscoreSelected()
    End Sub 'ResetMembers()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub ResetValues()

        Me.ResetMembers()

        ' todo: implement sort order like this: 
        '  lsvPeptides.Sorting=SortOrder.Ascending

        Me.DisplayProtInfo()
        Me.DisplayPeptInfo()
        Me.UpdateCurrSelPept()

        'Changed PM_ALWAYS_DISPLAY_FIRST_PEPTIDE 2004-11-10
        'Display the first peptide...
        DisplayNthPeptide(0, "", 0)
    End Sub 'ResetValues()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuShowMS1_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuShowMS1.Click

        'Display the MS1 spectrum associated with the current MS/MS spectrum.
        ' mWiffFileName()
        Trace.Assert(False, "PIL ASSERT. This should never happen...")
    End Sub 'mnuShowMS1_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuMarkPeptVerifiedAndMoveToNext_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuMarkPeptVerifiedAndMoveToNext.Click

        MarkPeptVerifiedAndMoveToNext()
    End Sub 'mnuMarkPeptVerifiedAndMoveToNext_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuMarkPeptNotVerifAndMoveNext_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuMarkPeptNotVerifAndMoveNext.Click

        MarkPeptNotVerifAndMoveNext()
    End Sub 'mnuMarkPeptNotVerifAndMoveNext_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub btnVerifyAndNext_Click( _
      ByVal sender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles btnVerifyAndNext.Click

        MarkPeptVerifiedAndMoveToNext()
    End Sub 'btnVerifyAndNext_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub btnRejectAndNext_Click( _
      ByVal sender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles btnRejectAndNext.Click

        MarkPeptNotVerifAndMoveNext()
    End Sub 'btnRejectAndNext_Click


    'Changed PM_REFACTOR 2007-09-25. No longer needed. If we again need
    '  this functionality in this form then it should
    '  be implemented in another way.
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub btnZoomPrev_Click( _
    '   ByVal sender As System.Object, ByVal anEvent As System.EventArgs) _
    '   Handles btnZoomPrev.Click
    ' 
    '     ZoomPrevFragment()
    ' End Sub 'btnZoomPrev_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub btnCycleSeq_Click( _
      ByVal sender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles btnCycleTopSequences.Click

        Me.CycleSequences()
    End Sub 'btnCycleSeq_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub MarkPeptVerifiedAndMoveToNext()

        'Todo: this causes a crash if nothing is selcted (even though
        'it shouldn't).
        'Best will be to always load the top peptide.
        Dim idx As Integer = lsvPeptides.SelectedIndices.Item(0)
        lsvPeptides.Items(idx).Checked = True

        synchronizeVerifiedAndCheckedStatus(idx, lsvPeptides.Items(idx).Checked)
        If idx = lsvPeptides.Items.Count - 1 Then
            MsgBox("Last peptide reached")
        Else
            lsvPeptides.Items(idx + 1).Selected = True
            mCurrentlySelectedPeptIdx = idx + 1
            Me.UpdateCurrSelPept()
            DisplayNthPeptide(idx + 1, "", 0)
        End If
    End Sub 'MarkPeptVerifiedAndMoveToNext


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub MarkPeptNotVerifAndMoveNext()

        Dim idx As Integer = lsvPeptides.SelectedIndices.Item(0)
        lsvPeptides.Items(idx).Checked = False
        synchronizeVerifiedAndCheckedStatus(idx, lsvPeptides.Items(idx).Checked)
        If idx = lsvPeptides.Items.Count - 1 Then
            MsgBox("Last peptide reached")
        Else
            lsvPeptides.Items(idx + 1).Selected = True
            mCurrentlySelectedPeptIdx = idx + 1
            Me.UpdateCurrSelPept()
            DisplayNthPeptide(idx + 1, "", 0)
        End If
    End Sub 'MarkPeptNotVerifAndMoveNext


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub clearOrangMessageBox()

        Dim someOrigColour As Color = Color.FromName("Control")
        lblExtraInfo.BackColor = someOrigColour
        lblExtraInfo.Text = "" 'Clear any design time value...
    End Sub 'clearOrangMessageBox()


    'Changed PM_REFACTOR 2008-10-11. New, single, function instead of two nearly identical.
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub proteinMoveToNextProtein(ByVal aProteinIsCorrect As Boolean)

        'Note: there seems to be 6 sets of calls to this function, of which
        '      only 2 are necessary. Eliminate the other 4 - they are 
        '      probably from buttons/events that are no longer in use.


        'Changed PM_QUANTMODE_WARNING_CLEARED 2008-10-11
        mStartingUp = True 'Misuse of this flag??
        clearOrangMessageBox()


        'Report this to main form and table then get next protein.
        mFrmProteinList.MarkProteinAsChecked(mProt.hitNumber, aProteinIsCorrect) '
        Me.MoveNextProtein()
        Me.ResetValues()

        'Changed PM_QUANTMODE_WARNING_CLEARED 2008-10-11
        mStartingUp = False 'Misuse of this flag??
    End Sub 'proteinMoveToNextProtein


    'Changed PM_REFACTOR 2007-09-25. No longer needed. If we again need
    '  this functionality in this form then it should
    '  be implemented in another way.
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub ZoomNextFragment()
    ' 
    '     'What about MS3??
    '     ZoomFragment(mMSMSFragments.nextFragment())
    ' End Sub 'ZoomNextFragment


    'Changed PM_REFACTOR 2007-09-25. No longer needed. If we again need
    '  this functionality in this form then it should
    '  be implemented in another way.
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub ZoomPrevFragment()
    ' 
    '     'What about MS3??
    '     ZoomFragment(mMSMSFragments.previousFragment())
    ' End Sub 'ZoomPrevFragment


    'Changed PM_REFACTOR 2007-07-22. Not currently used.
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub PreviousMS1()
    '     'todo: keep from falling of lower edge (i.e. zero cycle)
    '     mCurrCycle -= 1
    '     DisplayMS1()
    ' End Sub 'PreviousMS1


    'Changed PM_REFACTOR 2007-07-22. Not currently used.
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub NextMS1()
    '     'todo: limit to last cycle
    '     mCurrCycle += 1
    '     DisplayMS1()
    ' End Sub 'NextMS1


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub Integrate(ByVal aMass As Double)
        'integrates at 'aMass'
    End Sub 'Integrate


    'Not used. Delete it?
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub QuantitateComparative()
    '
    '     Trace.Assert(mOptions.rawFileMode = rawFileModeEnum.enumAnalyst, _
    '       "PIL ASSERT. Analyst raw file mod expected. Old code....")
    '
    '     'Strategy is to get the currently selected peptide, go into the retention time of the same
    '     'area in the other wiff file and count up the events there
    '     'about - 2 min to + 2 min
    '     'Todo: modularize these two functions
    '
    '     'First map from the selected table index to the index in the mProt.pepts struct\
    '     'Todo: currently selected peptide is not relevant but the one that was displayed in spectrum
    '     'these could be different if user has selected something else in the meantime
    '
    '     'Changed PM_PROTVAL_COLUMNS 2005-02-28
    '     'Dim qNumStr As String = _
    '     '  lsvPeptides.Items(mCurrentlySelectedPeptIdx).SubItems( _
    '     '    peptTbItmColEnum.eQueryNumber).Text
    '     Dim rowToRead As ListViewItem = lsvPeptides.Items(mCurrentlySelectedPeptIdx)
    '     Dim qNumStr As String = _
    '       mColumnMapper.readOffListItem( _
    '         rowToRead, _
    '         peptideColEnum2.enumQueryNumber)
    '
    '     Dim qNum As Integer
    '     If IsNumeric(qNumStr) Then
    '         qNum = CInt(qNumStr)
    '     Else
    '         MsgBox("Could not extract query number from table")
    '     End If
    '
    '     Trace.Assert(mQueryNumHash.Count > 0, _
    '       "PIL ASSERT. mQueryNumHash is empty!.")
    '     Dim idx As Integer = CInt(mQueryNumHash(qNum))
    '
    '     Dim thePept As PeptideHitStructure = _
    '       DirectCast(mProt.pepts(idx), _
    '       PeptideHitStructure)
    '
    '     Dim theRT As Double = thePept.MSMSretentionTimeMinutes
    '     Dim theFragMass As Double = thePept.measuredMZ
    '     Dim theActualPeriod As Integer
    '     Dim theCycle As Integer
    '
    '     Dim theNumExp As Integer = mWFComp.GetNumberOfExperiments(1, 0)
    '
    '     'Note: 3rd and 4th parameter to GetActualPeriodAndCycleFromTime() are output parameters.
    '     mWFComp.GetActualPeriodAndCycleFromTime( _
    '       1, 0, CSng(theRT * 60), theActualPeriod, theCycle)
    '
    '     Dim deltaT As Single
    '     Dim theStartT As Single = _
    '       mWFComp.GetActualTimeFromPeriodAndCycle(1, 0, 0, theCycle)
    '     deltaT = _
    '       theStartT - _
    '       mWFComp.GetActualTimeFromPeriodAndCycle(1, 0, 0, theCycle - 1)
    '
    '     Dim theT As Single
    '
    '     'Dim data As New FMANSpecDataClass()
    '     'note: the routine must be called with retention time in seconds!!
    '     Call mCompData_2.SetSpectrum( _
    '       mWiffInfo.sampleNumberInRawFile, 0, 0, theStartT, theStartT)
    '
    '     Dim i, j As Integer
    '     'Dim MAX_Y_VALUES As Integer = 500
    '     'Dim yArr(MAX_Y_VALUES) As Double 'can hold up to 500 yValues
    '     'change to - 5 minutes to + 5 minutes from - 2 to + 2 minutes
    '     Dim iLower As Integer = CInt(-5 * 60 / deltaT)
    '     Dim iHigher As Integer = CInt(+5 * 60 / deltaT)
    '     Dim deltaMass As Double = 0.1 'look in +- 0.1 Da
    '     Dim startPT, stopPT As Integer '
    '     Dim xMax, yMax As Double
    '     Dim yMinPt, yMaxPt As Integer
    '
    '     Dim centrXArr(100) As Double
    '     Dim centrYArr(100) As Double
    '     Dim xVal, ySum, yVal, xySum, yOver50Percent As Double
    '
    '     Dim T1 As Date = Now()
    '     Dim TS As TimeSpan
    '     Dim thePt As Integer
    '     Dim theXVal As Double
    '
    '     For i = iLower To iHigher
    '         theStartT = mWFComp.GetActualTimeFromPeriodAndCycle(1, 0, 0, theCycle + i)
    '         Call mCompData_2.SetSpectrum( _
    '           mWiffInfo.sampleNumberInRawFile, 0, 0, theStartT, theStartT)
    '         mCompData_2.GetClosestPointNumberForXValue( _
    '           theFragMass - deltaMass, WhichClosestPointType.CLOSEST_POINT, startPT)
    '         mCompData_2.GetClosestPointNumberForXValue( _
    '           theFragMass + deltaMass, WhichClosestPointType.CLOSEST_POINT, stopPT)
    '         mCompData_2.GetYValueRangeForXValueRange( _
    '           theFragMass - deltaMass, theFragMass + deltaMass, yMinPt, yMaxPt)
    '         mCompData_2.GetDataPoint(yMaxPt, xMax, yMax)
    '
    '         For j = startPT To stopPT
    '             mCompData_2.GetDataPoint(j, xVal, yVal)
    '             'get the center of mass at 50%
    '             yOver50Percent = Math.Max((yVal - (0.5 * yMax)), 0)
    '             ySum += yOver50Percent
    '             xySum += yOver50Percent * xVal
    '         Next j
    '         centrXArr(i - iLower) = xySum / ySum
    '         mCompData_2.GetClosestPointNumberForXValue( _
    '           centrXArr(i - iLower), _
    '           WhichClosestPointType.CLOSEST_POINT, thePt)
    '         mCompData_2.GetDataPoint(thePt, theXVal, centrYArr(i - iLower))
    '     Next i
    '
    '     Dim measMass, xMean, xSigma As Double
    '     Dim count As Integer
    '
    '     For i = 0 To 100 - 1
    '         If (centrYArr(i) > 100) Then 'only count rates over 100
    '             xMean += centrXArr(i)
    '             count += 1
    '         End If
    '     Next
    '
    '     xMean /= count
    '
    '     For i = 0 To 100 - 1
    '         If (centrYArr(i) > 100) Then
    '             xSigma += (centrXArr(i) - xMean) * (centrXArr(i) - xMean)
    '         End If
    '     Next
    '     xSigma /= (count - 1)
    '     xSigma = Math.Sqrt(xSigma)
    '
    '     'now do the quantitation:
    '     Dim totalY As Double
    '     Dim background As Double = 20
    '     count = 0
    '
    '     For i = 0 To 100 - 1
    '         If (centrYArr(i) > background) Then
    '             totalY += (centrYArr(i) - background)
    '             count += 1
    '         End If
    '     Next
    '
    '     staSpectrumInfoEtc.Text &= "  Comp = " & totalY.ToString("####")
    '
    '     'Hack: we have to change some stuff so one can see the new spectrum
    ' End Sub 'QuantitateComparative()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub UpdateCurrSelPept()
        'Makes sure that the mCurrSelPept is syncronized with the selected
        'table(index).

        'Changed PM_REFACTOR 2006-03-16
        Dim token As Integer
        mCurrSelPept = _
          getPeptideFromVisualIndex(mCurrentlySelectedPeptIdx, token)

        'Changed PM_PROTVAL_COLUMNS 2005-02-28
        Dim rowToRead As ListViewItem = _
          lsvPeptides.Items(mCurrentlySelectedPeptIdx)

        'Changed PM_PROTVAL_COLUMNS 2005-02-28
        'mCurrSelPeptMod = _
        '  lsvPeptides.Items(mCurrentlySelectedPeptIdx).SubItems( _
        '    peptTbItmColEnum.eModStr).Text
        mCurrSelPeptMod = _
          mColumnMapper.readOffListItem( _
            rowToRead, _
            peptideColEnum2.enumModStr)
    End Sub 'UpdateCurrSelPept


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub CycleSequences()
        'If we have the second sequence displayed, then display the first 
        'sequence and vice versa.
        'Strip out HTML formating.

        'Changed PM_STRING_CLEANUP 2004-12-14
        'Dim seq1a As String = Regex.Replace(mCurrSelPept.seq1, "<.*?>", "")
        'Dim seq2a As String = Regex.Replace(mCurrSelPept.seq2, "<.*?>", "")
        Dim seq1a As String = ""
        Dim seq2a As String = ""

        Dim seq As String
        'Only works for rank one and two right now but this will be
        'visible in title.

        'Changed PM_REFACTOR 2007-09-25
        ' Dim title As String = Nothing 'Keep compiler happy.
        ' Select Case mOptions.rawFileMode
        '     Case rawFileModeEnum.enumAnalyst
        ' 
        '         'Changed PM_REFACTOR 2007-07-21
        '         'title = _
        '         '  mAxGraphControl_ANALYSTCOM_2.SeriesColl.Item(1).Title.Text
        '         title = _
        '           mAnalystCOM_Graph.axControl_getTitle()
        ' 
        '     Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
        '         'Nothing for now..
        '         title = "Some title..."
        ' 
        '     Case Else
        '         Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
        ' End Select
        Dim title As String = mMSMSdisplay.getTitle()

        If title.IndexOf(seq1a) > 0 Then
            seq = seq2a
        ElseIf title.IndexOf(seq2a) > 0 Then
            seq = seq1a
        Else
            MsgBox("Couldn't get the right sequence")
            Exit Sub

            'Changed PM_STRUCTURED_PROGRAMMING 2005-12-05
            'Note: take care in eliminating this 'Exit Sub', as the first
            '  the if's do not do Exit Sub..
        End If

        Me.writeSeqAndQueryinTitle(seq, mCurrSelPept.queryNumber)

        'Changed PM_GENERALISED_QUANT_MODE 2003-12-10
        Dim quantitationModesObject As QuantitationModes_moreGeneral = _
          mApplication.getQuantModes()

        Dim modificationsList As List(Of List(Of AAsetStruct)) = _
          quantitationModesObject.constructSimpleModificationList( _
            mCurrSelPept.modHits2)

        'What about MS3??
        Dim dummy1 As ionSetStruct
        dummy1.backwardIonDiffs = Nothing 'Keep compiler happy.
        dummy1.forwardIonDiffs = Nothing 'Keep compiler happy.

        'Changed PM_FRAGMENTDISPLAY 2008-05-18. Disable for now.
        'Me.displayBAndYions(seq, True, 7, mCurrSelPept.rawFileID, _
        '  modificationsList, _
        '  mMSMSFragments, _
        '  dummy1, False)
        Trace.Assert(False, _
          "Stop!", "PIL ASSERT. Internal/development assert for stopping execution......")
    End Sub 'CycleSequences()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub quantLabeledProtein( _
      Optional ByVal aNewInstance As Boolean = True)

        'Changed PM_MANUAL_PEPTIDEQUANTSTATUSUPDATE 2003-05-06
        'Error detection.
        Trace.Assert(mProteinListIndex >= 0, _
          "PIL ASSERT. Undefined field: mProteinListIndex.")

        Dim quantWindow2 As frmQuantWindow
        If aNewInstance Or mCurrentQuantWindow Is Nothing Then
            quantWindow2 = New frmQuantWindow( _
                Me, mProt, mRecalibrator2, _
                mWiffInfo, mOptions, mProteinListIndex, _
                mRawDataFileHandling, mRawFiles, mApplication, _
                mParseIDnumber, _
                mExperimentSettings)
        Else
            quantWindow2 = mCurrentQuantWindow
            quantWindow2.Init(Me, mProt, mRecalibrator2, _
                mWiffInfo, mOptions, mProteinListIndex, _
                mRawDataFileHandling, mRawFiles, mApplication, _
                mParseIDnumber)
        End If

        'Changed PM_QUANT_AUTOMATION 2003-03-11
        mCurrentQuantWindow = quantWindow2

        quantWindow2.Show()
    End Sub 'quantLabeledProtein()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuClose1_Click_1( _
      ByVal sender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuClose1.Click

        Me.Close()
    End Sub 'mnuClose1_Click_1


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub ToolBarFormVal_ButtonClick( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.Windows.Forms.ToolBarButtonClickEventArgs)

        Trace.Assert(False, "Stop!", "PIL ASSERT. Internal/development assert for stopping execution......")
    End Sub 'ToolBarFormVal_ButtonClick


    'Changed PM_EXPORT_QUANTIFIED 2003-03-12
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Function getCurrentProtein_quant() As _
      ProteinHitStructure

        Return mCurrentQuantWindow.getCurrentProtein()
    End Function


    'Changed PM_MS3INTEGRATION 2004-06-03
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Function getCurrentProtein_ms3() As _
      ProteinHitStructure

        Return mProt
    End Function 'getCurrentProtein_ms3


    'Changed PM_REFACTOR 2003-04-15
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function ProteinSaveString() As String

        Dim strSB As System.Text.StringBuilder = _
          New System.Text.StringBuilder(24000)

        'Changed PM_REFACTOR 2007-07-18
        'Dim protStr As String = _
        '  mProt.accNum & vbCrLf & _
        '  mProt.monoIsotopicMass.ToString("0.00") & vbTab & " Da " & vbCrLf & _
        '  mProt.description2
        'strSB.Append(protStr)
        strSB.Append(mProt.accNum)
        strSB.Append(vbCrLf)
        strSB.Append(mProt.monoIsotopicMass.ToString("0.00"))
        strSB.Append(vbTab)
        strSB.Append(" Da ")
        strSB.Append(vbCrLf)
        strSB.Append(mProt.description3)


        strSB.Append(vbCrLf)
        strSB.Append("Sequence")
        strSB.Append(vbTab)
        strSB.Append("Checked")
        strSB.Append(vbTab)
        strSB.Append("Mascot score")
        strSB.Append(vbTab)
        strSB.Append("Charge")
        strSB.Append(vbTab)
        strSB.Append("Verified")
        strSB.Append(vbTab)
        strSB.Append("measuredMZ")
        strSB.Append(vbTab)
        strSB.Append("MascotCalculatedMW")
        strSB.Append(vbTab)
        strSB.Append("calibratedMeasuredMZ")
        strSB.Append(vbTab)
        strSB.Append("calibratedMeasuredMass")
        strSB.Append(vbTab)
        strSB.Append("MascotScorePlusMS3Score")
        strSB.Append(vbTab)
        strSB.Append("MS3 precursor")
        strSB.Append(vbTab)
        strSB.Append(vbCrLf)

        'Note: corresponding values for the GUI is filled in in DisplayPeptInfo().
        Dim pept As PeptideHitStructure = _
          PeptideHitStructure.blankPeptide() 'Keep compiler happy.

        Dim pepIter As peptideListIterator = _
          New peptideListIterator(mProt.peptides)
        While Not pepIter.nextPeptide(pept)

            'Changed PM_REFACTOR 2007-07-18
            'strSB.Append(pept.AASequence & vbTab)
            strSB.Append(pept.AASequence)
            strSB.Append(vbTab)

            Dim checkStr As String = "No"
            If pept.checkboxChecked Then
                checkStr = "Yes"
            End If

            'Changed PM_REFACTOR 2007-07-18
            'strSB.Append( _
            '  checkStr & vbTab & _
            '  pept.MascotScore & vbTab & _
            '  pept.charge & vbTab)
            strSB.Append(checkStr)
            strSB.Append(vbTab)
            strSB.Append(pept.MascotScore2.ToString("0.0"))
            strSB.Append(vbTab)
            strSB.Append(pept.charge)
            strSB.Append(vbTab)

            Dim verStr As String = "No"
            If pept.verified Then
                verStr = "Yes"
            End If

            strSB.Append(verStr)
            strSB.Append(vbTab)

            strSB.Append(pept.measuredMCR)
            strSB.Append(vbTab)

            strSB.Append(pept.MascotCalculatedMass)
            strSB.Append(vbTab)

            strSB.Append(pept.calibratedMeasuredMCR)
            strSB.Append(vbTab)

            strSB.Append(pept.calibratedMeasuredMass)
            strSB.Append(vbTab)

            'Changed PM_MS3INTEGRATION 2004-06-03
            strSB.Append(pept.MascotScorePlusMS3Score)
            strSB.Append(vbTab)

            'Changed PM_STRING_CLEANUP 2004-12-14
            strSB.Append( _
              PILInputOutput.emptyForNothing(pept.MS3precursorStr))
            strSB.Append(vbTab)

            strSB.Append(vbCrLf)
        End While 'Through peptides.

        Return strSB.ToString
    End Function 'ProteinSaveString()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuExportProteinInfo_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuExportProteinInfo.Click

        'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-27
        'For now: no peptide filter.
        'Dim peptideFilter As peptideFilterSpecificationStructure = _
        '  mOptions.peptideFilters(peptideFilterEnum.enumExport2)
        Dim peptideFilter As peptideFilterStructure = _
          peptideFilterStructure.noPepFilter()

        'Later: replace with generalised export/save dialog functionality.

        Dim sb As StringBuilder = New StringBuilder(2700)

        'Changed PM_REFACTOR 2008-05-05. Changed to more memory
        '  efficient version...
        'Dim exportStr As String = 
        quantApplication.peptideTableWithHeader4( _
          mRecalibrator2, _
          mProt, _
          mOptions.quantModeCode, _
          mApplication, _
          peptideFilter, False, sb, _
          Nothing)
        Dim exportStr As String = sb.ToString

        '4th parameter is to dump all (false) or only the
        'quantified peptides (true) - is this independent on
        'the actual result of the quantitation?.

        'Changed PM_BROKENEXPORT 2008-05-28
        'Excel for now.
        Dim ex As exportTargetSettingsStruct = _
          exportTargetSettingsStruct.defaultExportTargetSettings()
        ex.target = targetEnum.enumExportToExcel

        PILInputOutput.pushToTarget(exportStr, ex, AppCommon2.appPath())
    End Sub 'mnuExportProteinInfo_Click()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub lsvPepts_SelectedIndexChanged( _
      ByVal sender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles lsvPeptides.SelectedIndexChanged

        'Empty.... See functions that call DisplayNthPeptide(),
        '  e.g. lsvPepts_DoubleClick() and lsvPepts_KeyUp().
    End Sub 'lsvPepts_SelectedIndexChanged


    'Changed PM_SAVETOFILE 2003-04-15
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSaveProteinInfo_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuSaveProteinInfo.Click

        Dim suggestedFileName As String = "protein_" & mProt.accNum
        Dim exportStr As String = ProteinSaveString()

        'Use return value for some text reporting to GUI?
        Dim wasSaved As Boolean = _
          pushToUserSelectedFile2( _
          exportStr, _
          "Saved protein information to file.", _
          suggestedFileName)
    End Sub 'mnuSaveProteinInfo_Click


    'Note: ***identical*** to sub of the same name in
    '  "frmProteinList.vb"/Class frmProteinList. They are in two different
    'forms. How do we refactor? SaveFileDialog1 and ParserStatus/lblProtInfo
    ' belongs to a particular form.
    '
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Function pushToUserSelectedFile2( _
      ByVal aStr As String, _
      ByVal aOKStatusStr As String, _
      ByVal aStartFileName As String) _
      As Boolean

        'Return value is true if the file was saved, false if the user cancelled.

        Dim toReturn As Boolean = _
          PILInputOutput.pushToUserSelectedFile2( _
            aStr, SaveFileDialog1, lblProtInfo.Text, aOKStatusStr, aStartFileName)
        Return toReturn
    End Function 'pushToUserSelectedFile2()


    'Changed PM_MANUAL_PEPTIDEQUANTSTATUSUPDATE 2003-05-06
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub updateProtein(ByVal aProteinListIndex As Integer, _
      ByRef aProt As ProteinHitStructure)

        mProt = aProt 'Needed?

        'Forward to parent - where it needs to be updated
        mFrmProteinList.updateProtein(aProteinListIndex, aProt)
    End Sub 'updateProtein


    '****************************************************************************
    '*    A N A L Y S T   D E P E N D E N T ,   B E G I N                       *
    '****************************************************************************


    ''for incorporating a GraphControl we need to:
    '' 1. right click on Windows Toolbox and select coustomize Toolbox. Select GraphControl. (This is an .ocr ActiveX control)
    '' 2. add Explore Data Type Lib 1.0 via the Add reference and Com tab
    '' 3. add the Analyst bin directory to the 'system path' in Environ Variables in
    ''the my computer property page under advanced



    ''From object browser:
    ''Public Sub SetSpectrum(ByVal sample As Integer, ByVal period As Integer,
    '                        ByVal experiment As Integer, ByVal startTime As Single,
    '                        ByVal endTime As Single)
    '            (However, startTime and endTime need to be declared double anyway)
    '
    'AxGraphControl_ANALYSTCOM_1.SeriesColl.Item(1).DataObject = theData
    '' Get start and stop mass of range scanned.
    'startMass = theData.GetStartMass
    'stopMass = theData.GetStopMass
    '
    '' Get the point numbers of the points with the smallest and largest
    '' intensities.
    'd$ declared as double, double, integer, integer
    ''theData.GetYValueRangeForXValueRange(startMass, stopMass, minPoint, maxPoint)
    '
    '' The base peak mass is the x-value of the point with largest intensity:
    'basePeak = theData.GetDataPointXValue(maxPoint)


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub setSpectrumAndDisplay( _
      ByVal aSpectrumNumber As Integer, _
      Optional ByVal anExperiment As Integer = 1)

        'To do: update for new fragment spectrum.
        Dim rtSecs As Double = _
          mRawDataFileHandling.SpectrumNumber2RetentionTime( _
            aSpectrumNumber, 0) '0: ????????
        Me.setSpectrumAndDisplay(rtSecs, anExperiment)
    End Sub 'setSpectrumAndDisplay


    '****************************************************************************
    '*    setSpectrumAndDisplay                                                 *
    '*                                                                          *
    '*    Change/set the spectrum to be displayed and display header            *
    '*    information.                                                          *
    '*                                                                          *
    '*    Does not actually display the spectrum for Finnigan data.             *
    '****************************************************************************
    Private Sub displaySpectrumInformation(ByVal aSpectrumNumber As Integer)
        'Changed PM_REFACTOR 2005-08-01. Not used....
        ' Dim outSpectrumClassification As SpectrumClassificationStructure
        ' 'Note: we don't use the return value. Actually we only
        ' '      use this function to get the input spectrum (usually MS-MS)
        ' '      classified. Use another function instead??
        ' mRawDataFileHandling.spectrumNumberForMSspectrum( _
        '   spectrumNum, outSpectrumClassification)


        Dim header As String = mRawDataFileHandling.DataTitle()

        'Changed PM_QSTAR_BROKEN 2007-10-03
        Trace.Assert(Not mMSMSdisplay Is Nothing, _
          "PIL ASSERT. mMSMSdisplay is undefined...")

        mMSMSdisplay.setSpectrumTitle(header)

        Dim rawFileFull As String = _
          mRawDataFileHandling.getCurrentFullRawFileName()
        Dim rawFile As String = Path.GetFileName(rawFileFull)

        Dim typeStr As String = ""
        Dim curSpectrumClassification As SpectrumClassificationStructure = _
          mRawDataFileHandling.getCurSpectrumClassification()
        Select Case curSpectrumClassification.spectrumSubType2

            Case spectrumSubTypeEnum.enumIsFragmentCID
                typeStr = ". CID."
            Case spectrumSubTypeEnum.enumIsFragmentECD
                typeStr = ". ECD."
            Case spectrumSubTypeEnum.enumIsFragmentMPD
                typeStr = ". MPD."
            Case spectrumSubTypeEnum.enumIsFragmentMS3
                typeStr = ". MS3."

            Case spectrumSubTypeEnum.enumIsNormalMS
                typeStr = ". Normal MS."
            Case spectrumSubTypeEnum.enumIsZoomMS
                typeStr = ". Zoom MS"

                '    'Yes, CID. 
                'Case spectrumSubTypeEnum.enumIsFragmentNormal
                '    typeStr = ". Frag normal (phased out)."

            Case Else
                Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
        End Select 'Spectrum type string

        Dim msg1 As String = _
          rawFile & _
          ", #" & aSpectrumNumber & ", " & typeStr & ", " & header
        Me.postInformation(msg1)

        'Clear PTM information when changing to a new spectrum.
        'Changed PM_ID_SILACDISH 2008-07-15. Added the condition. Otherwise
        'the warning would be cleared and never been seen...
        If Not mStartingUp Then
            StatusBarPanelPTM.Text = ""

            clearOrangMessageBox()

            clearPTMscoreSelected()
        Else
            Dim peter2 As Integer = 2 'Don't at init time...
        End If

    End Sub 'displaySpectrumInformation


    '****************************************************************************
    '*    setSpectrumAndDisplay                                                 *
    '*                                                                          *
    '*    Change/set the spectrum to be displayed and display header            *
    '*    information.                                                          *
    '*                                                                          *
    '*    Does not actually display the spectrum for Finnigan data.             *
    '****************************************************************************
    Private Sub setSpectrumAndDisplay( _
      ByVal aRTsecs As Double, ByVal anExperiment As Integer)

        Dim spectrumNum As Integer
        mRawDataFileHandling.setSpectrumCONV( _
          aRTsecs, anExperiment, spectrumNum)
        Me.displaySpectrumInformation(spectrumNum)
    End Sub 'setSpectrumAndDisplay


    'Changed PM_AUTOMATCH_FRAGMENTS 2005-08-17
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub displayIonsAndHighlightMatched( _
      ByVal aSeq As String, _
      ByVal aPrecursorCharge As Integer, _
      ByVal aRawFileRef As Integer, _
      ByRef anInOutFragments As peptideFragments, _
      ByRef anInMassAdjustments As ionSetStruct, _
      ByRef anInLastMSMSSignal As _
        List(Of massSpectrometryBase.signalStructure), _
      ByRef anInLastMSMSSignalInfo As dataPointsInfoStructure2 _
    )
        'Old:
        '  ByRef anInLastMSMSSignal As ArrayList

        'Changed PM_GENERALISED_QUANT_MODE 2003-12-10
        Dim quantitationModesObject As QuantitationModes_moreGeneral = _
          mApplication.getQuantModes()

        Dim modificationsList As List(Of List(Of AAsetStruct)) = _
          quantitationModesObject.constructSimpleModificationList( _
            mLastPeptHit.modHits2)

        'Changed PM_REFACTOR 2008-05-18. Moved down, to after matching ions.
        '
        'Me.displayBAndYions( _
        '  aSeq, True, aPrecursorCharge, _
        '  aRawFileRef, modificationsList, _
        '  anInOutFragments, anInMassAdjustments)
        Dim lowestX2 As Double
        Dim highestX2 As Double
        If True Then
            Dim dataPointsInfo As dataPointsInfoStructure2

            'Adaption to previous side effects.
            'Note: this is to ensure proper side effects... To be as efficient
            '      as before we should somehow eliminated the extra call
            '      to getDataPointsAndSetState(), through displayBAndYions() below.
            Me.getDataPointsAndSetState( _
              aRawFileRef, lowestX2, highestX2, dataPointsInfo)
        End If

        'Changed PM_AUTOMATCH_FRAGMENTS 2005-08-17
        If True Then
            Dim smartPickingLevel As Integer = 9
            Dim MannReductionLevel As Integer = 4

            smartPickingLevel = mReductionParameters2.smartPickingLevel3
            MannReductionLevel = mReductionParameters2.MannReductionLevel2

            'Changed PM_USERSET_MS3_MATCHING_TOLERANCE 2007-07-13
            Dim massSegmentSize As Double = _
              mReductionParameters2.smartPickingMassWindow
            Dim massTol As Double = mReductionParameters2.matchingMassTolerance

            Dim maxIntPeakLst() As Integer = Nothing 'Keep compiler happy.

            'Changed PM_TYPESAFE 2006-11-01
            'Dim effectiveDatapoints As ArrayList = Nothing 'Keep compiler happy.
            Dim effectiveDatapoints As List(Of LCPeakInfoStructure) = _
              Nothing 'Keep compiler happy.



            BSignal.reducePeakList2( _
              anInLastMSMSSignal, _
              maxIntPeakLst, _
              effectiveDatapoints, _
              smartPickingLevel, _
              massSegmentSize, _
              MannReductionLevel, _
              massTol)
            '9: SmartPicking search level

            'Changed PM_GENERALISED_IONSERIES_SPECTRUMCLASSIFICATION 2008-06-24
            Dim curSpectrumClassification As SpectrumClassificationStructure = _
              mRawDataFileHandling.getCurSpectrumClassification()

            'Changed PM_FRAGMENTDISPLAY 2008-05-18. Moved out of displayBAndYions3().
            'Changed PM_REFACTOR 2005-02-24
            Dim dummyToken As Integer
            Dim curPep As PeptideHitStructure = _
              getPeptideFromVisualIndex(mCurrentlySelectedPeptIdx, dummyToken)
            'Calculate all the fragments and the description strings.
            anInOutFragments.CalcFragIons2( _
              aSeq, True, curPep.AASequence, aPrecursorCharge, _
              modificationsList, _
              mCurrSelPeptMod.ToLower, anInMassAdjustments, _
              curPep.modHits2, _
              False, _
              curSpectrumClassification.spectrumSubType2)

            anInOutFragments.resetMarkMatches()
            peptideFragments.matchFragmentIons( _
              effectiveDatapoints, maxIntPeakLst, _
              mLastPeptHit.charge, _
              massTol, _
              anInOutFragments)

            'Changed PM_ION_SERIES_DISPLAYOPTION 2008-05-26
            Dim showOnlyMatchedIons As Boolean = mApplication.getShowOnlyMatchedIons()

            'Changed PM_REFACTOR 2008-05-18. Moved to here. To do the fragment 
            '  ion matching before we display. This is because the pixel 
            '  display now depends on whether a fragment is matching a peak 
            '  in the data or not. It is no longer just the colour that 
            '  depends on the matching.
            Me.displayBAndYions3( _
              aSeq, True, aPrecursorCharge, _
              aRawFileRef, modificationsList, _
              anInOutFragments, anInMassAdjustments, _
              False, _
              showOnlyMatchedIons)

            highlightMatchedFragments(anInOutFragments)

            'Changed PM_DISPLAY_SCORE 2008-06-25
            'Display score and associated.
            If True Then 'Perhaps later: avoid recomputing score when this
                '  function is called from PTM scoring.

                'Note: some redundancy with calling sequences
                '      in getDataMatchAndScore3(), file MS3scoring.vb.
                Dim XminForScore As Double
                Dim XmaxForScore As Double
                If True Then 'If False: can be used to expose a boundary problem.
                    XminForScore = lowestX2
                    XmaxForScore = highestX2
                Else
                    'Not used. Corresponding to older behavior for MS3
                    'and PTM soscoring.
                    XminForScore = _
                      anInOutFragments.lightestFragmentMCR()
                    XmaxForScore = _
                      anInOutFragments.heaviestFragmentMCR()
                End If

                Dim N As Integer
                Dim K As Integer
                Dim score As Double = _
                  MS3scoring.DetermineScore( _
                    anInOutFragments, XminForScore, XmaxForScore, N, K)

                'For now. Will overwrite combinations information for PTM scoring...
                mScratchSB.Length = 0
                mScratchSB.Append("Score: ")
                mScratchSB.Append(score.ToString("0.00"))
                mScratchSB.Append(". Matched ")
                mScratchSB.Append(K)
                mScratchSB.Append(" out of ")
                mScratchSB.Append(N)
                mScratchSB.Append(" in [ ")
                mScratchSB.Append(XminForScore.ToString("0.0"))
                mScratchSB.Append(" Th; ")
                mScratchSB.Append(XmaxForScore.ToString("0.0"))
                mScratchSB.Append(" Th].")

                StatusBarPanelPTM.Text = mScratchSB.ToString

            End If

        End If
    End Sub 'displayIonsAndHighlightMatched


    '****************************************************************************
    '*                                                                          *
    '*  Parameters:                                                             *
    '*    1. anInMustBeThisSequence : only for error detection (checking        *
    '*                                for correct peptide sequence). Empty      *
    '*                                string, "", for no error detection        *
    '*                                                                          *
    '*    2. aQueryNumber           : Will display the peptide with that        *
    '*                                query number. Ignored if 0 - it that      *
    '*                                case aVisualIndex2 is used to decide      *
    '*                                which peptide to display on opening       *
    '*                                the this dialog                           *
    '*                                                                          *
    '****************************************************************************
    Private Sub DisplayNthPeptide( _
      ByVal aVisualIndex2 As Integer, _
      ByRef anInMustBeThisSequence As String, _
      ByVal aQueryNumber As Integer _
      )
        'What is the colour??? = Color.LightGray
        '  Gray is a color, Grey is a *colour*.


        If SDUPrecalibrator.identityCalibration(mRecalibrator2) Then
            lblExtraInfo.BackColor = Color.Salmon
            lblExtraInfo.Text = "Note: no recalibration!"
        Else
            'Changed PM_QUANTMODE_WARNING_CLEARED 2008-10-11. Now no clearing.
            '  here. It is too late, e.g. would clear the warning "1. SILAC 
            '  modifications have not been ..." when displaying a new protein 
            '  by using menu command Proteins and Peptides/Accept Protein. But 
            '  what was the original meaning of clearing it here?? - we may 
            '  have re-introduced a bug...
            '
            ' 'Changed PM_ID_SILACDISH 2008-07-15. Added the condition. Otherwise
            ' 'the warning would be cleared and never been seen...
            ' If Not mStartingUp Then
            '     'Clear it...
            '     clearOrangMessageBox()
            ' Else
            '     Dim peter2 As Integer = 2 'Don't at init time...
            ' End If
            Dim peter2 As Integer = 2 'For breakpoints...
        End If

        mFirstMS1 = True 'Reset.

        If mWiffFileName = "" Then
            MsgBox( _
              "No valid raw data file (.wiff, .raw or .idx) open. " & _
              "Please close the protein validation window and try again")
        End If

        'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-29
        Dim visualPeptides As Integer = lsvPeptides.Items.Count()
        Trace.Assert(visualPeptides > 0, "PIL ASSERT. No peptides to display!.")

        'Changed PM_RECALIB_VISUAL_CLICK_TO_PEPTIDEINFO 2008-03-12
        Dim visualIndex As Integer = aVisualIndex2
        If aQueryNumber <> 0 Then
            'Find visual index for query number. We have to
            'go through the visual stuff as the peptides
            'can be in any order - the user may e.g. have
            'sorted them by mass.

            Dim lastIndex As Integer = visualPeptides - 1
            Dim j As Integer
            For j = 0 To lastIndex Step 1

                Dim qNum As Integer = readOffQueryNumber(j)
                If qNum = aQueryNumber Then
                    visualIndex = j
                    Exit For
                End If
            Next j
        End If

        'Make the list item visible if it isn't.
        lsvPeptides.Items(visualIndex).EnsureVisible()

        Dim token As Integer
        mLastPeptHit = _
          getPeptideFromVisualIndex(visualIndex, token)

        Trace.Assert( _
          False Or _
          mLastPeptHit.AASequence = anInMustBeThisSequence Or _
            anInMustBeThisSequence = "", _
          "PIL ASSERT. Unexpected sequence for peptide!!!. It is: " & _
          mLastPeptHit.AASequence & ", visual index = " & visualIndex & _
          ". Expected sequence: " & anInMustBeThisSequence)

        Cursor = Cursors.WaitCursor

        'Changed PM_SEVERALWIFFS_BUGFIX 2003-08-28
        mRawDataFileHandling.newCurrentFile(mLastPeptHit.rawFileID)

        'Dim period As Integer = mLastPeptHit.period   not used...
        Dim experimentNumber As Integer = mLastPeptHit.experimentNumber

        'Note: for Analyst; MS-MS spectra are chosen/filtered based
        '      on the retention time.
        If True Then 'This is where it is the *** MS-MS *** spectrum.
            Dim retTmin As Double = mLastPeptHit.MSMSretentionTimeMinutes

            'Changed PM_REFACTOR 2003-03-15
            Dim RTsecs As Single = CSng(retTmin * 60)

            'Changed PM_REFACTOR 2004-05-13
            Me.setSpectrumAndDisplay(RTsecs, experimentNumber)

            'Changed PM_SPECTRUM_BROWSE 2005-08-02
            mSpectrumTree.setIDspectrum(RTsecs, experimentNumber)
        End If '

        'Something was deleted here....

        mCurrentlySelectedPeptIdx = visualIndex 'This is still the case
        'because selection in table.
        Me.UpdateCurrSelPept()
        lsvPeptides.Items(mCurrentlySelectedPeptIdx).Selected = True
        'First get the sequence.

        Dim sequence As String = mLastPeptHit.AASequence
        Dim queryNum As Integer = mLastPeptHit.queryNumber
        Dim precursorCharge As Integer = mLastPeptHit.charge

        Me.writeSeqAndQueryinTitle(sequence, queryNum)

        'Changed PM_AUTOMATCH_FRAGMENTS 2005-08-17
        Dim dummy1 As ionSetStruct
        dummy1.backwardIonDiffs = Nothing
        dummy1.forwardIonDiffs = Nothing
        Me.displayIonsAndHighlightMatched( _
          sequence, precursorCharge, mLastPeptHit.rawFileID, _
          mMSMSFragments, dummy1, _
          mLastMSMSSignal, mLastMSMSSignalInfo _
          )

        'Changed PM_REFACTOR 2005-08-16. Not needed anymore.
        ''Changed PM_MS3_EXPORT 2005-01-20
        'mLastMS2signal = mLastMSMSSignal

        'Changed PM_REFACTOR 2005-02-25
        ''set the zoomed peptide variable to the middle
        'mCurrentlyZoomedFrag = CInt(mFragments.fragments() / 2)
        mMSMSFragments.readStateMiddleFragment()

        'Dim TS As TimeSpan = T2.Subtract(T1)

        'Changed PM_VISUAL_NOISE 2004-11-08
        'StatusBar1.Text = "Read spectrum in " & TS.TotalSeconds.ToString("##.0") & " secs"

        'Changed PM_REOPEN_PROTVAL_PTMSCORE 2007-04-19
        'Run PTM scoring in order to build up mass difference arrays, etc.
        If Not mLastPeptHit.PTMs2 Is Nothing Then
            Dim len As Integer = mLastPeptHit.PTMs2.Count()
            'Trace.Assert(len <> 0, "PIL ASSERT. Empty PTM combinations...")
            If len = 0 Then
                Dim peter10 As Integer = 10
            End If

            Me.doPTMscoring2(False)
        End If

        Cursor = Cursors.Default

        'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-04
        addPTMcombinationsToGUI(mPTMversionMarker)
    End Sub 'DisplayNthPeptide()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub basicDisplayRawSpectrum( _
      ByVal anInLowestX2 As Double, _
      ByRef anInOutHighestX2 As Double, _
      ByRef aCalcFragSpec_AnalystCOM2 As rawDataFileHandling, _
      ByRef anInMaxY As Double)

        'Changed PM_QSTAR_BROKEN_ZOOMING 2007-10-03. New parameter: anInMaxY.


        'Old type:
        '  ByRef aCalcFragSpec_ANALYSTCOM As QS20.ExploreDataObjects.XYData

        Try
            'Changed PM_MS3_BADZOOM 2007-10-11. Disabled... Consequence for
            '  Micromass: XXXXX.
            '
            'anInOutHighestX2 = mCurrSelPept.measuredMass 'The Gouw
            ''  way - Micromass only!.

            mMSMSdisplay.clearMarkers()

            'Changed PM_REFACTOR 2005-03-04
            Dim zoom As massZoomStructure
            zoom.startMass = anInLowestX2
            zoom.endMass = anInOutHighestX2

            'Changed PM_QSTAR_BROKEN_ZOOMING 2007-10-03
            'zoom.maxYVal = -1
            zoom.maxYVal = anInMaxY

            Dim displayMassWindow As Double = _
              zoom.endMass - zoom.startMass
            If displayMassWindow < 0.000000001 Then
                Trace.Assert(False, "PIL ASSERT. Empty display range.. " & _
                  "This can happen if the buggy XCalibur 2.0 is used on older .RAW files.")
            Else
                Dim peter2 As Integer = 2
            End If

            mMSMSdisplay.setInitialZoom(zoom) '-1: For now.
            mMSMSdisplay.updateData()


            ' Select Case mOptions.rawFileMode
            '     Case rawFileModeEnum.enumAnalyst
            ' 
            '         'Changed PM_REFACTOR 2007-07-22
            '         'Dim count As Integer = _
            '         '  mAxGraphControl_ANALYSTCOM_2.SeriesColl.Count()
            '         Dim count As Integer = _
            '           mAnalystCOM_Graph.axControl_SeriesCollCount()
            ' 
            '         If count = 1 Then
            ' 
            '             'Changed PM_REFACTOR 2007-07-22
            '             'This will add a second series first time around.
            '             ''AxGraphControl_ANALYSTCOM_1.SeriesColl.CreateAddSeries()
            '             'mAxGraphControl_ANALYSTCOM_2.SeriesColl.CreateAddSeries()
            '             mAnalystCOM_Graph.axControl_CreateAddSeries() 'This
            '             '  changes count!
            ' 
            '             count = _
            '               mAnalystCOM_Graph.axControl_SeriesCollCount()
            '         End If
            '         If Not count = 2 Then
            '             MsgBox("Problem with creating series object in Graph")
            '         End If
            ' 
            '         'Now put them into an overlay.
            '         '
            '         'This data object will hold our fragments.
            ' 
            '         'Changed PM_REFACTOR 2007-07-22
            '         ' aCalcFragSpec_ANALYSTCOM = New QS20.ExploreDataObjects.XYData
            '         ' aCalcFragSpec_ANALYSTCOM.XValuesAreSorted = False 'This was the missing
            '         ' '  line!!! (can not do this for spectra).
            '         Dim dataSource As AnalystCOM = _
            '           DirectCast(aCalcFragSpec_AnalystCOM2, _
            '             AnalystRawDataFileHandling).getAnalystDataSource()
            '         dataSource.XYdata_create(False)
            ' 
            '         'Changed PM_REFACTOR 2007-07-22
            '         'mAxGraphControl_ANALYSTCOM_2.SeriesColl.Item( _
            '         '  1).SeriesCaptionColl.RemoveAll()
            '         mAnalystCOM_Graph.axControl_SeriesRemoveAll(1)
            ' 
            '         'Changed PM_REFACTOR 2007-07-22
            '         'Now try to set the symbols differently:
            '         'mAxGraphControl_ANALYSTCOM_2.SeriesColl.Item( _
            '         '  2).AutoCreateMetaData()
            '         mAnalystCOM_Graph.axControl_AutoCreateMetaData(2)
            ' 
            '     Case rawFileModeEnum.enumFinnegan
            '         mFinneganMSMS.clearMarkers(Me)
            ' 
            '         'Changed PM_REFACTOR 2005-03-04
            '         Dim zoom As massZoomStructure
            '         zoom.startMass = anInLowestX
            '         zoom.endMass = anInOutHighestX
            '         zoom.maxYVal = -1
            ' 
            '         Dim displayMassWindow As Double = _
            '           zoom.endMass - zoom.startMass
            '         If displayMassWindow < 0.000000001 Then
            '             Trace.Assert(False, "PIL ASSERT. Empty display range.. " & _
            '               "This can happen if the buggy XCalibur 2.0 is used on older .RAW files.")
            '         Else
            '             Dim peter2 As Integer = 2
            '         End If
            ' 
            '         mFinneganMSMS.setInitialZoom(zoom) '-1: For now.
            ' 
            '         'Changed PM_XY_EXPORT 2005-01-11
            '         'mFinneganMSMS.updateData(outSignal)
            '         mFinneganMSMS.updateData()
            ' 
            '     Case rawFileModeEnum.enumMicromass
            '         'highestX is set to the deconvoluted mass of the precursor.
            '         anInOutHighestX = mCurrSelPept.measuredMass 'The Gouw
            '         '  way - Micromass only!.
            ' 
            '         'Changed PM_REFACTOR 2005-03-04
            '         Dim zoom As massZoomStructure
            '         zoom.startMass = anInLowestX
            '         zoom.endMass = anInOutHighestX
            '         zoom.maxYVal = -1
            ' 
            '         Dim displayMassWindow As Double = _
            '           zoom.endMass - zoom.startMass
            '         If displayMassWindow < 0.000000001 Then
            '             Dim peter1 As Integer = 1
            '             Trace.Assert(False, "PIL ASSERT. Empty display range..")
            '         Else
            '             Dim peter2 As Integer = 2
            '         End If
            ' 
            '         mFinneganMSMS.setInitialZoom(zoom) '-1: For now.
            ' 
            '         'Changed PM_XY_EXPORT 2005-01-11
            '         'mFinneganMSMS.updateData(outSignal)
            '         mFinneganMSMS.updateData()
            '     Case Else
            '         Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
            ' End Select


        Catch exceptionObject As Exception
            Dim errMsg1 As String = "Error: " & exceptionObject.ToString & ControlChars.NewLine
            Dim errMsg2 As String = _
              "Message: " & exceptionObject.Message & ControlChars.NewLine
            Dim errMsg3 As String = ""
            If Not exceptionObject.InnerException Is Nothing Then
                errMsg3 = _
                    "Extra info: " & exceptionObject.InnerException.Message & ControlChars.NewLine
            End If
            Dim errMsg As String = errMsg1 & errMsg2 & errMsg3
            MsgBox(errMsg)
            Exit Sub
        End Try
    End Sub 'basicDisplayRawSpectrum


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub displayRawSpectrum( _
      ByRef anInRawDataFileHandling As massSpectrometryBase.rawDataFileHandling, _
      ByVal aRawFileRef As Integer, _
      ByRef anOutSignal As List(Of massSpectrometryBase.signalStructure), _
      ByRef anOutDataPointsInfo As dataPointsInfoStructure2, _
      ByRef anOutLowestX As Double, _
      ByRef anOutHighestX As Double, _
      ByRef aCalcFragSpec_AnalystCOM2 As massSpectrometryBase.rawDataFileHandling _
      )
        'Old type:
        '  ByRef aCalcFragSpec_ANALYSTCOM As QS20.ExploreDataObjects.XYData

        'Old:
        '  ByRef anOutSignal As ArrayList

        'Changed PM_REFACTOR 2005-08-15
        anInRawDataFileHandling.datapointsCONV( _
          aRawFileRef, anOutSignal, anOutDataPointsInfo, _
          anOutLowestX, anOutHighestX)

        'Changed PM_QSTAR_BROKEN_ZOOMING 2007-10-03
        Dim maxY As Double = anOutDataPointsInfo.maximumSignal.Ysig

        Me.basicDisplayRawSpectrum( _
          anOutLowestX, anOutHighestX, aCalcFragSpec_AnalystCOM2, maxY)
    End Sub 'displayRawSpectrum


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub displayFragments( _
      ByRef anInFragments As peptideFragments, _
      ByVal aLowestX As Double, ByVal aHighestX As Double, _
      ByRef aCalcFragSpec_AnalystCOM2 As massSpectrometryBase.rawDataFileHandling, _
      ByVal aShowOnlyMatchedIons As Boolean)

        'Old type:
        '  ByRef anINcalcFragSpec_ANALYSTCOM As QS20.ExploreDataObjects.XYData

        'Changed PM_FINNEGAN_MSMS_DISPLAY 2004-02-04
        Dim tokens As List(Of Integer) = _
          anInFragments.getFragmentTokens(aLowestX, aHighestX)

        Dim fragment2 As fragmentExStructure
        Dim token As Integer
        For Each token In tokens
            fragment2 = anInFragments.getFragment(token)

            'Changed PM_ION_SERIES_DISPLAYOPTION 2008-05-26
            Dim doAdd As Boolean = True
            If aShowOnlyMatchedIons Then
                If fragment2.ionMatched = False Then
                    doAdd = False
                End If
            End If

            'Changed PM_REFACTOR 2007-09-19
            'Dim MCRCalcLoc As Double = fragment.MCRcalcLoc
            If doAdd Then
                mMSMSdisplay.addIonMarker(fragment2, mDeltaMass, token)
            Else
                Dim peter2 As Integer = 2 'Not to be displayed due to the option.
            End If

            'Changed PM_REFACTOR 2007-09-19. Old. Delete at any time.
            ' Select Case mOptions.rawFileMode
            ' Case rawFileModeEnum.enumAnalyst
            ' 
            '     'Changed PM_REFACTOR 2005-02-24. Compute yLoc when we need it.
            '     Dim yLoc As Double = largestYinData(MCRCalcLoc, mDeltaMass)
            ' 
            '     'Changed PM_REFACTOR 2007-07-23
            '     'anINcalcFragSpec_ANALYSTCOM.AppendDataPoint(MCRCalcLoc, yLoc)
            '     Dim dataSource As AnalystCOM = DirectCast(mRawDataFileHandling, _
            '       AnalystRawDataFileHandling).getAnalystDataSource()
            '     dataSource.XYdata_AppendDataPoint(MCRCalcLoc, yLoc)
            ' 
            '     If fragment.ionType = ionTypeEnum.enumPrecursorIon Then
            '         'Changed PM_REFACTOR 2007-07-22
            '         'Dim index As Integer = _
            '         '  mAxGraphControl_ANALYSTCOM_2.SeriesColl.Item( _
            '         '    1).SeriesCaptionColl.CreateAddUserLabel( _
            '         '    fragment.descStr, MCRCalcLoc, yLoc)
            '         Dim index As Integer = _
            '           mAnalystCOM_Graph.axControl_CreateAddUserLabel( _
            '             1, fragment.descStr, MCRCalcLoc, yLoc)
            ' 
            '         'Changed PM_REFACTOR 2007-07-22
            '         'mAxGraphControl_ANALYSTCOM_2.SeriesColl.Item( _
            '         '  1).SeriesCaptionColl.Item(index).Font.Italic = _
            '         '    True
            '         'mAxGraphControl_ANALYSTCOM_2.SeriesColl.Item( _
            '         '  1).SeriesCaptionColl.Item(index).Font.Bold = _
            '         '  True
            '         mAnalystCOM_Graph.axControl_fontBoldItalic( _
            '           1, index)
            '     Else
            '         'Not precursor ion...
            ' 
            '         'Changed PM_REFACTOR 2007-07-22
            '         'mAxGraphControl_ANALYSTCOM_2.SeriesColl.Item( _
            '         '  1).SeriesCaptionColl.CreateAddUserLabel( _
            '         '     fragment.descStr, MCRCalcLoc, yLoc)
            '         mAnalystCOM_Graph.axControl_CreateAddUserLabel( _
            '           1, fragment.descStr, MCRCalcLoc, yLoc)
            '     End If
            '
            ' Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
            '     'Changed PM_FINNEGAN_LABELS 2004-05-04
            '     Dim newMarker As markerStructure
            '     newMarker.MCR = MCRCalcLoc
            ' 
            '     'Changed PM_REFACTOR 2005-01-26
            '     'newMarker.Yion = .Yion
            '     'newMarker.Bion = .Bion
            '     newMarker.ionType = fragment.ionType
            ' 
            '     'Changed PM_FRAGMENTS_EXTRAINFO 2005-08-18
            '     'Changed PM_VS2005 2006-06-15
            '     'Why can't this be in a block???
            '     Dim extraStr As String = ""
            '     If fragment.ionType <> ionTypeEnum.enumPrecursorIon Then
            '         If peptideFragments.isForwardIon7(fragment.ionType) Then
            '             Dim lastIndex As Integer = fragment.seq.Length - 1
            '             extraStr = ",+" & fragment.seq.Substring(lastIndex)
            '         Else
            '             extraStr = ",+" & fragment.seq.Substring(0, 1)
            '         End If
            '     End If
            '     newMarker.moreDescription = extraStr
            '     newMarker.labelDescription = fragment.descStr
            '     newMarker.charge = fragment.charge
            '     newMarker.tag = token.ToString
            ' 
            '     mFinneganMSMS.addMarker( _
            '       Me, mFarOff, newMarker, yLevelForMarkers.Height, False, _
            '       Color.Empty)
            '     '   MCRCalcLoc
            ' Case Else
            '     Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
            ' End Select
        Next

        mMSMSdisplay.lastMarkerAdded(aHighestX)


        'Changed PM_REFACTOR 2007-09-19. Old. Delete at any time.
        ' Select Case mOptions.rawFileMode
        '     Case rawFileModeEnum.enumAnalyst
        '         'Changed PM_REFACTOR 2007-07-22
        '         'mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.Max = aHighestX
        '         mAnalystCOM_Graph.axControl_setXaxisMax(aHighestX)
        ' 
        '         'Changed PM_REFACTOR 2007-07-22
        '         'mAxGraphControl_ANALYSTCOM_2.SeriesColl.Item(2).DataObject = _
        '         '  anINcalcFragSpec_ANALYSTCOM
        '         Dim dataSource As Object = DirectCast(aCalcFragSpec_AnalystCOM2, _
        '           AnalystRawDataFileHandling).getAnalystDataSource()
        '         mAnalystCOM_Graph.axControl_setXYObject(2, dataSource)
        ' 
        '         'Changed PM_REFACTOR 2007-07-22
        '         'mAxGraphControl_ANALYSTCOM_2.InvalidateControl()
        '         mAnalystCOM_Graph.axControl_InvalidateControl()
        ' 
        '     Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
        '         'Nothing for now..
        ' 
        '     Case Else
        '         Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
        ' End Select

    End Sub 'displayFragments


    'Changed PM_REFACTOR 2008-05-18
    '****************************************************************************
    '*    This function exist to have proper side effects... At least *
    '*    it is centralised...                                             *
    '****************************************************************************
    Private Sub getDataPointsAndSetState( _
      ByVal aRawFileRef As Integer, _
      ByRef anOutStartX As Double, _
      ByRef anOutEndX As Double, _
      ByRef anOutDataPointsInfo As dataPointsInfoStructure2 _
      )

        'Changed PM_REFACTOR 2005-08-15. Split up so all the
        'display stuff comes at the end. At moved down here.

        'Changed PM_REFACTOR 2006-10-12
        'Dim outSignal As ArrayList = Nothing 'Keep compiler happy.
        Dim outSignal As List(Of massSpectrometryBase.signalStructure) = _
          Nothing 'Keep compiler happy.

        'Me.displayRawSpectrum( _
        '  mRawDataFileHandling, aRawFileRef, _
        '  outSignal, dataPointsInfo, lowestX, highestX, _
        '  calcFragSpec_ANALYSTCOM)
        mRawDataFileHandling.datapointsCONV( _
          aRawFileRef, outSignal, anOutDataPointsInfo, _
          anOutStartX, anOutEndX)


        'Changed PM_BELARUS_EMPTY_FRAGMENT_SPECTRA_DUE_TO_RAW2MSM_BUG 2008-10-21
        'Work-around the raw2msm bug (that repeats the peak 
        'list of the previous fragment spectrum if the 
        'current fragment spectrum is empty).
        If outSignal.Count = 0 Then
            'Empty fragment spectrum. Due to raw2msm bug. Synthesise some data
            'in order to allow execution to continue without errors.

            MsgBox( _
              "The fragment spectrum (in the raw spectrum file) is empty. " & _
              "The reason that an empty spectrum appears to have " & _
              "identified a peptide (!) is due to a bug in raw2msm. " & _
              "Please complain to the developers of raw2msm.")

            'Change the signal.
            'This is a rather nasty, but we are only here in exceptional
            'circumstances.

            Dim x As Double = 130.5
            Dim y As Double = 0.041

            anOutDataPointsInfo.minX2 = x
            anOutStartX = x

            Dim fakedPoint As massSpectrometryBase.signalStructure
            fakedPoint.Ysig = y 'Same for all.

            Dim j As Integer
            For j = 1 To 2
                fakedPoint.Xsig = x
                outSignal.Add(fakedPoint)

                x += 200.0
            Next j

            anOutDataPointsInfo.maxX2 = x
            anOutEndX = x

            anOutDataPointsInfo.minimumSignal = fakedPoint
            anOutDataPointsInfo.maximumSignal = fakedPoint
        End If 'No signal/empty spectrum.

        'Changed PM_MS3INTEGRATION 2004-05-13
        mLastMSMSSignal = outSignal
        mLastMSMSSignalInfo = anOutDataPointsInfo
    End Sub 'getDataPointsAndSetState()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub displaySpectrumWithFragments( _
      ByVal aRawFileRef As Integer, _
      ByRef anInFragments As peptideFragments, _
      ByVal aShowOnlyMatchedIons As Boolean)

        Dim lowestX2 As Double
        Dim highestX2 As Double
        Dim dataPointsInfo As dataPointsInfoStructure2

        ' If True Then
        '     'Changed PM_REFACTOR 2005-08-15. Split up so all the
        '     'display stuff comes at the end. At moved down here.
        ' 
        '     'Changed PM_REFACTOR 2006-10-12
        '     'Dim outSignal As ArrayList = Nothing 'Keep compiler happy.
        '     Dim outSignal As List(Of massSpectrometryBase.signalStructure) = _
        '       Nothing 'Keep compiler happy.
        ' 
        ' 
        '     'Me.displayRawSpectrum( _
        '     '  mRawDataFileHandling, aRawFileRef, _
        '     '  outSignal, dataPointsInfo, lowestX, highestX, _
        '     '  calcFragSpec_ANALYSTCOM)
        '     mRawDataFileHandling.datapointsCONV( _
        '       aRawFileRef, outSignal, dataPointsInfo, _
        '       lowestX2, highestX2)
        ' 
        '     'Changed PM_MS3INTEGRATION 2004-05-13
        '     mLastMSMSSignal = outSignal
        '     mLastMSMSSignalInfo = dataPointsInfo
        ' End If
        Me.getDataPointsAndSetState(aRawFileRef, lowestX2, highestX2, dataPointsInfo)


        'Changed PM_DISPLAY_BOUNDARY_SPECTRUMDATA 2007-10-11
        'Provide x-margin so first and last datapoint can be zoomed in to.
        Dim zoomXmin As Double = lowestX2 - 10.0
        Dim zoomXmax As Double = highestX2 + 10.0


        'Changed PM_DEADCODE_COM_ANALYST 2008-11-14
        'Not needed anymore!! In this way we now only have references
        'to Analyst in the specific classes/files for them: 
        '  AnalystRawDataFileHandling.vb
        '  QS11analystCOM.vb
        '  QS20analystCOM.vb
        '
        'Dim calcFragSpec_ANALYSTCOM As QS20.ExploreDataObjects.XYData = _
        '  Nothing 'Keep compiler happy.


        'Changed PM_QSTAR_BROKEN_ZOOMING 2007-10-03
        Dim maxY As Double = dataPointsInfo.maximumSignal.Ysig

        'Changed PM_REFACTOR 2005-08-15
        Me.basicDisplayRawSpectrum( _
          zoomXmin, zoomXmax, mRawDataFileHandling, maxY) 'Old: calcFragSpec_ANALYSTCOM

        Me.displayFragments( _
          anInFragments, zoomXmin, zoomXmax, mRawDataFileHandling, _
          aShowOnlyMatchedIons)

    End Sub 'displaySpectrumWithFragments


    'Note: this function call be eliminated. Replace with call to displaySpectrumWithFragments().
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '*   anInModificationsList: type is simpleModificationSpecification         *
    '****************************************************************************
    Private Sub displayBAndYions3( _
      ByVal aSeq As String, _
      ByVal aSeqIsRealPeptide As Boolean, _
      ByVal aPrecursorCharge As Integer, _
      ByVal aRawFileRef As Integer, _
      ByRef anInMassesList As _
        List(Of List(Of AAsetStruct)), _
      ByRef anInOutFragments As peptideFragments, _
      ByRef anInMassAdjustments As ionSetStruct, _
      ByVal aMS3_BionFlag As Boolean, _
      ByVal aShowOnlyMatchedIons As Boolean)

        'Old:
        '  ByRef anInModificationsList As ArrayList, _

        Trace.Assert(aPrecursorCharge > 0, _
          "PIL ASSERT. precursor charge is improper: ." & aPrecursorCharge)

        'Eliminated as first parameter because it is no longer used:
        '  ByVal anIdxToPeptProts As Integer,

        'Changed PM_FRAGMENTDISPLAY 2008-05-18. Moved to caller side...
        ' 'Changed PM_REFACTOR 2005-02-24
        ' Dim dummyToken As Integer
        ' Dim curPep As PeptideHitStructure = _
        '   getPeptideFromVisualIndex(mCurrentlySelectedPeptIdx, dummyToken)
        ' 
        ' 'Calculate all the fragments and the description strings.
        ' anInOutFragments.CalcFragIons2( _
        '   aSeq, aSeqIsRealPeptide, curPep.AASequence, aPrecursorCharge, _
        '   anInMassesList, _
        '   mCurrSelPeptMod.ToLower, anInMassAdjustments, _
        '   curPep.modHits2, _
        '   aMS3_BionFlag)

        If True Then 'Display stuff
            Me.displaySpectrumWithFragments(aRawFileRef, anInOutFragments, _
              aShowOnlyMatchedIons)
        End If 'Display stuff
    End Sub 'displayBAndYions


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub writeSeqAndQueryinTitle( _
      ByVal aSeq As String, ByVal aQuery As Integer)

        'origTitle = AxGraphControl_ANALYSTCOM_1.SeriesColl.Item(1).Title.Text
        'Must take the title from the data object because the graph title is not
        'updated.
        'Remove the second line which is the one containing the TOF constants.

        'Changed PM_BACK_TO_NORMAL 2003-07-29
        'Dim title As String = mANALYSTCOM_Data.DataTitle
        Dim title As String = mRawDataFileHandling.DataTitle()

        Dim idx As Integer = title.IndexOf("wiff")
        If idx > 0 Then
            idx += 4 'because of the 'wiff'
            title = title.Remove(idx, title.Length - idx)
        End If

        'Changed PM_REFACTOR 2007-09-25
        ' Select Case mOptions.rawFileMode
        '     Case rawFileModeEnum.enumAnalyst
        '         Dim titleStr As String = _
        '           title & vbLf & "Seq: " & aSeq & vbTab & _
        '           " Query " & aQuery.ToString
        ' 
        '         'Changed PM_REFACTOR 2007-07-22
        '         'mAxGraphControl_ANALYSTCOM_2.SeriesColl.Item(1).Title.Text = _
        '         '  titleStr
        '         mAnalystCOM_Graph.axControl_setTitle(1, titleStr)
        ' 
        '     Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
        '         'Nothing for now..
        ' 
        '     Case Else
        '         Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
        ' End Select
        Dim titleStr As String = _
          title & vbLf & "Seq: " & aSeq & vbTab & _
          " Query " & aQuery.ToString
        mMSMSdisplay.setSpectrumTitle(titleStr)
    End Sub 'writeSeqAndQueryinTitle


    'Changed PM_REFACTOR 2007-09-25. No longer needed. If we again need
    '  this functionality in this form then it should
    '  be implemented in another way.
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub ZoomFragment2(ByRef aFragment As fragmentExStructure)
    ' 
    '     Dim lowerX, higherX As Double
    ' 
    '     'Changed PM_REFACTOR 2005-02-25
    '     'Dim massOfCurrFrag As Double = mDisplItmArr1(nthItem).MCRcalcLoc
    '     Dim massOfCurrFrag As Double = aFragment.MCRcalcLoc
    ' 
    '     Dim zoomRange As Double = 4.0 '(-2 to plus 2 so the peak should be exactly in the middle
    '     lowerX = massOfCurrFrag - zoomRange / 2.0
    '     higherX = massOfCurrFrag + zoomRange / 2.0
    '     Dim maxYval As Integer = _
    '       CInt(mRawDataFileHandling.maxYValueInMassRange(lowerX, higherX))
    ' 
    '     Select Case mOptions.rawFileMode
    '         Case rawFileModeEnum.enumAnalyst
    ' 
    '             'Changed PM_REFACTOR 2007-07-22
    '             ' mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.Min = lowerX
    '             ' mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.Max = higherX
    '             ' 
    '             ' 'Changed PM_REFACTOR_FINNEGAN 2003-08-18
    '             ' 'mANALYSTCOM_Data.GetYValueRangeForXValueRange( _
    '             ' '  lowerX, higherX, minYPt, maxYPt)
    '             ' 'AxGraphControl_ANALYSTCOM_1.GraphArea.YAxis.Max = _
    '             ' '  mANALYSTCOM_Data.GetDataPointYValue(maxYPt)
    '             ' mAxGraphControl_ANALYSTCOM_2.GraphArea.YAxis.Max = maxYval
    '             Me.setAnalystAxes(lowerX, higherX, maxYval)
    ' 
    '         Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
    '             'Nothing for now..
    ' 
    '         Case Else
    '             Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
    '     End Select
    ' End Sub 'ZoomFragment


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function ExtractPrecursorMCRmass() As Double

        Dim toReturn As Double = -10.0

        'Changed PM_BACK_TO_NORMAL 2003-07-29
        Dim title As String = mRawDataFileHandling.DataTitle()

        'Changed PM_FUTURE_ASSERT_MARK 2003-08-18
        'Later: check that spectrum type is MS-MS.

        Dim result As Match
        'the precursor ion mass is the only thing in parens
        result = Regex.Match(title, "\(([.0-9]+)\)")
        If result.Success Then

            'Title is expected to be from an MS-MS spectrum.
            'Sample of good title:
            '  +TOF Product (622.3): Experiment 2, 90.496 min from
            '  Q1LCMS190203_01DoubleArg.wiff a=3.56516493456177530e-004 ,
            '  t0=2.24732744132488730e+001

            Dim precursorMCRStr As String = result.Groups(1).Value
            If IsNumeric(precursorMCRStr) Then
                toReturn = CDbl(precursorMCRStr)
            End If
        Else
            'Can happen if the current spectrum is not an MS-MS spectrum, like
            'an MS spectrum!
            'Sample (one line, possibly with line break just before "a="):
            '  +TOF MS: Experiment 1, 0.034 min from
            '  Q1LCMS190203_01DoubleArg.wiff a=3.56516493456177530e-004 ,
            '  t0=2.24732744132488730e+001

            MsgBox("could not extract precursor ion mass")
        End If

        If toReturn < 0.0 Then
            Dim peter9 As Integer = 9
        End If
        Return toReturn
    End Function 'ExtractPrecursorMCRmass


    'Changed PM_REFACTOR 2007-07-22. Not currently used.
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub DisplayMS1()
    '     'Display the MS1 spectrum before or after our current tandem MS.
    '     'Keep current zoom settings, so one can see how the peak goes up and down.
    ' 
    '     Dim lowerX As Double = 400.7
    '     Dim higherX As Double = 410.2
    '     Select Case mOptions.rawFileMode
    '         Case rawFileModeEnum.enumAnalyst
    ' 
    '             lowerX = mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.Min
    '             higherX = mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.Max
    ' 
    '         Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
    '             'Nothing for now..
    ' 
    '         Case Else
    '             Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
    '     End Select
    ' 
    '     Dim title As String = mRawDataFileHandling.DataTitle()
    ' 
    '     If mFirstMS1 Then
    '         mFirstMS1 = False
    '         mCurrCycle = 0 'so we get the correct survey spectrum
    '         'if this is the first time around for MS1 for this MS/MS spectrum
    '         Dim precursorMass As Double = ExtractPrecursorMCRmass()
    ' 
    '         'We will zoom right away.
    '         lowerX = precursorMass - 5.0
    '         higherX = precursorMass + 5.0
    ' 
    '         'Display the MS1 survey spectrum before this spectrum.
    ' 
    '         Dim result As Match
    '         result = Regex.Match(title, "([.0-9]+)\s+min")
    '         Dim retT As Double
    '         If result.Success Then
    '             Dim retTstr As String = result.Groups(1).Value
    '             If IsNumeric(retTstr) Then
    '                 retT = CDbl(retTstr)
    '             End If
    '         Else
    '             MsgBox("could not get MS1 spectrum")
    '             Exit Sub
    '         End If
    ' 
    '         Dim retentionTimeSecs As Single = CSng(retT * 60)
    ' 
    '         'Changed PM_REFACTOR_FINNEGAN 2003-08-18
    '         ''Note: 3rd and 4th parameter to GetActualPeriodAndCycleFromTime() are output parameters.
    '         'mANALYSTCOM_WiffFile.GetActualPeriodAndCycleFromTime( _
    '         '  1, 0, retentionTimeSecs, theActualPeriod, mCurrCycle)
    '         Dim dummy2 As spectrumSpecStructure
    '         Dim dummy3 As SpectrumClassificationStructure
    '         dummy3.dataSourceName = Nothing 'Keep compiler happy.
    ' 
    '         mCurrCycle = _
    '           mRawDataFileHandling.newSpectrumByRetentionTime( _
    '             retentionTimeSecs, dummy2, dummy3)
    '     End If
    '     Dim maxYval As Integer = _
    '       CInt(mRawDataFileHandling.maxYValueInMassRange(lowerX, higherX))
    ' 
    '     'Changed PM_REFACTOR_FINNEGAN 2003-08-18. Not used....
    '     'Dim theNumExp As Integer = _
    '     '  mANALYSTCOM_WiffFile.GetNumberOfExperiments(1, 0)
    ' 
    '     'Changed PM_REFACTOR_FINNEGAN 2003-08-18
    '     'Dim theTime As Single = _
    '     '  mANALYSTCOM_WiffFile.GetActualTimeFromPeriodAndCycle(1, 0, 0, mCurrCycle)
    '     ''note: the routine must be called with retention time in seconds!!
    '     'Call mANALYSTCOM_Data.SetSpectrum(mWiffInfo.sample, 0, 0, theTime, theTime)
    '     Dim dummy4 As SpectrumClassificationStructure
    '     dummy4.dataSourceName = Nothing 'Keep compiler happy.
    ' 
    '     Dim retTimeSecs As Double = _
    '       mRawDataFileHandling.newSpectrumBySpectrumNumber(mCurrCycle, dummy4)
    ' 
    '     Select Case mOptions.rawFileMode
    '         Case rawFileModeEnum.enumAnalyst
    '             mAxGraphControl_ANALYSTCOM_2.SeriesColl.Item( _
    '               1).SeriesCaptionColl.RemoveAll()
    ' 
    '             'Changed PM_BACK_TO_NORMAL 2003-07-29
    '             'AxGraphControl_ANALYSTCOM_1.SeriesColl.Item(1).Title.Text = _
    '             '  mANALYSTCOM_Data.DataTitle()
    '             mAxGraphControl_ANALYSTCOM_2.SeriesColl.Item(1).Title.Text = title
    ' 
    '
    '             Dim calcFragSpec As New QS20.ExploreDataObjects.XYData
    '             
    '             If mAxGraphControl_ANALYSTCOM_2.SeriesColl.Count = 2 Then
    '             
    '                 'mAxGraphControl_ANALYSTCOM_2.SeriesColl.Item(2).DataObject() = _
    '                 '      calcFragSpec
    '                 Dim dataSource As Object = DirectCast(mRawDataFileHandling, _
    '                   AnalystRawDataFileHandling).getAnalystDataSource()
    '                     mAnalystCOM_Graph.axControl_setXYObject(2, dataSource)
    '             End If
    '
    ' 
    '             'Changed PM_REFACTOR 2007-07-22
    '             ' mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.Min = lowerX
    '             ' mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.Max = higherX
    '             ' 
    '             ' 'Changed PM_FUTURE_ASSERT_MARK 2003-08-18
    '             ' 'Old:
    '             ' 'Dim minYPt, maxYPt As Integer
    '             ' 'mANALYSTCOM_Data.GetYValueRangeForXValueRange(lowerX, higherX, minYPt, maxYPt)
    '             ' 'AxGraphControl_ANALYSTCOM_1.GraphArea.YAxis.Max = _
    '             ' '  mANALYSTCOM_Data.GetDataPointYValue(maxYPt)
    '             ' mAxGraphControl_ANALYSTCOM_2.GraphArea.YAxis.Max = maxYval
    '             Me.setAnalystAxes(lowerX, higherX, maxYval)
    ' 
    '             mAxGraphControl_ANALYSTCOM_2.InvalidateControl()
    ' 
    '         Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
    '             'Nothing for now..
    ' 
    '         Case Else
    '             Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
    '     End Select
    ' End Sub 'DisplayMS1


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuScanAllMSMS_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs)

        Trace.Assert(False, "Stop!", "PIL ASSERT. Internal/development assert for stopping execution......")

        'Changed PM_REFERENCES 2004-07-20. Disabled by outcommenting to
        '  remove reference, PEAKLISTMODULELib;
        '  object: PEAKLISTMODULELib.SpectralPeakDataList.
        '  DLL: \Analyst\bin\PeakListModule.dll

        'Dim numCycles As Integer = _
        '  mANALYSTCOM_WiffFile_2.GetActualNumberOfCycles(1, 0)
        'StatusBar1.Text = numCycles.ToString & " cycles "

        'Dim numDataPts As Long
        'Dim numPeaks As Integer
        '' Dim theOptions As IFMANSpecData

        'Dim theStartT As Single
        'Dim theCycle As Integer
        'Dim T1 As Date = Now()
        'Dim startCycle As Integer = 1000 '1
        'Dim endCycle As Integer = 1300 'numCycles
        'For theCycle = startCycle To endCycle '1 To numCycles
        '    theStartT = mANALYSTCOM_WiffFile_2.GetActualTimeFromPeriodAndCycle(1, 0, 0, theCycle)
        '    Call mANALYSTCOM_Data.SetSpectrum( _
        '      mWiffInfo.sampleNumberInRawFile, 0, 0, theStartT, theStartT)
        '    Dim theActNumPeriods As Integer = _
        '      mANALYSTCOM_WiffFile_2.GetActualNumberOfPeriods(1)

        '    'Note: 3rd and 4th parameter to GetActualPeriodAndCycleFromTime() are output parameters.
        '    mANALYSTCOM_WiffFile_2.GetActualPeriodAndCycleFromTime( _
        '      1, 0, theStartT, theActNumPeriods, theCycle)

        '    numDataPts += mANALYSTCOM_Data.GetNumberOfDataPoints 'added PeakList Module via the 'Add Reference' module
        '    'numPeaks += mANALYSTCOM_Data.spectralpeaklist
        '    Dim peakList As PEAKLISTMODULELib.SpectralPeakDataList
        '    peakList = _
        '      CType(AxGraphControl_ANALYSTCOM_2.SeriesColl.Item( _
        '        1).SpectralPeakDataList(), _
        '        PEAKLISTMODULELib.SpectralPeakDataList)
        '    numPeaks += peakList.Count()
        '    ProgressBar1.Value = _
        '      CInt((100.0 * (theCycle - startCycle)) / (endCycle - startCycle))
        'Next
        'Dim T2 As Date = Now()
        'Dim TSpan As TimeSpan = T2.Subtract(T1)
        'StatusBar1.Text &= "Read all survey spectra in " & TSpan.TotalSeconds.ToString("0") & " seconds; "
        'StatusBar1.Text &= (numDataPts / 1000000.0).ToString("0.0") & " million data points; "
        'StatusBar1.Text &= numPeaks.ToString & " peaks"
        'ProgressBar1.Value = 0
    End Sub 'mnuScanAllMSMS_Click


    '****************************************************************************
    '*    A N A L Y S T   D E P E N D E N T ,   E N D                           *
    '****************************************************************************


    'Changed PM_MARKER_FINDPEAK 2004-01-07

    '****************************************************************************
    '*    F I N D   T A G  ,   B E G I N                                        *
    '****************************************************************************


    '****************************************************************************
    '*    F I N D   T A G  ,   E N D                                            *
    '****************************************************************************


    'Changed PM_MS3INTEGRATION 2004-05-14
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub highlightMatchedFragments( _
      ByRef anInFragments As peptideFragments)

        Trace.Assert(Not anInFragments Is Nothing, _
          "PIL ASSERT. anInFragments is Nothing. In highlightMatchedFragments().")

        'Changed PM_AUTOMATCH_FRAGMENTS 2005-08-17
        'Dim MS3fragments As peptideFragments = mMS3scorer.getMS3Fragments()

        Dim tokens As List(Of Integer) = _
          anInFragments.getFragmentTokens(45.0, 99999.9)

        Dim fragment As fragmentExStructure
        Dim token As Integer
        For Each token In tokens
            fragment = anInFragments.getFragment(token)
            If fragment.ionMatched Then

                mMSMSdisplay.highLightMarker(Me, token)


                'Changed PM_REFACTOR 2007-09-19. Old. Delete at any time.
                ' 'Changed PM_QSTAR_BROKEN 2005-09-27
                ' Select Case mOptions.rawFileMode
                '     Case rawFileModeEnum.enumAnalyst
                ' 
                '     Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
                '         Trace.Assert(Not mFinneganMSMS Is Nothing, _
                '            "PIL ASSERT. mFinneganMSMS is nothing....")
                '         mFinneganMSMS.highLightMarker(Me, token)
                '     Case Else
                '         Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
                ' End Select


            End If
        Next
    End Sub 'highlightMatchedFragments


    'Changed PM_MS3INTEGRATION 2004-06-02
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub AddExtraScoreToPeptList_Visual( _
      ByVal aIonTypeStr As String, ByVal aScore As Double)

        'Put the score in the table.

        'Changed PM_PROTVAL_COLUMNS 2005-02-28
        'With lsvPeptides.SelectedItems(0)
        '    .SubItems(peptideColEnum2.eMS3precursorIon).Text = aIonTypeStr
        '    .SubItems(peptideColEnum2.eScoreWithMS3).Text = aScore.ToString("F1")
        '    'With lsvPepts.Items.Add(peptHit.AASequence)
        'End With
        Dim rowToUpdate As ListViewItem = lsvPeptides.SelectedItems(0)
        mColumnMapper.updateListItem( _
          rowToUpdate, _
          peptideColEnum2.enumMS3precursorIon, _
          aIonTypeStr)
        mColumnMapper.updateListItem( _
          rowToUpdate, _
          peptideColEnum2.enumScoreWithMS3, _
          aScore.ToString("F1"))
    End Sub 'AddExtraScoreToPeptList_Visual


    'Changed PM_MS3INTEGRATION 2004-06-02
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function AddExtraScoreToPeptStruct( _
      ByVal aIonTypeStr As String, ByVal aScore As Double) As Double

        'Write back the score to the underlying pepide data structure, so we
        'can export it convert from visible index to index
        'in mProt.pepts ArrayList.

        Dim toReturn As Double = 0.0

        Dim outToken As Integer
        Dim pept As PeptideHitStructure
        pept = getPeptideFromVisualIndex(mCurrentlySelectedPeptIdx, outToken)

        'Let it work if this function is called several times (different MS3
        '  scores, the last call being for the best score).
        'If aScore > peptHit.MascotScorePlusMS3Score Then
        If True Then

            'Changed PM_MASCOTSCORE_ASDOUBLE 2008-11-25. No
            'longer implicit conversion from integer to
            'double...
            pept.MascotScorePlusMS3Score = _
              pept.MascotScore2 + aScore

            toReturn = pept.MascotScorePlusMS3Score

            pept.MS3precursorStr = aIonTypeStr

            mProt.peptides.updatePeptideByToken(outToken, pept)

            'Changed PM_MS3_EXPORT 2005-01-25
            'We must also update this:
            mLastPeptHit = pept

            'Should we also update mCurrSelPept???
        Else
            Dim peter71 As Integer = 71
        End If

        Return toReturn
    End Function 'AddExtraScoreToPeptStruct


    'Changed PM_MS3INTEGRATION 2004-05-12
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function MS3_NextSpecAndCalcExtraScore( _
      ByVal aPeptideCharge As Integer) _
      As Boolean

        'Changed PM_REFACTOR 2005-08-15

        Dim quantitationModesObject As QuantitationModes_moreGeneral = _
          mApplication.getQuantModes()

        Dim modificationsList As List( _
          Of List(Of AAsetStruct)) = _
            quantitationModesObject.constructSimpleModificationList( _
              mCurrSelPept.modHits2)

        'Changed PM_COMB_FOR_MS3 2006-08-01
        'Dim dummy1 As ionSetStructure
        'dummy1.backwardIonDiffs = Nothing 'Keep compiler happy.
        'dummy1.forwardIonDiffs = Nothing 'Keep compiler happy.
        'Note: is set as a side effect in updatePTM_GUIdisplay().
        Dim comb As ionSetStruct = mCurrentComb

        'Dim matchedFragmentForBestMSscore As fragmentExStructure
        Dim MS3fragments As peptideFragments = Nothing 'Keep compiler happy.

        Dim MS3matchInfo As MS3matchStructure
        MS3matchInfo.explainString = Nothing 'Keep compiler happy.
        MS3matchInfo.matchedFragmentForBestMSscore.descStr = _
          Nothing 'Keep compiler happy.
        MS3matchInfo.matchedFragmentForBestMSscore.seq = _
          Nothing 'Keep compiler happy.

        'Why are we using two different peptides, mLastPeptHit and mCurrSelPept ???
        'And the charge is provided by the caller??
        mMS3scorer.MS3score( _
          mMSMSFragments, mLastPeptHit.AASequence, _
           aPeptideCharge, mCurrSelPept.rawFileID, _
          modificationsList, "currPeptMod", comb, _
          Nothing, _
          mReductionParameters2, _
          MS3fragments, _
          MS3matchInfo, _
          mLastPeptHit.modHits2, _
          mLastPeptHit.queryNumber _
          )

        'Changed PM_DOTNET_HELL 2007-06-25
        'Defaults if not scored.
        Dim descrStr As String = "" 'Precursor
        Dim extraScore As Double = 0.0

        If MS3matchInfo.MS3scored Then

            'Changed PM_ION_SERIES_DISPLAYOPTION 2008-05-26
            Dim showOnlyMatchedIons As Boolean = mApplication.getShowOnlyMatchedIons()

            displaySpectrumInformation(MS3matchInfo.ms3spectrumNumber)
            displaySpectrumWithFragments( _
              mCurrSelPept.rawFileID, MS3fragments, showOnlyMatchedIons)

            Dim anyMS3fragments As Boolean
            highlightMatchedFragments( _
              mMS3scorer.getMS3Fragments(anyMS3fragments))

            'Changed PM_OLD_BUTTONS 2006-11-12
            'txtScore.Text = "Extra score: " & _
            '  MS3matchInfo.extraScoreByMS3.ToString("F1")


            'Changed PM_CLEAR_MS3 2007-06-25
            'Scoring/precursor stuff was here...
            descrStr = _
              MS3matchInfo.matchedFragmentForBestMSscore.descStr 'Precursor
            extraScore = MS3matchInfo.extraScoreByMS3

        Else
            If Not MS3matchInfo.foundMS3spectrum Then
                'Clear spectrum so as not to confuse the user.

                mMSMSdisplay.clearDisplay("No MS3 spectra found")


                'Changed PM_REFACTOR 2007-09-19. Old. Delete at any time.
                ' Select Case mOptions.rawFileMode
                '     Case rawFileModeEnum.enumAnalyst
                '         'Not yet....
                '     Case rawFileModeEnum.enumFinnegan, _
                '          rawFileModeEnum.enumMicromass
                ' 
                '         mFinneganMSMS.clearDisplay("No MS3 spectra found")
                ' End Select

            Else
                Me.setSpectrumAndDisplay(MS3matchInfo.ms3spectrumNumber)
                If Not MS3matchInfo.foundCloseEnoughFragmentPrecursor Then

                End If
            End If

            lblExtraInfo.BackColor = Color.Salmon
            lblExtraInfo.Text = MS3matchInfo.explainString

            lblExtraInfo.BringToFront()

            'Changed PM_OLD_BUTTONS 2006-11-12
            'lblMSMSMSInfo2.BringToFront()
        End If

        'Changed PM_CLEAR_MS3 2007-06-25
        'Moved down here. Score and precursor string should also
        'be updated (cleared) when MS3 score can not be found. This
        'is important when one PTM combination results in a MS3 score
        'and then for another PTM combination it can not be found (no 
        'precursor was found).
        Dim absScore As Double = _
          AddExtraScoreToPeptStruct(descrStr, extraScore)
        '
        ''Changed PM_MS3INTEGRATION 2004-06-07
        'Post absolute score. Must be AFTER
        'AddExtraScoreToPeptStruct().
        AddExtraScoreToPeptList_Visual(descrStr, absScore)
    End Function 'NextSpecAndCalcExtraScore


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function getCurrentDataPoints() _
    As List(Of massSpectrometryBase.signalStructure)

        'Old return type:
        '  ArrayList

        'Changed PM_REFACTOR 2006-10-12
        'Dim toReturn As ArrayList = Nothing
        Dim toReturn As _
          List(Of massSpectrometryBase.signalStructure) = Nothing

        If Not mLastMSMSSignal Is Nothing Then

            Dim zoom As massZoomStructure = mMSMSdisplay.getZoomRange()

            'Changed PM_REFACTOR 2007-09-19. Old. Delete at any time.
            ' Dim zoom As massZoomStructure
            ' zoom.startMass = -10.0
            ' zoom.endMass = 1.0E+28
            ' Select Case mOptions.rawFileMode
            '     Case rawFileModeEnum.enumAnalyst
            ' 
            '     Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
            '         zoom = mFinneganMSMS.getZoomRange()
            '     Case Else
            '         Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
            ' End Select

            Dim maxY As Double
            BSignal.filterSignalByMassRange( _
              mLastMSMSSignal, zoom.startMass, zoom.endMass, toReturn, _
              maxY)
        Else
            Dim peter81 As Integer = 81 'For breakpoints.
        End If
        If toReturn Is Nothing Then
            'toReturn = New ArrayList
            toReturn = New List(Of massSpectrometryBase.signalStructure)
        End If
        Return toReturn
    End Function 'getCurrentDataPoints


    'Changed PM_XY_EXPORT 2005-01-05
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function spectrumDatapointsSaveString( _
      ByVal anInInsertZeros As Boolean) As String

        Dim toReturn As String = ""

        'Changed PM_REFACTOR 2006-10-12
        'Dim signalToUse As ArrayList = getCurrentDataPoints()
        Dim signalToUse As _
          List(Of massSpectrometryBase.signalStructure) = _
            getCurrentDataPoints()

        toReturn = PILoutUtil.dumpXYSpectrumPoints( _
          signalToUse, mRawDataFileHandling.DataTitle(), _
          mLastPeptHit.AASequence, mProt.accNum, _
          "Fragment spectrum data points", _
          anInInsertZeros)
        Return toReturn
    End Function 'spectrumDatapointsSaveString


    'Changed PM_XY_EXPORT 2005-01-05
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuExportSpectrumDataPoints_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuExportSpectrumDataPoints.Click

        Dim str As String = spectrumDatapointsSaveString(True)

        'Changed PM_BROKENEXPORT 2008-05-28
        'Excel for now.
        Dim ex As exportTargetSettingsStruct = _
          exportTargetSettingsStruct.defaultExportTargetSettings()
        ex.target = targetEnum.enumExportToExcel

        PILInputOutput.pushToTarget(str, ex, AppCommon2.appPath())
    End Sub 'mnuExportSpectrumDataPoints_Click


    'Changed PM_XY_EXPORT 2005-01-05
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSaveSpectrumDataPoints_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuSaveSpectrumDataPoints.Click

        If Not mLastPeptHit.AASequence Is Nothing Then
            Dim suggestedFileName As String = _
              "fragments_" & mProt.accNum & "_" & mLastPeptHit.AASequence

            Dim str As String = spectrumDatapointsSaveString(True)

            'Use return value for some text reporting to GUI?
            Dim wasSaved As Boolean = _
              pushToUserSelectedFile2( _
                str, _
                "Saved current spectrum data points to file.", _
                suggestedFileName)
        Else
            MsgBox("Could not save datapoints. No fragment spectra have been displayed yet. Open some peptide to display a fragment spectrum.")
        End If
    End Sub 'mnuSaveSpectrumDataPoints_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function reducedListSaveString() As String

        Dim toReturn As String = ""

        'Dim inputSignal As ArrayList = getCurrentDataPoints()
        Dim inputSignal As _
          List(Of massSpectrometryBase.signalStructure) = _
            getCurrentDataPoints()

        'Changed PM_TYPESAFE 2006-11-01
        'Dim peakList As ArrayList = Nothing 'Keep compiler happy.
        Dim peakList As List(Of LCPeakInfoStructure) = Nothing 'Keep
        '  compiler happy.

        If True Then
            Dim catchDistance As Double = 0.3 'Bigger peaks will not svallow smaller
            '  ones, even if the data is already centroided.
            Dim catchDistanceForExtension As Double = 1.1
            'Dim findPeaksMaxSearchLevel As Integer = 99
            'Dim findPeaksMaxSearchLevel As Integer = 5
            Dim findPeaksMaxSearchLevel As Integer = 6
            Dim actualDeepestSearchLevel As Integer

            BSignal.findThePeaksNonEx( _
              inputSignal, _
              peakList, _
              catchDistance, catchDistanceForExtension, _
              findPeaksMaxSearchLevel, actualDeepestSearchLevel)
        End If

        'Changed PM_REFACTOR 2006-10-12
        'Dim peakList2 As ArrayList = _
        '  BSignal.convertListTo_signalStructureList(peakList)
        Dim peakList2 As List(Of massSpectrometryBase.signalStructure) = _
          BSignal.convertListTo_signalStructureList(peakList)

        toReturn = PILoutUtil.dumpXYSpectrumPoints( _
          peakList2, mRawDataFileHandling.DataTitle(), _
          mLastPeptHit.AASequence, mProt.accNum, _
          "Reduced data (peak list) ", _
          False)
        Return toReturn
    End Function 'reducedListSaveString


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSaveReducedPeakList_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuSaveReducedPeakList.Click

        If Not mLastPeptHit.AASequence Is Nothing Then
            Dim suggestedFileName As String = _
              "peakList_" & mProt.accNum & "_" & mLastPeptHit.AASequence

            Dim str As String = reducedListSaveString()

            'Use return value for some text reporting to GUI?
            Dim wasSaved As Boolean = _
              pushToUserSelectedFile2( _
                str, _
                "Saved peaklist to file.", _
                suggestedFileName)
        Else
            MsgBox("Could not save peaklist. No fragment spectra have been displayed yet. Open some peptide to display a fragment spectrum.")
        End If
    End Sub 'mnuSaveReducedPeakList_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuExportReducedPeakList_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuExportReducedPeakList.Click

        Dim str As String = reducedListSaveString()

        'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
        ''Changed PM_BROKENEXPORT 2008-05-28
        ''Excel for now.
        'Dim ex As exportTargetSettingsStruct = _
        '  exportTargetSettingsStruct.defaultExportTargetSettings()
        'ex.target = targetEnum.enumExportToExcel
        Dim exportTargetSettings As exportTargetSettingsStruct = _
          Me.getGlobalTargetSettings()

        PILInputOutput.pushToTarget( _
          str, exportTargetSettings, AppCommon2.appPath())
    End Sub 'mnuExportReducedPeakList_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function ms3dumpInformationSaveString() As String

        'Provide some header as well?

        'Return mMS3dumpSB.ToString()
        Return mMS3scorer.getMS3dump()
    End Function 'ms3dumpInformationSaveString


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSaveMS3dumpInformation_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuSaveMS3dumpInformation.Click

        Dim str As String = ms3dumpInformationSaveString()

        If str <> "" Then
            'Use return value for some text reporting to GUI?
            Dim wasSaved As Boolean = _
              pushToUserSelectedFile2( _
                str, _
                "Saved peaklist to file.", _
                "MS3dump.txt")
        Else
            Dim msgStr As String = _
              "No output. " & AppConstants.LONG_APP & _
              " could not output anything because no MS3 scoring " & _
              "has taken place. Do some MS3 scoring first."
            MsgBox(msgStr)
        End If
    End Sub 'mnuSaveMS3dumpInformation_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuExportMS3dumpInformation_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuExportMS3dumpInformation.Click

        Dim str As String = ms3dumpInformationSaveString()
        If str <> "" Then

            'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
            ''Changed PM_BROKENEXPORT 2008-05-28
            ''Excel for now.
            'Dim ex As exportTargetSettingsStruct = _
            '  exportTargetSettingsStruct.defaultExportTargetSettings()
            'ex.target = targetEnum.enumExportToExcel
            Dim exportTargetSettings As exportTargetSettingsStruct = _
              Me.getGlobalTargetSettings()

            PILInputOutput.pushToTarget( _
              str, exportTargetSettings, AppCommon2.appPath())
        Else
            Dim msgStr As String = _
              "No output. " & AppConstants.LONG_APP & _
              " could not output anything because no MS3 scoring has " & _
              "taken place. Do some MS3 scoring first."
            MsgBox(msgStr)
        End If
    End Sub 'mnuExportMS3dumpInformation_Click


    'Changed PM_REFACTOR 2007-09-25. Disabled for now. Do we still need it?
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub AxGraphControl_ANALYSTCOM_2_GraphZoom( _
    '   ByVal aSender As Object, _
    '   ByVal anEvent As graphZoom2EventArgs) _
    '   Handles mAnalystCOM_Graph.GraphZoom2
    ' 
    '     'Old:
    '     '  ByVal anEvent As AxQS20_GraphControlLib._DGraphControlEvents_GraphZoomEvent
    '     '  Handles mAxGraphControl_ANALYSTCOM_2.GraphZoom
    ' 
    ' 
    '     'Changed PM_REFACTOR 2007-07-22
    '     'frmAnalystSpectraWithLabelMarkers.avoidInvalidNumberOfParametersError( _
    '     '  mAnalystCOM_Graph)
    '     mAnalystCOM_Graph.avoidInvalidNumberOfParametersError()
    ' End Sub 'AxGraphControl_ANALYSTCOM_2_GraphZoom


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function currentFragmentsString() As String

        Dim fragSB As StringBuilder = New StringBuilder(5000)

        Dim anyMS3fragments As Boolean
        Dim MS3fragments As peptideFragments = _
          mMS3scorer.getMS3Fragments(anyMS3fragments)

        Dim peptideInfoSB As StringBuilder = New StringBuilder(3000) 'What
        '  is a good size. Should we allow peptideTableHeaderWithAheader to
        '  accept Nothing and create one with an appropriate capacity set?

        'Changed PM_FRAGMENTS_PEPTIDEINFO 2007-03-22
        If True Then
            Dim miscSettings As miscSettingsStructure2Struct = _
              mApplication.getMiscSettings()

            quantApplication.peptideTableHeaderWithAheader( _
              "", miscSettings.option1b, _
              mApplication, mOptions.quantModeCode, _
              peptideInfoSB)

            'What is simple about this???
            quantApplication.addPeptideLine_simple( _
              mLastPeptHit, _
              mProt, _
              mApplication, _
              mOptions.quantModeCode, _
              peptideInfoSB _
            )
        End If

        fragSB.Append("MS2:")
        fragSB.Append(ControlChars.NewLine)
        mMSMSFragments.fragmentsSaveString(fragSB, peptideInfoSB)
        fragSB.Append(ControlChars.NewLine)

        If anyMS3fragments Then
            fragSB.Append("MS3:")
            fragSB.Append(ControlChars.NewLine)
            MS3fragments.fragmentsSaveString(fragSB, peptideInfoSB)
            fragSB.Append(ControlChars.NewLine)
        End If

        Return fragSB.ToString()
    End Function 'currentFragmentsString


    'Changed PM_FINNEGAN_MSMS_DISPLAY 2004-02-04
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuExportFragments_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuExportFragments.Click

        'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
        ''Changed PM_BROKENEXPORT 2008-05-28
        ''Excel for now.
        'Dim ex As exportTargetSettingsStruct = _
        '  exportTargetSettingsStruct.defaultExportTargetSettings()
        'ex.target = targetEnum.enumExportToExcel
        Dim exportTargetSettings As exportTargetSettingsStruct = _
          Me.getGlobalTargetSettings()

        PILInputOutput.pushToTarget( _
          Me.currentFragmentsString(), _
          exportTargetSettings, _
          AppCommon2.appPath())
    End Sub 'mnuExportFragments_Click


    'Changed PM_FINNEGAN_MSMS_DISPLAY 2004-02-04
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSaveFragments_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuSaveFragments.Click

        Dim suggestedFileName As String = _
          "theoFragments_" & mLastPeptHit.AASequence

        'Use return value for some text reporting to GUI?
        Dim wasSaved As Boolean = _
          pushToUserSelectedFile2( _
            Me.currentFragmentsString(), _
            "Saved current theoretical fragments to file.", _
            suggestedFileName)
    End Sub 'mnuSaveFragments_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub setPeptideListViewColumns( _
      ByRef anApplication As quantApplication)

        Dim full As Boolean = False 'True for the old numbers of columns.

        Dim settings As miscSettingsStructure2Struct = _
          anApplication.getMiscSettings()
        Dim shv1b As Boolean = True
        If False AndAlso (settings.option1b And 1) = 0 Then
            shv1b = False
        End If

        'This will void any design time settings...
        lsvPeptides.Columns.Clear()

        'Changed PM_COLUMNALIGNMENT 2008-04-16
        Dim numberAlignment As HorizontalAlignment = HorizontalAlignment.Right


        'This one is mandatory.
        'And sequence must be first as this is how we (currently) add a
        'new item (and that gets the checkbox).
        mColumnMapper.newColumn( _
          "Sequence", 295 - 40 - 20, peptideColEnum2.enumSequence, _
          HorizontalAlignment.Left, False) '20 to
        '   get the scroll bar right!
        'Changed PM_PROTVAL_SCROLLBAR 2007-07-27

        'This one is mandatory as it is currently read back.
        mColumnMapper.newColumn( _
          "Modification", 70, peptideColEnum2.enumModStr, _
          HorizontalAlignment.Left, False)

        'This one is mandatory as it is currently read back.
        mColumnMapper.newColumn( _
          "Query", 51, peptideColEnum2.enumQueryNumber, _
          numberAlignment, False)

        mColumnMapper.newColumn( _
          "Mascot Score", 40, peptideColEnum2.enumMascotScore, _
          numberAlignment, False)

        'Changed PM_ID_SILACDISH 2008-07-15
        mColumnMapper.newColumn( _
          "Dish for peptide ID", 44, peptideColEnum2.enumID_SILACdish, _
          numberAlignment, False)

        mColumnMapper.newColumn( _
          "MS3 score", 64 - 20, peptideColEnum2.enumScoreWithMS3, _
          numberAlignment, False)

        mColumnMapper.newColumn( _
          "MS3 precursor", 82 - 40 + 20, peptideColEnum2.enumMS3precursorIon, _
          HorizontalAlignment.Left, False)

        If shv1b Then
            mColumnMapper.newColumn( _
              "PTM score", 64 - 20, peptideColEnum2.enumScoreWithPTM, _
              numberAlignment, False)

            'Changed PM_PHOSPHO_SCORING_DISPLAY 2005-10-19
            mColumnMapper.newColumn( _
              "PTM info", 70, peptideColEnum2.enumPTMinfo, _
              HorizontalAlignment.Left, False)
        End If

        'Changed PM_STANDARDS_COMPLIANCE 2005-10-20
        mColumnMapper.newColumn( _
          "LF", 20, peptideColEnum2.enumLeftFlankingAA, _
          HorizontalAlignment.Center, False)
        mColumnMapper.newColumn( _
          "RF", 20, peptideColEnum2.enumRightFlankingAA, _
          HorizontalAlignment.Center, False)

        If full Then
            mColumnMapper.newColumn( _
              "M. chckd", 58, peptideColEnum2.enumMascorCheckBoxChecked, _
              HorizontalAlignment.Center, False)
            mColumnMapper.newColumn( _
              "Rank", 38, peptideColEnum2.enumMascotRank, _
              numberAlignment, False)
        End If

        mColumnMapper.newColumn( _
          "Charge", 15, peptideColEnum2.enumCharge, _
          numberAlignment, False)

        mColumnMapper.newColumn( _
          "MCR [Th]", 65, peptideColEnum2.enumMeasuredMCR2, _
          numberAlignment, False)

        If full Then
            mColumnMapper.newColumn( _
              "Calc. Mass [Da]", 90, peptideColEnum2.enumCalculatedMass, _
              numberAlignment, False)
        End If

        mColumnMapper.newColumn( _
          "Rel.err [ppm]", 48, peptideColEnum2.enumRelativeError, _
          numberAlignment, False)

        'Changed PM_UNIQUE_COLUMN_IS_USELESS 2005-04-13
        'Is useless!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        If False Then
            'Changed PM_UNIQUE_COLUMN 2005-04-06. Moved from full.
            mColumnMapper.newColumn( _
              "Unique", 47, peptideColEnum2.enumNumSeqOcc, _
              HorizontalAlignment.Left, False)
        End If

        'Changed PM_MKI_MISSED_CLEAVAGES 2005-04-14
        mColumnMapper.newColumn( _
          "Missed", 36, peptideColEnum2.enumMissedCleavages, _
          numberAlignment, False)

        mColumnMapper.newColumn( _
          "Delta score", 40, peptideColEnum2.enumMascotDeltaScore, _
          numberAlignment, False)

        If full Then
            mColumnMapper.newColumn( _
              "Ret. T. [min]", 60, peptideColEnum2.enumRetentionTime, _
              numberAlignment, False)
            mColumnMapper.newColumn( _
              "period", 41, peptideColEnum2.enumPeriod, _
              numberAlignment, False)
            mColumnMapper.newColumn( _
              "exp", 30, peptideColEnum2.enumExperiment, _
              numberAlignment, False)
            mColumnMapper.newColumn( _
              "cycle", 38, peptideColEnum2.enumCycle, _
              numberAlignment, False)
        End If

        Dim origPixels As Integer = lsvPeptides.Width
        Dim newPixels As Integer = mColumnMapper.effectivePixelWidth()
        lsvPeptides.Width = newPixels
    End Sub 'setPeptideListViewColumns


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub btnAccProtAndMoveNext_Click( _
      ByVal sender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles btnAccProtAndMoveNext.Click

        'Note: also in a menu
        proteinMoveToNextProtein(True)
    End Sub 'btnAccProtAndMoveNext_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub btnRejProtAndMoveNext_Click( _
      ByVal sender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles btnRejProtAndMoveNext.Click

        'Note: also in a menu
        proteinMoveToNextProtein(False)
    End Sub 'btnRejProtAndMoveNext_Click


    'Changed PM_USER_EXACT_ZOOM 2005-03-03
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuZoom_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuZoom.Click

        Dim zoom As massZoomStructure = mMSMSdisplay.getZoomRange()

        Dim zoomRangeForm As New frmZoomRange(zoom, Me)
        zoomRangeForm.Show()
    End Sub 'mnuZoom_Click


    'Changed PM_USER_EXACT_ZOOM 2005-03-03
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub setZoomRange( _
      ByVal aZoom As massZoomStructure)

        mMSMSdisplay.setZoomRange2(aZoom)
        mMSMSdisplay.refresh2()
    End Sub 'setZoomRange


    'Changed PM_SHORTCUT_ACCEPTPROTEIN 2005-03-03
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuAcceptProtein_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuAcceptProtein.Click

        'Note: also in a button
        proteinMoveToNextProtein(True)
    End Sub 'mnuAcceptProtein_Click


    'Changed PM_SHORTCUT_ACCEPTPROTEIN 2005-03-03
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuRejectProtein_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuRejectProtein.Click

        'Note: also in a button
        proteinMoveToNextProtein(False)
    End Sub 'mnuRejectProtein_Click


    'Changed PM_VALIDATIONWINDOW_SHORTCUTS 2005-07-07
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuAcceptPeptide_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuAcceptPeptide.Click

        MarkPeptVerifiedAndMoveToNext()
    End Sub 'mnuAcceptPeptide_Click


    'Changed PM_VALIDATIONWINDOW_SHORTCUTS 2005-07-07
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuRejectPeptide_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuRejectPeptide.Click

        MarkPeptNotVerifAndMoveNext()
    End Sub 'mnuRejectPeptide_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub updateSpectrumDisplay(ByVal aLevel As Integer)

        'Note: for Analyst there is only 2 levels.

        If True Then
            Select Case aLevel
                Case -3 'E.g. Full scan when ID is from MS3 spectrum.

                Case -2 'E.g. Full scan

                Case -1 'E.g. SIM

                Case 0 'ID spectrum, in most cases a MS/MS spectrum.

                Case Else
                    'OK
            End Select
        End If
    End Sub 'updateSpectrumDisplay


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub addChargedMSmarker( _
      ByVal aNeutralPeptideMass As Double, _
      ByVal aCharge As Integer, _
      ByVal aLabel As String)

        Dim diff1 As Double = MSconstants.C12_C13_DIFF / aCharge
        Dim diff2 As Double = 2 * diff1

        'Changed PM_REFACTOR 2008-05-20
        'Dim calculatedMCR As Double = _
        '  aNeutralPeptideMass / aCharge + MSconstants.PROTON_MASS
        Dim calculatedMCR As Double = _
          PILmassCalc.chargeTransform(aNeutralPeptideMass, 0, aCharge)

        Dim newMarker As markerStructure
        newMarker.MCR = calculatedMCR

        newMarker.ionType3 = ionTypeEnum.enumPrecursorIon2
        newMarker.labelDescription = aLabel
        newMarker.charge = aCharge
        newMarker.tag = calculatedMCR.ToString("0.0000")

        'Changed PM_VS2005_SERIOUS 2006-06-15
        newMarker.moreDescription = ""

        'Dim overrideColor As Color = Color.Empty
        Dim overrideColour As Color = Color.Green

        Const MASSMARKERSIZE As Integer = 37

        mMSMSdisplay.addMarker2( _
          newMarker, MASSMARKERSIZE, False, _
          overrideColour, labelDirectionEnum.enumLineDown, 0, 0)

        'Changed PM_REFACTOR 2007-09-19. Old. Delete at any time.
        ' Select Case mOptions.rawFileMode
        '     Case rawFileModeEnum.enumAnalyst
        ' 
        '     Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
        '         'For now: only Finnigan!!!
        '         mFinneganMSMS.addMarker( _
        '           Me, mFarOff, newMarker, MASSMARKERSIZE, False, _
        '           overrideColour)
        '     Case Else
        '         Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
        ' End Select

        'C13
        If True Then
            newMarker.labelDescription = "+1"
            newMarker.MCR += diff1

            mMSMSdisplay.addMarker2( _
              newMarker, MASSMARKERSIZE, False, _
              overrideColour, labelDirectionEnum.enumLineDown, 0, 0)

            'Changed PM_REFACTOR 2007-09-19. Old. Delete at any time.
            ' ' Select Case mOptions.rawFileMode
            ' Select Case mOptions.rawFileMode
            '     Case rawFileModeEnum.enumAnalyst
            ' 
            '     Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
            '         'For now: only Finnigan!!!
            '         mFinneganMSMS.addMarker( _
            '           Me, mFarOff, newMarker, MASSMARKERSIZE, False, _
            '           overrideColour)
            '     Case Else
            '         Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
            ' End Select
        End If

        '2 x C13
        If True Then
            newMarker.labelDescription = "+2"
            newMarker.MCR += diff1

            mMSMSdisplay.addMarker2(newMarker, MASSMARKERSIZE, False, _
              overrideColour, labelDirectionEnum.enumLineDown, 0, 0)

            'Changed PM_REFACTOR 2007-09-19. Old. Delete at any time.
            ' Select Case mOptions.rawFileMode
            '     Case rawFileModeEnum.enumAnalyst
            ' 
            '     Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
            '         'For now: only Finnigan!!!
            '         mFinneganMSMS.addMarker( _
            '           Me, mFarOff, newMarker, MASSMARKERSIZE, False, _
            '           overrideColour)
            '     Case Else
            '         Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
            ' End Select
        End If

    End Sub 'addMSmarker


    'Changed PM_REFACTOR 2007-07-11
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub displaySpectrum_NoFragments( _
      ByVal aSpectrumNumber As Integer, _
      ByVal anExperiment As Integer)

        setSpectrumAndDisplay(aSpectrumNumber, anExperiment)

        Dim outSignal As List(Of massSpectrometryBase.signalStructure) = _
          Nothing 'Keep compiler happy.

        Dim dataPointsInfo As dataPointsInfoStructure2
        Dim lowestX As Double
        Dim highestX As Double

        'Dim calcFragSpec_ANALYSTCOM As QS20.ExploreDataObjects.XYData = _
        '  Nothing 'Keep compiler happy.

        Me.displayRawSpectrum( _
          mRawDataFileHandling, mLastPeptHit.rawFileID, _
          outSignal, dataPointsInfo, lowestX, highestX, _
          mRawDataFileHandling)
        'Old: calcFragSpec_ANALYSTCOM

    End Sub 'displaySpectrum_NoFragments


    'Changed PM_SPECTRUM_BROWSE 2005-08-04
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub leveledSpectrumUpdate(ByVal aSpectrumInfo As specStruct)

        'Changed PM_SPECTRUMDOWN_FULLDISPLAY 2007-07-10. Use full
        'display if ID spectrum (an MS2 or MS3 spectrum).
        If aSpectrumInfo.isIDspectrum Then
            'Full display: matched fragments, etc.
            DisplayNthPeptide(mCurrentlySelectedPeptIdx, "", 0)
        Else
            displaySpectrum_NoFragments( _
              aSpectrumInfo.specNumb, _
              aSpectrumInfo.experimentNumber)
        End If

        If aSpectrumInfo.isMSspectrum Then
            Dim baseMass As Double = mLastPeptHit.MascotCalculatedMass
            Dim charge As Integer = mLastPeptHit.charge

            Dim chargeStr As String = mMSMSdisplay.chargeEncoding(charge)

            'Changed PM_REFACTOR 2007-09-19. Old. Delete at any time.
            ' Dim chargeStr As String = Nothing 'Keep compiler happy.
            ' Select Case mOptions.rawFileMode
            '     Case rawFileModeEnum.enumAnalyst
            ' 
            '     Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
            '         'For now: only Finnigan!!!
            '         chargeStr = mMSMSdisplay.chargeEncoding(charge)
            '     Case Else
            '         Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
            ' End Select

            Me.addChargedMSmarker( _
              baseMass, _
              mLastPeptHit.charge, _
              "ID pept" & chargeStr)

            Dim neutralLossMass1 As Double = _
              baseMass - MSconstants.PHOSPHORYLATION_DIFF_98
            Me.addChargedMSmarker( _
              neutralLossMass1, _
              charge, _
              "p1" & chargeStr)

            Dim neutralLossMass2 As Double = _
              baseMass - 2 * MSconstants.PHOSPHORYLATION_DIFF_98
            Me.addChargedMSmarker( _
              neutralLossMass2, _
              charge, _
              "p2" & chargeStr)
        End If 'MS spectrum
    End Sub 'leveledSpectrumUpdate


    'Changed PM_SPECTRUM_BROWSE 2005-07-29
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuUpSpectrumLevel_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuUpSpectrumLevel.Click

        Try
            'Changed PM_MARKER 2007-08-08. Note: does still not work for the others.
            If quantApplication.isFinnegan(mOptions.rawFileMode) Then
                Dim spectrumInfo As specStruct
                If mSpectrumTree.moveUp(spectrumInfo) Then
                    leveledSpectrumUpdate(spectrumInfo)
                End If 'moveUp
            End If

        Catch exceptionObject As Exception
            Dim errMsg1 As String = "Error: " & exceptionObject.ToString & ControlChars.NewLine
            Dim errMsg2 As String = _
              "Message: " & exceptionObject.Message & ControlChars.NewLine
            Dim errMsg3 As String = ""
            If Not exceptionObject.InnerException Is Nothing Then
                errMsg3 = _
                    "Extra info: " & exceptionObject.InnerException.Message & ControlChars.NewLine
            End If
            Dim errMsg As String = errMsg1 & errMsg2 & errMsg3
            MsgBox(errMsg)
            Exit Sub
        End Try
    End Sub 'mnuUpSpectrumLevel_Click


    'Changed PM_SPECTRUM_BROWSE 2005-08-01
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuDownSpectrumLevel_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuDownSpectrumLevel.Click

        Try
            'Changed PM_MARKER 2007-08-08. Note: does still not work for the others.
            If quantApplication.isFinnegan(mOptions.rawFileMode) Then
                Dim spectrumInfo As specStruct
                If mSpectrumTree.moveDown(spectrumInfo) Then
                    leveledSpectrumUpdate(spectrumInfo)
                End If 'moveDown
            End If

        Catch exceptionObject As Exception
            Dim errMsg1 As String = "Error: " & exceptionObject.ToString & ControlChars.NewLine
            Dim errMsg2 As String = _
              "Message: " & exceptionObject.Message & ControlChars.NewLine
            Dim errMsg3 As String = ""
            If Not exceptionObject.InnerException Is Nothing Then
                errMsg3 = _
                    "Extra info: " & exceptionObject.InnerException.Message & ControlChars.NewLine
            End If
            Dim errMsg As String = errMsg1 & errMsg2 & errMsg3
            MsgBox(errMsg)
            Exit Sub
        End Try

    End Sub 'mnuDownSpectrumLevel_Click


    'Changed PM_PHOSPHO_SCORING 2005-09-08
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub updatePTMscoreInDataStructures( _
      ByVal aScore As Double, ByVal aBestComb As ionSetStruct, _
      ByRef anInPTMScorer As PTMscorer)

        If True Then
            Dim outToken As Integer
            Dim pept As PeptideHitStructure
            pept = getPeptideFromVisualIndex(mCurrentlySelectedPeptIdx, outToken)

            If pept.PTMs2 Is Nothing Then
                pept.PTMs2 = New List(Of onePTMStructure)
                Dim emptyPTM As onePTMStructure
                emptyPTM.combinations2 = Nothing 'Keep compiler happy.

                pept.PTMs2.Add(emptyPTM)
            End If
            Dim oldList2 As List(Of onePTMStructure) = pept.PTMs2

            'Changed PM_PHOSPHO_SCORING_EXPORT 2005-10-20
            Trace.Assert(oldList2.Count = 1, "PIL ASSERT. <message>.")

            Dim oldPTM As onePTMStructure = oldList2(0) 'Assume only
            '  one kind of PTM...

            Dim somePTM As onePTMcombinationStructure
            somePTM.positions2 = Nothing 'Keep compiler happy.

            'Changed PM_PHOSPHO_SCORING_USERSEL 2005-12-21
            somePTM.checked7 = False 'To be explicit

            ' somePTM.score = aScore 'Use aBestComb.score instead?
            ''  bestComb.positions = Nothing 'For now.
            Dim acceptedCombination As Boolean
            anInPTMScorer.fillInExternalStructures( _
              aBestComb, somePTM, acceptedCombination)

            'Changed PM_POSEXCLUDING_MODS 2008-06-18
            If acceptedCombination Then
                'Dim onePTM As onePTMStructure 'The best scoring one.
                'onePTM.combinations = New ArrayList
                If oldPTM.combinations2 Is Nothing Then
                    oldPTM.combinations2 = New List(Of onePTMcombinationStructure)
                End If

                oldPTM.combinations2.Add(somePTM)

                ''peptHit.PTMScore = aScore
                'peptHit.PTMs = New ArrayList 'Overwrites any existing...
                'peptHit.PTMs.Add(onePTM)
                oldList2(0) = oldPTM
                pept.PTMs2 = oldList2

                mProt.peptides.updatePeptideByToken(outToken, pept)

                'We must also update this:
                mLastPeptHit = pept
            End If 'Accepted combination.

        End If 'Block.

    End Sub 'updatePTMscoreInDataStructures


    'Changed PM_PHOSPHO_SCORING_USERSEL 2005-12-21
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub checkForHighestPTMscore(ByVal aScoreTolerance As Double)

        'aScoreTolerance is in unit of PTM score. Should it be relative
        'to the (absolute) score?

        Dim outToken As Integer
        Dim pept As PeptideHitStructure
        pept = getPeptideFromVisualIndex(mCurrentlySelectedPeptIdx, outToken)

        Dim oldList2 As List(Of onePTMStructure) = pept.PTMs2

        Trace.Assert(Not oldList2 Is Nothing, _
          "PIL ASSERT. pept.PTMs2 is Nothing...")

        Dim oldPTM As onePTMStructure = oldList2(0) 'Assume only one kind of PTM...

        Dim bestScore As Double = -1.0E+25

        Dim lastIndex As Integer = oldPTM.combinations2.Count - 1
        If True Then
            Dim j As Integer
            For j = 0 To lastIndex Step 1
                Dim someComb As onePTMcombinationStructure = _
                  oldPTM.combinations2(j)

                Dim score As Double = someComb.score
                If score > bestScore Then
                    bestScore = score
                End If

                'We do not have to look at someComb.positions
            Next j
        End If

        If True Then
            'One more iteration. If we only wanted to set one to true we
            'could have saved the index for the best scoring above, but there
            'can be more than one (identical highest scores).

            Dim j As Integer
            For j = 0 To lastIndex Step 1
                Dim someComb As onePTMcombinationStructure = _
                  oldPTM.combinations2(j)

                Dim score As Double = someComb.score

                Dim scoreDiff As Double = bestScore - score
                If scoreDiff < aScoreTolerance Then
                    someComb.checked7 = True
                    oldPTM.combinations2(j) = someComb 'Write-back.
                End If
            Next j
        End If

        oldList2(0) = oldPTM
        pept.PTMs2 = oldList2

        'Some asserts here...

        mProt.peptides.updatePeptideByToken(outToken, pept)

        'We must also update this:
        mLastPeptHit = pept
    End Sub 'checkForHighestPTMscore


    'Changed PM_PHOSPHO_SCORING_USERSEL 2005-12-22
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub addPTMcombinationsToGUI(ByRef aPTMversionMarker As String)


        'Changed PM_MS3_CRASH 2007-05-15
        mCurrentComb = Nothing 'We have to reset as mCurrentComb may
        '  not be updated. E.g. if all PTM combinations are below
        '  the display threshold. Or no combination is selected.


        Dim AAsequence As String = Nothing 'Keep compiler happy.
        Dim onePTM As onePTMStructure = Me.getOnePTM(AAsequence)

        If onePTM.combinations2 Is Nothing Then
            'Nothing to do..
            Dim peter23 As Integer = 23
        Else
            Dim bufSB As StringBuilder = New StringBuilder
            Dim chkYdiff As Integer = 24
            Dim cbPrefix As String = "_PTM_CB_"

            PTMscorer.sortCombinationsByScoreUsingIndex( _
              onePTM.combinations2, mSortedPTMIndices2)

            'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-03
            clearPTMscoreSelected()

            'Changed PM_PHOSPHO_SCORING 2006-01-09
            Dim miscSetttings As miscSettingsStructure2Struct = _
              mApplication.getMiscSettings()
            Dim maxItemsToDisplay As Integer = _
              miscSetttings.maxDisplayedPTMcombinations2
            Dim minimumScore As Double = miscSetttings.PTMminimumScore3

            'Changed PM_MOD_PREFIX_AND_POSTFIX 2006-06-07
            Dim quantitationModesObject As QuantitationModes_moreGeneral = _
              mApplication.getQuantModes()

            Dim lastIndex As Integer = onePTM.combinations2.Count - 1

            'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-05
            mPTMcombinationsCycler = New SDUPcycler(0, lastIndex) 'For now: one
            '  creation per peptide...

            Dim lowestScore As Double = +1.0E+30
            Dim highestScore As Double = -1.0E+30
            Dim consideredScores As Integer = 0
            If True Then
                Dim j As Integer
                For j = 0 To lastIndex

                    Dim rNum As Integer = j + 1

                    'Changed PM_PHOSPHO_SCORING 2006-01-09
                    Dim topN As Boolean = rNum <= maxItemsToDisplay
                    If topN Then
                        Dim index As Integer = mSortedPTMIndices2(j)
                        Dim someComb As onePTMcombinationStructure = _
                          onePTM.combinations2(index)

                        'Changed PM_PHOSPHO_SCORING 2006-01-09
                        'Note: this will only work properly with the rest of
                        '      the program if scores are sorted (and are
                        '      descending).
                        Dim scoreIsHigh As Boolean = _
                          someComb.score >= minimumScore

                        If scoreIsHigh Then
                            Dim score As Double = someComb.score
                            bufSB.Length = 0
                            bufSB.Append(rNum)

                            'Changed PM_BROADER_PTMSCORE 2007-04-04
                            bufSB.Append(aPTMversionMarker)

                            bufSB.Append(" ")
                            bufSB.Append(score.ToString("0.0"))
                            bufSB.Append(" ")
                            PTMscorer.formatOneCombination( _
                              AAsequence, someComb.positions2, _
                              quantitationModesObject, bufSB)

                            Dim combStr As String = bufSB.ToString

                            If True Then
                                'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-03
                                clbPTMcombinations.Items.Add( _
                                  combStr, someComb.checked7)
                            End If

                            If True Then 'Update score range.
                                If score < lowestScore Then
                                    lowestScore = score
                                End If
                                If score > highestScore Then
                                    highestScore = score
                                End If
                            End If
                        Else
                            'Score not high enough..
                            Dim peter20 As Integer = 20
                        End If
                    Else
                        'Not displayed...
                        Dim peter7 As Integer = 7
                    End If

                    'yLoc += chkYdiff
                    consideredScores += 1
                Next j
            End If

            'Display score range
            If True Then
                Dim modCount As Integer = -9999
                If Not mPTMscorer Is Nothing Then
                    modCount = mPTMscorer.getModificationCount()
                Else
                    Dim peter9 As Integer = 9
                End If

                bufSB.Length = 0

                bufSB.Append("Scores, ")
                bufSB.Append(consideredScores)
                bufSB.Append(" combinations for ")
                bufSB.Append(modCount)

                bufSB.Append(" modified: [")
                bufSB.Append(lowestScore.ToString("0.000"))
                bufSB.Append(" ; ")
                bufSB.Append(highestScore.ToString("0.000"))
                bufSB.Append(" ]")
                Dim PTMstr As String = bufSB.ToString
                StatusBarPanelPTM.Text = PTMstr
            End If
        End If

        'Refresh() is NOT necessary, but this function must be called after
        'any clearing of clbPTMcombinations and StatusBarPanelPTM....
    End Sub 'addPTMcombinationsToGUI


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub doPTMscoring2( _
      ByVal anAutoComputeCheckedSet As Boolean)

        'New PTM scoring. We can handle that more than one modification acts
        'on the same amino acid(s).

        'Changed PM_BROADER_PTMSCORE 2007-04-04
        mPTMversionMarker = "sl" 'Store it for use by formatting functions.

        'Lazy instantiation....
        Dim quantitationModesObject As QuantitationModes_moreGeneral = _
          mApplication.getQuantModes()
        If mPTMscorer Is Nothing Then
            mPTMscorer = New PTMscorer( _
              quantitationModesObject, mOptions.quantModeCode)
        End If

        Dim curSpectrumClassification As SpectrumClassificationStructure = _
          mRawDataFileHandling.getCurSpectrumClassification()
        Dim isMS3spectrum As Boolean = _
          curSpectrumClassification.spectrumSubType2 = _
          spectrumSubTypeEnum.enumIsFragmentMS3

        'Changed PM_LIMIT_PTMCOMBINATIONS 2008-01-15
        Dim maxCombinations As Double
        If True Then
            Dim miscSetttings As miscSettingsStructure2Struct = _
              mApplication.getMiscSettings()
            maxCombinations = miscSetttings.maxCombinations
        End If

        Dim PTMcombinations As Integer
        Dim OKtoScore As Boolean = mPTMscorer.setPeptideAndModifications( _
          mLastPeptHit.AASequence, _
          mLastPeptHit.modHits2, maxCombinations, _
          isMS3spectrum, PTMcombinations)

        'Changed PM_REOPEN_PROTVAL_PTMSCORE 2007-04-19

        '  anAutoComputeCheckedSet is true when PTM score is initially computed
        '  and false when an already PTM scored peptide is opened.

        Me.PTMpostCombinationsHandling( _
          OKtoScore, quantitationModesObject, mPTMversionMarker, _
          anAutoComputeCheckedSet, PTMcombinations)
    End Sub 'doPTMscoring2


    'Changed PM_REFACTOR 2007-03-30
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub PTMpostCombinationsHandling( _
      ByVal anOKtoScore As Boolean, _
      ByRef anInQuantitationModesObject As QuantitationModes_moreGeneral, _
      ByRef anInPTMversionMarker As String, _
      ByVal anAutoComputeCheckedSet As Boolean, _
      ByVal anInExpectedCombinations As Integer)

        'Changed PM_REOPEN_PROTVAL_PTMSCORE 2007-04-19
        'New: anAutoComputeCheckedSet.

        If anOKtoScore Then
            'Changed PM_MARKER_PTM 2007-03-16
            'Later: refactor the stuff below into common functions
            '       in this class and into the PTMscorer class.

            mPTMscorer.resetReadCombinations()

            'Note: mLastPeptHit is still dependent on the visual thingy.
            Dim maxIntPeakLst() As Integer = Nothing 'Keep compiler happy.

            'Changed PM_TYPESAFE 2006-11-01
            'Dim effectiveDatapoints As ArrayList = Nothing 'Keep compiler happy.
            Dim peaklist As List(Of LCPeakInfoStructure) = _
              Nothing 'Keep compiler happy.

            Dim smartPickingLevel As Integer = 9 'Overridden just below.
            Dim mannReductionLevel As Integer = 4 'Overridden just below.

            smartPickingLevel = 20 'Also overridden... Is that OK?? 
            smartPickingLevel = mReductionParameters2.smartPickingLevel3
            mannReductionLevel = mReductionParameters2.MannReductionLevel2

            'Changed PM_USERSET_MS3_MATCHING_TOLERANCE 2007-07-13
            Dim massSegmentSize As Double = _
              mReductionParameters2.smartPickingMassWindow
            Dim massTol As Double = mReductionParameters2.matchingMassTolerance

            If True Then
                Dim fullSignal As _
                  List(Of massSpectrometryBase.signalStructure) = _
                    Nothing 'Keep compiler happy.

                Dim lowestX As Double
                Dim highestX As Double
                Dim fullDataPointsInfo As dataPointsInfoStructure2
                mRawDataFileHandling.datapointsCONV( _
                  mLastPeptHit.rawFileID, fullSignal, fullDataPointsInfo, _
                  lowestX, highestX)

                BSignal.reducePeakList2( _
                  fullSignal, maxIntPeakLst, _
                  peaklist, _
                  smartPickingLevel, _
                  massSegmentSize, _
                  mannReductionLevel, _
                  massTol)
            End If

            Dim modificationsList As _
              List(Of List(Of AAsetStruct)) = _
                anInQuantitationModesObject.constructSimpleModificationList( _
                  mCurrSelPept.modHits2)

            'To accomodate MS3 refactoring. Perhaps matchedFragment is
            'a misnomer.
            Dim matchedFragment As fragmentExStructure
            matchedFragment.charge = 1
            matchedFragment.descStr = "xyz"
            matchedFragment.ionMatched = True
            matchedFragment.ionType = ionTypeEnum.enumPrecursorIon2
            matchedFragment.MCRcalcLoc = 9999.9
            matchedFragment.seq = "XYZ"

            'Is this the right way to do it?
            Dim spectrumInfo As specStruct = _
              mSpectrumTree.getCurrentSpectrumInfo()

            Dim someMatch As MS3matchStructure

            'Changed PM_PTMSCORE_TROUBLE 2008-05-22
            'someMatch.extraScoreByMS3 = -9999.9 'Required by client;
            ''  initially low value.
            someMatch.extraScoreByMS3 = -7777.7 'Required by client;

            'What other fields should be set in someMatch?
            someMatch.definedCode = 997

            someMatch.explainString = Nothing 'Keep compiler happy.
            someMatch.matchedFragmentForBestMSscore.descStr = _
              Nothing 'Keep compiler happy.
            someMatch.matchedFragmentForBestMSscore.seq = _
              Nothing 'Keep compiler happy.

            'Changed PM_REFACTOR 2006-10-12
            'Dim dummySignal As ArrayList = New ArrayList
            Dim dummySignal As _
              List(Of massSpectrometryBase.signalStructure) = _
                New List(Of massSpectrometryBase.signalStructure)

            Dim combCount As Integer = 0
            Dim combNumberForBest As Integer = 0

            'Changed PM_PTMSCORE_MEMORY_EFFICIENCY 2007-08-03. Does not
            '  seem to be used.
            ''Dim scoreStr2 As String = ""
            'Dim scoreStr2SB As StringBuilder = New StringBuilder(200)

            Dim firstTime As Boolean = True

            Dim bestComb As ionSetStruct 'We need to keep track of this...
            bestComb.backwardIonDiffs = Nothing 'Keep compiler happy.
            bestComb.forwardIonDiffs = Nothing 'Keep compiler happy.

            'Changed PM_PTMSCORE_MEMORY_EFFICIENCY 2007-08-03
            'Dim allCombs As ArrayList = New ArrayList
            Dim allCombs2 As List(Of ionSetStruct) = _
              New List(Of ionSetStruct)

            If True Then
                If True Then
                    Dim msg As String = _
                      "Prepare for " & anInExpectedCombinations & _
                      "combinations ..."
                    StatusBarPanelPTM.Text = msg
                    staSpectrumInfoEtc.Refresh() 'StatusBarPanelPTM is a
                    '  panel in here.

                    Application.DoEvents() 'How do we force immediate display?
                End If

                Dim timeSliceSecs As Double = 2.0
                'timeSliceSecs = 10.0
                Dim chunkerPTMscore As SDUPchunker = _
                  New SDUPchunker(timeSliceSecs)

                chunkerPTMscore.Init(0, 999999999, True)

                Dim someComb As ionSetStruct
                someComb.backwardIonDiffs = Nothing 'Keep compiler happy.
                someComb.forwardIonDiffs = Nothing 'Keep compiler happy.

                Dim done As Boolean = False
                While Not chunkerPTMscore.jobFinished() AndAlso _
                      Not done

                    'Note: we must check done below because we do not 
                    '      know beforehand when we are done.
                    While Not chunkerPTMscore.timeIsUp() AndAlso _
                          Not done

                        'We don't the number, but currentNumber() must be called.
                        Dim i As Integer = _
                          chunkerPTMscore.currentNumber()

                        Dim res As Boolean = _
                          mPTMscorer.readNextCombination(someComb)
                        done = Not res

                        If Not done Then
                            If firstTime Then
                                firstTime = False
                            Else
                                'Changed PM_PTMSCORE_MEMORY_EFFICIENCY 2007-08-03. 
                                '  Does not seem to be used.
                                ''scoreStr &= ", "
                                'scoreStr2SB.Append(", ")
                            End If

                            Dim prevScore As Double = someMatch.extraScoreByMS3
                            Dim curScore As Double

                            'Note: currently we don't reset mWorkingFragments 
                            '  if it points to the same instance as 
                            '  mMSMSFragments. It means that the best scoring 
                            '  is **not** in mMSMSFragments after we are
                            '  done in this loop.

                            'Real problem with 3rd last parameter and 5th last
                            'parameter: item type is different depending on 
                            'wether called from PTM scoring or MS3 scoring!
                            '
                            'PTM scoring passes data points, but ignores
                            'returned ones.
                            '
                            'MS3 scoring passes Nothing, but return list is
                            'assigned to mMS3signalForBestScore. This was used 
                            'for reducing the datapoints in 
                            'mMS3signalForBestScore and dumping corresponding 
                            'reduced peak to Export.
                            '  Down in getDataMatchAndScore() 

                            'Possible resolution:
                            '  1. do not return raw datapoints.

                            'Changed PM_BAD_QSTARSPECTRUM_FOR_PTMSCORING 2007-09-14
                            Dim experimentNumber As Integer = _
                              mLastPeptHit.experimentNumber

                            MS3scoring.getDataMatchAndScore3( _
                              mMSMSFragments, _
                              mWorkingFragments, _
                              mLastPeptHit.AASequence, _
                              mLastPeptHit.charge, _
                              mLastPeptHit.AASequence, _
                              mLastPeptHit.charge, _
                              modificationsList, _
                              "currPeptMod", _
                              someComb, _
                              False, _
                              matchedFragment, _
                              spectrumInfo.specNumb, _
                              mRawDataFileHandling, _
                              mLastPeptHit.rawFileID, _
                              smartPickingLevel, _
                              massSegmentSize, _
                              mannReductionLevel, _
                              massTol, _
                              someMatch, _
                              dummySignal, _
                              curScore, _
                              peaklist, _
                              maxIntPeakLst, _
                              mLastPeptHit.modHits2, _
                              experimentNumber _
                              )

                            'Assumption about the functions behavior/return
                            'values.
                            Trace.Assert(dummySignal Is Nothing, _
                              "PIL ASSERT. dummySignal is different from Nothing.")

                            mPTMscorer.setScoreForCurrent(curScore)

                            someComb.score = curScore 'This is not done
                            '  automatically. It probably should....

                            'Changed PM_PTMSCORE_MEMORY_EFFICIENCY 2007-08-03. Does
                            '  not seem to be used.
                            ''scoreStr &= curScore.ToString("0.0")
                            'scoreStr2SB.Append(curScore.ToString("0.0"))

                            combCount += 1

                            'For now: client side detection of best scoring
                            If someMatch.extraScoreByMS3 > prevScore Then
                                bestComb = someComb
                                combNumberForBest = combCount 'Note: is 
                                '  one-based index because we assign after 
                                '  combCount has been updated.
                            End If

                            allCombs2.Add(someComb)
                        End If 'Not done

                    End While 'Time-is-up loop...

                    If True Then 'Time for GUI update...
                        Application.DoEvents()

                        Dim msg As String = _
                          combCount.ToString() & " combinations"
                        StatusBarPanelPTM.Text = msg
                    End If
                End While

                'While mPTMscorer.readNextCombination(someComb)
                'End While
            End If

            Dim PTMscore As Double = someMatch.extraScoreByMS3

            'Changed PM_REOPEN_PROTVAL_PTMSCORE 2007-04-19
            If anAutoComputeCheckedSet Then

                'Now inside this if block... Will not be called when
                'a peptide is reopened (to preserve the user's changes)

                If True Then 'Put the PTM information into the current peptide.
                    Me.resetOnePTM()

                    Dim lastIndex As Integer = allCombs2.Count() - 1
                    Dim j As Integer
                    For j = 0 To lastIndex Step 1

                        'This is not very efficient. There will be a lot
                        'of memory garbage by adding each combination
                        'at a time.
                        Me.updatePTMscoreInDataStructures( _
                          PTMscore, allCombs2(j), mPTMscorer)
                    Next j

                    'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-05. Now: keep
                    '  same order as in mPTMscorer. This is needed when
                    '  the user selects combinations - only mPTMscorer has
                    '  the information to display the proper fragment
                    '  masses (and thereby matching fragments).
                End If

                If True Then
                    'Fix-up. Initially select one or more combinations with
                    '  the highest score.
                    Dim miscSetttings As miscSettingsStructure2Struct = _
                      mApplication.getMiscSettings()
                    Dim minimumDeltaScore As Double = _
                      miscSetttings.minimumPTMdeltaScore

                    Me.checkForHighestPTMscore(minimumDeltaScore)
                End If
            Else
                'Reopening of peptide
                Dim peter2 As Integer = 2

            End If 'During initial PTM scoring

            Me.addPTMcombinationsToGUI(anInPTMversionMarker)

            Dim visualIndexForBest As Integer = 0
            Me.displayPTMcombination( _
              bestComb, PTMscore, visualIndexForBest)

            'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-05
            'No longer needed.
            'Dim extraInfo As String = "Best score, comb #" & _
            '  combNumberForBest & ": " & _
            '  PTMscore.ToString("0.0") & _
            '  ". Scores: " & scoreStr
            'Dim msg As String = _
            '  "From Mascot: " & phosCount & _
            '  " modifications. Combinations: " & combCount & _
            '  ". " & extraInfo
            'lblExtraInfoZZZZZ.Text = msg

            mPTMscorer.resetReadCombinations() 'Needed.
        Else
            'Not OK to score...
            'MsgBox("Could not PTM score. " & _
            '  "The peptide does not have any modifications. " & _
            '  "Use PTM scoring on a peptide that has.")
            Dim msgStr As String = _
              "Could not PTM score. " & _
              "The peptide does not have any modifications or they do " & _
              "not apply to PTM scoring or the number of combinations " & _
              "is too high (" & anInExpectedCombinations & ")."
            lblExtraInfo.BackColor = Color.Salmon
            lblExtraInfo.Text = msgStr 'Note: it cleared when a peptide
            '  is initially displayed.
        End If
    End Sub 'PTMpostCombinationsHandling


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub doPTMscoring_old(ByVal anAutoComputeCheckedSet As Boolean)

        'Is this the old score PTM score (that can no longer be accessed
        'from the user interface) ?
        '
        'Answer: yes!

        'Changed PM_MARKER_REFACTOR 2006-08-24
        'Note: we compute a lot of things in this function that does
        '      not change between calls of this function. It would be
        '      more natural and more efficient to cache the information
        '      in class QuantitationModes_moreGeneral.

        'Changed PM_BROADER_PTMSCORE 2007-04-04
        mPTMversionMarker = "old" 'Store it for use by formatting functions.

        Try
            Dim OKtoScore As Boolean = True
            If mLastPeptHit.modHits2 Is Nothing Then
                OKtoScore = False
            Else
                OKtoScore = mLastPeptHit.modHits2.Count > 0
            End If

            If OKtoScore Then
                Dim quantitationModesObject As QuantitationModes_moreGeneral = _
                  mApplication.getQuantModes()

                'Lazy instantiation....
                If mPTMscorer Is Nothing Then
                    mPTMscorer = New PTMscorer( _
                      quantitationModesObject, mOptions.quantModeCode)
                End If

                Dim PTMCount As Integer = -1 'Out here because later
                '  blocks need it.

                'Changed PM_TYPESAFE 2008-12-03
                ''Changed PM_TYPESAFE 2008-12-02
                ' ''Changed PM_GENERALISED_PTMSCORE2 2006-03-27. Mass difference
                ' ''is now a function of amino acid. E.g. this means we
                ' ''can handle partial Mox and partial/full phosphorylation at
                ' ''the same time.
                ' ''Dim basicMassDiff As Double = -10.0
                ''Dim basicMassDifferencesAndOthers As Hashtable = New Hashtable
                ''
                'Note: we could move this down to use lazy instantitation. But
                '      this function is not accessible from the user interface
                '      anymore and is likely to be phased out completely.
                Dim capacity As Integer = 2 'What is appropriate???
                Dim basicMassDifferencesAndOthers2 As _
                  Dictionary(Of String, quantModificationStructure) = _
                    New Dictionary(Of String, _
                      quantModificationStructure)(capacity)

                Dim peptideSequence As String = mLastPeptHit.AASequence

                'Changed PM_TYPESAFE 2008-12-02
                ''Changed PM_GENERALISED_PTMSCORE 2006-03-10
                'Dim seqAAcounts As Hashtable = PTMscorer.AAstats(peptideSequence)
                Dim seqAAcounts2 As Dictionary(Of String, Integer) = _
                  PTMscorer.AAstats2(peptideSequence)

                'Changed PM_PTMBUG 2006-07-03
                Dim countsFromMascot As ArrayList = New ArrayList

                'Changed PM_GENERALISED_PTMSCORE 2006-05-03

                Dim SILACmods2 As Dictionary(Of Integer, Integer) = _
                  quantitationModesObject.modificationIDsForQuantitationMode( _
                    mOptions.quantModeCode)

                'Changed PM_LOWMASS_PHOSPHO_FRAGMENTS 2006-01-06
                Dim affectedAminoAcids As String = "" 'Set below. Is peptide
                '  dependent. E.g. only "Y" if Mascot indicates the
                '  modification "pY".
                If True Then 'Going through modifications for current peptide.

                    'Changed PM_TYPESAFE 2008-12-03
                    ''Changed PM_PTM_BROKEN20060713 2006-08-24
                    ''Dim unitAAset As String = ""
                    ''Dim unitAAsetHash As Hashtable = New Hashtable
                    'Dim unitAAsetHash As Hashtable = New Hashtable
                    Dim unitAAsetHash2 As Dictionary(Of Integer, String) = _
                      New Dictionary(Of Integer, String) 'For now: one
                    '  per modification in order to have the functionality as
                    '  before.

                    'Changed PM_LOWMASS_PHOSPHO_FRAGMENTS 2006-01-06
                    If True Then 'Find unit set of affected amino acids, but
                        '  only those for PTM scoring.

                        'Changed PM_TYPESAFE 2008-12-02
                        'Dim AAhash As Hashtable = New Hashtable
                        Dim AAhash2 As Dictionary(Of String, Integer) = _
                          New Dictionary(Of String, Integer)

                        Dim someMod As modificationCountStruct

                        'First loop through the modifications.
                        For Each someMod In mLastPeptHit.modHits2

                            Dim modID As Integer = someMod.quantModificationID

                            'Changed PM_GENERALISED_PTMSCORE 2006-05-03
                            'We simply ignore the SILAC modifications
                            'Changed PM_REFACTOR 2007-03-16. No need
                            'to use TryGetValue() as this code is going
                            'to be phased out.
                            'If Not SILACmods.ContainsKey(modID) Then
                            If Not SILACmods2.ContainsKey(modID) Then
                                'Note: getModification() is stateless/Shared.
                                Dim modInfo As _
                                  quantModificationStructure = _
                                    quantitationModesObject.getModification(modID)
                                Dim countFromMascot As Integer = someMod.count3

                                'Changed PM_QUANTGENERAL_PREPARATION 2006-07-13
                                'For now we use the unit set.
                                Dim unitAAsetSB As StringBuilder = _
                                  New StringBuilder(30)

                                Dim acceptPeptide As Boolean = False
                                Dim totalCountInPeptide As Integer = 0
                                Dim phosSites As Boolean = False
                                If True Then 'First pass: find number of
                                    '  affected amino acids in the
                                    '  peptide (for the current modification).
                                    '  The decision about accepting the
                                    '  peptide for PTM scoring can also be taken.

                                    Dim someAAset As AAsetStruct

                                    'Note: this is the old PTM scoring...
                                    For Each someAAset In modInfo.affectedAAs

                                        'Changed PM_QUANTGENERAL_PREPARATION 2006-07-13
                                        unitAAsetSB.Append(someAAset.AAs)

                                        'Loop through amino acids for
                                        '  the current modification.
                                        Dim lastIndex As Integer = _
                                          someAAset.AAs.Length() - 1

                                        'One iteration for each AA in current 
                                        'modifcation. E.g. 3 for "STY".
                                        Dim j As Integer
                                        For j = 0 To lastIndex Step 1
                                            Dim oneAA As String = _
                                              someAAset.AAs.Substring(j, 1)

                                            'What if an amino acid letter appear
                                            'more than once?????

                                            Dim countInPeptide As Integer = _
                                              seqAAcounts2(oneAA)
                                            totalCountInPeptide += countInPeptide

                                            'Changed PM_MARKER 2007-03-14
                                            If totalCountInPeptide > 3 Then
                                                Dim peter3 As Integer = 3
                                            End If

                                            'If oneAA = "S" Or oneAA = "T" Or oneAA = "Y" Then
                                            '    phosSites = True
                                            'End If
                                        Next
                                    Next 'Through set, usually only one. More
                                    '  for N15.
                                End If

                                'acceptPeptide = countFromMascot < _
                                '  totalCountInPeptide
                                acceptPeptide = _
                                  countFromMascot <= totalCountInPeptide 'Always
                                '  true??

                                ''For now: also score phos sites even if all 
                                ''         sites are modified.
                                'If phosSites Then
                                '    If acceptPeptide Then
                                '        Dim peter87 As Integer = 87
                                '    Else
                                '        Dim peter88 As Integer = 88
                                '    End If
                                '    acceptPeptide = True
                                'End If

                                If acceptPeptide Then 'Second pass: do not PTM 
                                    '  score if all amino acids are 
                                    '  modified (e.g. SILAC modifications).

                                    'Changed PM_QUANTGENERAL_PREPARATION 2006-07-13
                                    Dim modAAsSB As StringBuilder = _
                                      New StringBuilder(30)

                                    'Changed PM_PTMBUG 2006-07-03
                                    Dim someModCountCheck As _
                                      modCountCheckStructure
                                    someModCountCheck.targetCount = _
                                      countFromMascot

                                    'Changed PM_PTM_BROKEN20060713 2006-08-24
                                    ''Changed PM_QUANTGENERAL_PREPARATION 2006-07-13
                                    ''someModCountCheck.modAAs = modInfo.AA
                                    'unitAAset = unitAAsetSB.ToString()
                                    'someModCountCheck.modAAs = unitAAset
                                    Dim unitAAset2 As String = _
                                      unitAAsetSB.ToString()
                                    someModCountCheck.modAAs = unitAAset2
                                    unitAAsetHash2(modID) = unitAAset2

                                    Dim lastIndex2 As Integer = _
                                      unitAAset2.Length() - 1

                                    'Is also used later, but we must reset
                                    'it here.
                                    someModCountCheck.bitVector7 = 0

                                    countsFromMascot.Add(someModCountCheck)
                                    'Key is the set of AAs.
                                    '  Can be more than one, e.g. "STY".
                                    '  However the key is not important at all,
                                    '  only the result of an AND between
                                    '  the bitvector and a (later) combination.
                                    '  The number of 1's in the result must
                                    '  match the field "targetCount".

                                    Dim j As Integer
                                    For j = 0 To lastIndex2 Step 1

                                        'Changed PM_QUANTGENERAL_PREPARATION 2006-07-13
                                        'Dim oneAA As String = _
                                        '  modInfo.AA.Substring(j, 1)
                                        Dim oneAA As String = _
                                          unitAAset2.Substring(j, 1)

                                        'Changed PM_GENERALISED_PTMSCORE 2006-03-10.
                                        'New condition: instead of some fixed set
                                        'then we will PTM score those that are not
                                        'fully modified.
                                        'Dim acceptAA As Boolean = _
                                        '  oneAA = "S" Or _
                                        '  oneAA = "T" Or _
                                        '  oneAA = "Y" Or _
                                        '  oneAA = "K" Or _
                                        '  False

                                        'Dim countInPeptide As Integer = _
                                        '  CInt(AAcounts(oneAA))
                                        'Dim acceptAA As Boolean = _
                                        '  countFromMascot < countInPeptide

                                        'Filter for AA for PTM, STY
                                        'Changed PM_GENERALISED_PTMSCORE 2006-03-09
                                        'If oneAA = "S" Or oneAA = "T" Or
                                        '   oneAA = "Y" Then

                                        'If acceptAA Then
                                        '    If AAhash.Contains(oneAA) Then
                                        '        'No need to count
                                        '        'Dim oldCount As Integer = _
                                        '        '  CInt(toReturn(AA))
                                        '        'toReturn(AA) = oldCount + 1
                                        '        Dim peter9 As Integer = 9
                                        '    Else
                                        '        AAhash.Add(oneAA, 1)
                                        '    End If
                                        'Else
                                        '    Dim peter2 As Integer = 2
                                        'End If

                                        If AAhash2.ContainsKey(oneAA) Then
                                            'No need to count
                                            'Dim oldCount As Integer = _
                                            '  CInt(toReturn(AA))
                                            'toReturn(AA) = oldCount + 1
                                            Dim peter9 As Integer = 9
                                        Else
                                            AAhash2.Add(oneAA, 1)
                                        End If
                                    Next j
                                End If 'Peptide accepted.
                            Else
                                Dim peter2 As Integer = 2 'SILAC mod! Do 
                                '  ***not*** include in AAhash (that is created
                                '  below and used later).
                            End If
                        Next 'First loop through the modifications.

                        If True Then 'Find unit set.
                            Dim AAsb As StringBuilder = New StringBuilder

                            'Dim hashEnumerator As IDictionaryEnumerator = _
                            '  AAhash.GetEnumerator()
                            Dim hashEnumerator2 As Dictionary( _
                              Of String, Integer).Enumerator = _
                                AAhash2.GetEnumerator()

                            While hashEnumerator2.MoveNext()

                                'Changed PM_TYPESAFE 2008-12-02. Replaced...
                                Dim someAA As String = _
                                  hashEnumerator2.Current.Key

                                AAsb.Append(someAA)
                            End While
                            affectedAminoAcids = AAsb.ToString
                        End If
                    End If 'Block, find unit set of affected amino acids.

                    'Current assumptions/limitations:
                    '  1. Only look for phosphorylations
                    '  2. S, T and Y are assumed to be phosphorylated.

                    If True Then
                        PTMCount = 0

                        'basicMassDiff = 0.0 'Need to set it as there may not 
                        ''  be any modifications.

                        Dim someMod As modificationCountStruct

                        'Second loop through the modifications.
                        For Each someMod In mLastPeptHit.modHits2

                            Dim modID As Integer = someMod.quantModificationID

                            'Changed PM_LOWMASS_PHOSPHO_FRAGMENTS 2006-01-06
                            'If modInfo.AA.IndexOf("S") >= 0 Or _
                            '   modInfo.AA.IndexOf("T") >= 0 Or _
                            '   modInfo.AA.IndexOf("Y") >= 0 Then
                            '    phosCount += modCount
                            'End If

                            'Changed PM_REFACTOR 2007-03-16. No need to
                            'use TryGetValue() as this code is going
                            'to be phased out.
                            'If Not SILACmods.ContainsKey(modID) Then
                            If Not SILACmods2.ContainsKey(modID) Then
                                'Note: getModification() is stateless/Shared.
                                Dim modInfo As _
                                  quantModificationStructure = _
                                    quantitationModesObject.getModification(modID)

                                Dim modCount As Integer = someMod.count3

                                'Dim massDiff As Double = modInfo.massDiffFromBase

                                'Changed PM_MARKER 2006-06-28
                                'asdasdad() 'Some checking that the mod count
                                '  for a particular mod is fullfilled for a
                                '  particular combination.

                                Dim increaseSites As Boolean = False
                                Dim lastIndex As Integer = _
                                  affectedAminoAcids.Length() - 1
                                Dim j As Integer
                                For j = 0 To lastIndex
                                    Dim oneAA As String = _
                                      affectedAminoAcids.Substring(j, 1)

                                    'Changed PM_QUANTGENERAL_PREPARATION 2006-07-13

                                    'Why is this inside the loop??
                                    Dim unitAAset3 As String = _
                                      unitAAsetHash2(modID)

                                    'If modInfo.AA.IndexOf(oneAA) >= 0 Then
                                    'If unitAAset.IndexOf(oneAA) >= 0 Then
                                    If unitAAset3.IndexOf(oneAA) >= 0 Then 'Always true??

                                        'Changed PM_MARKER_PTM 2007-03-15
                                        increaseSites = True

                                        If Not basicMassDifferencesAndOthers2.ContainsKey( _
                                          oneAA) Then

                                            'Changed PM_MARKER_PTM 2007-03-15
                                            'increaseSites = True

                                            'Changed PM_MOD_PREFIX_AND_POSTFIX 2006-06-07
                                            '  Carry on the whole thing now. Should
                                            '  not be a killer, even with the strings
                                            '  in the structure.
                                            'basicMassDifferencesAndOthers.Add( _
                                            '  oneAA, modInfo.massDiffFromBase)
                                            basicMassDifferencesAndOthers2.Add( _
                                              oneAA, modInfo)
                                        Else
                                            'There is already a mass difference for
                                            'the current AA....
                                            Dim peter2 As Integer = 2
                                        End If
                                    End If
                                Next j

                                If increaseSites Then
                                    PTMCount += modCount

                                    ''Take the first mass diff (that affects ... ????).
                                    ''
                                    ''Or: prefer phosphorylation over other 
                                    ''    in other to keep same behavior
                                    ''    as older versions??
                                    'If basicMassDiff <= 0.001 Then
                                    '    basicMassDiff = massDiff
                                    'Else
                                    '    Dim peter2 As Integer = 2
                                    'End If
                                End If
                            Else
                                Dim peter2 As Integer = 2 'SILAC mod!
                            End If
                        Next 'Second loop through the modifications.

                    End If
                End If 'Block, going through modifications for current peptide.

                'Changed PM_GENERALISED_PTMSCORE 2006-03-10
                Trace.Assert(PTMCount >= 0, _
                  "PIL ASSERT. PTMCount is undefined: ." & PTMCount)

                'Trace.Assert(basicMassDifferences.Count > 0, _
                '  "PIL ASSERT. No mass differences...")

                Dim neutralLosses As Integer = 0

                Dim curSpectrumClassification As SpectrumClassificationStructure = _
                  mRawDataFileHandling.getCurSpectrumClassification()
                If curSpectrumClassification.spectrumSubType2 = _
                   spectrumSubTypeEnum.enumIsFragmentMS3 Then 'Assumes MS3 is
                    'neutral loss experiment...

                    If PTMCount > 0 Then
                        neutralLosses = 1  'We assume 1 for now. Should be based on
                        '  the precursor mass difference and the charge.

                        ''With neutral loss there are fewer phospho sites available for
                        ''fragmentation than indicated by Mastcot. No!
                        'phosCount -= neutralLosses 'No reduction. Phospho's have
                        'the -18 Da evidence (instead of +80 Da)
                    Else
                        Dim peter8 As Integer = 8
                    End If
                End If

                If affectedAminoAcids.Length = 0 Then
                    OKtoScore = False
                End If

                If OKtoScore Then
                    mPTMscorer.setPeptide_old( _
                      peptideSequence, affectedAminoAcids, _
                      PTMCount, neutralLosses, _
                      basicMassDifferencesAndOthers2, _
                      countsFromMascot)

                    'Changed PM_REFACTOR 2007-03-30
                    Me.PTMpostCombinationsHandling( _
                      OKtoScore, quantitationModesObject, mPTMversionMarker, _
                      anAutoComputeCheckedSet, 9999)
                End If
            Else
                Dim peter7 As Integer = 7
            End If 'Checks before doing the scoring

        Catch exceptionObject As Exception
            AppCommon2.displayStandardExceptionInfo( _
              exceptionObject, _
              "") 'Empty string for now
            Exit Sub
        End Try
    End Sub 'doPTMscoring_old()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub displayPTMcombination( _
      ByRef anInComb As ionSetStruct, _
      ByVal aScore As Double, ByVal aVisualIndex As Integer)

        Trace.Assert(aVisualIndex >= 0, _
          "PIL ASSERT. aVisualIndex is undefined. Value: " & aVisualIndex & ".")

        Try
            Dim index As Integer = mSortedPTMIndices2(aVisualIndex)

            Dim quantitationModesObject As QuantitationModes_moreGeneral = _
              mApplication.getQuantModes()
            Dim modificationsList As _
              List(Of List(Of AAsetStruct)) = _
                quantitationModesObject.constructSimpleModificationList( _
                  mLastPeptHit.modHits2)

            Dim oldZoom As massZoomStructure = mMSMSdisplay.getZoomRange()

            'Changed PM_REFACTOR 2007-09-19. Old. Delete at any time.
            ' 'Changed PM_PTM_FOR_ALL 2007-06-21
            ' 'To be implemented later: maintain zoom for QSTAR/Analyst...
            ' '
            ' 'Maintain zoom...
            ' 'Trace.Assert(Not mFinneganMSMS Is Nothing, _
            ' '   "PIL ASSERT. mFinneganMSMS is nothing....")
            ' 'Dim oldZoom As massZoomStructure = mFinneganMSMS.getZoomRange()
            ' Select Case mOptions.rawFileMode
            '     Case rawFileModeEnum.enumAnalyst
            '         Dim peter2 As Integer = 2
            ' 
            '     Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
            '         oldZoom = mFinneganMSMS.getZoomRange()
            '     Case Else
            '         Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
            ' End Select

            'Changed PM_AUTOMATCH_FRAGMENTS 2005-08-17
            'Me.displayBAndYions( _
            '  mLastPeptHit.AASequence, True, mLastPeptHit.charge, _
            '  mLastPeptHit.rawFileID, modificationsList, _
            '  mMSMSFragments, anInComb)
            Me.displayIonsAndHighlightMatched( _
              mLastPeptHit.AASequence, mLastPeptHit.charge, mLastPeptHit.rawFileID, _
              mMSMSFragments, anInComb, _
              mLastMSMSSignal, mLastMSMSSignalInfo _
              )

            mMSMSdisplay.setZoomRange2(oldZoom)
            mMSMSdisplay.refresh2()

            'Changed PM_REFACTOR 2007-09-19. Old. Delete at any time.
            ' 'Changed PM_PTM_FOR_ALL 2007-06-21
            ' 'To be implemented later: maintain zoom for QSTAR/Analyst...
            ' '
            ' 'Trace.Assert(Not mFinneganMSMS Is Nothing, _
            ' '   "PIL ASSERT. mFinneganMSMS is nothing....")
            ' 'mFinneganMSMS.setZoomRange2(oldZoom)
            ' 'mFinneganMSMS.refresh2()
            ' Select Case mOptions.rawFileMode
            '     Case rawFileModeEnum.enumAnalyst
            '         Dim peter2 As Integer = 2
            ' 
            '     Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
            '         mFinneganMSMS.setZoomRange2(oldZoom)
            '         mFinneganMSMS.refresh2()
            '     Case Else
            '         Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
            ' End Select


            'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-05
            Dim curPepWithMod As String = Nothing 'Keep compiler happy.

            If True Then
                'Dim curPepWithMod As String = mPTMscorer.reportStrForCurrent()

                Dim AAsequence As String = Nothing 'Keep compiler happy.
                Dim onePTM As onePTMStructure = Me.getOnePTM(AAsequence)

                If Not onePTM.combinations2 Is Nothing Then
                    Dim someComb As onePTMcombinationStructure = _
                      onePTM.combinations2(index)
                    Dim bufSB As StringBuilder = New StringBuilder

                    PTMscorer.formatOneCombination( _
                      AAsequence, someComb.positions2, _
                      quantitationModesObject, bufSB)
                    curPepWithMod = bufSB.ToString

                    'Changed PM_PTMSCORE_FAILURE 2006-03-08. Failed here....
                    'clbPTMcombinations.SelectedIndex = aVisualIndex
                    Dim displayedPTMcombinations As Integer = _
                      clbPTMcombinations.Items.Count
                    If aVisualIndex < displayedPTMcombinations Then
                        clbPTMcombinations.SelectedIndex = aVisualIndex
                    Else
                        'This can happen if no PTM combination is above
                        'the minimum score. We expect displayedPTMcombinations
                        'to be zero....
                        Dim peter2 As Integer = 2
                    End If
                Else
                    Trace.Assert(False, "PIL ASSERT. This should never happen...")
                End If
            End If

            Dim msg As String = _
              "PTM position: " & curPepWithMod

            'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-05
            ''May not be true in the future...
            'Dim combinationNumber As Integer = anInComb.ID
            'Dim msg2 As String = _
            '  "Combination #" & combinationNumber & "."
            'lblExtraInfo.Text = msg & ". " & msg2
            lblExtraInfo.Text = msg

            'Changed PM_PHOSPHO_SCORING 2005-09-08
            Dim rowToUpdate As ListViewItem = lsvPeptides.SelectedItems(0)
            mColumnMapper.updateListItem( _
              rowToUpdate, _
              peptideColEnum2.enumScoreWithPTM, _
              aScore.ToString("F1"))

            'Later: refactor these 3 lines.
            'Changed PM_PHOSPHO_SCORING_DISPLAY 2005-10-19
            Dim PTMinfoSB As StringBuilder = New StringBuilder
            Dim highestPTMscore As Double
            PTMscorer.formatSomeCombinations( _
              mLastPeptHit.AASequence, mLastPeptHit.PTMs2, True, _
              quantitationModesObject, _
              PTMinfoSB, _
              highestPTMscore)
            mColumnMapper.updateListItem( _
              rowToUpdate, peptideColEnum2.enumPTMinfo, _
              PTMinfoSB.ToString)

        Catch exceptionObject As Exception
            AppCommon2.displayStandardExceptionInfo( _
              exceptionObject, _
              "In displayPTMcombination(): " & _
              " could not display PTM combination for peptide " & _
              mLastPeptHit.AASequence & _
              ", q" & mLastPeptHit.queryNumber & ".....")
            Exit Sub
        End Try

    End Sub 'displayPTMcombination


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function checkScorer() As Boolean
        Dim toReturn As Boolean = True
        If mPTMscorer Is Nothing Then
            toReturn = False
            MsgBox("Could not go the next. PTM most be scored first. Choose menu Protein;Peptide/Score PTM.")
        End If
        Return toReturn
    End Function 'checkScorer


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuNextPTMposition_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuNextPTMposition.Click

        Try
            'Changed PM_PTM_FOR_ALL 2007-08-08
            'If quantApplication.isFinnegan(mOptions.rawFileMode) Then
            'End If

            If checkScorer() Then
                'New way. Note: no data structure update.
                mPTMcombinationsCycler.stepForward()
                Me.updatePTM_GUIdisplay()
            End If

        Catch exceptionObject As Exception
            Dim errMsg1 As String = "Error: " & exceptionObject.ToString & ControlChars.NewLine
            Dim errMsg2 As String = _
              "Message: " & exceptionObject.Message & ControlChars.NewLine
            Dim errMsg3 As String = ""
            If Not exceptionObject.InnerException Is Nothing Then
                errMsg3 = _
                    "Extra info: " & exceptionObject.InnerException.Message & ControlChars.NewLine
            End If
            Dim errMsg As String = errMsg1 & errMsg2 & errMsg3
            MsgBox(errMsg)
            Exit Sub
        End Try
    End Sub 'mnuNextPTMposition_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuPrevPTMposition_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuPrevPTMposition.Click

        Try
            'Changed PM_PTM_FOR_ALL 2007-08-08
            'If quantApplication.isFinnegan(mOptions.rawFileMode) Then
            'End If

            If checkScorer() Then
                'New way. Note: no data structure update.
                mPTMcombinationsCycler.stepBackward()
                Me.updatePTM_GUIdisplay()
            End If

        Catch exceptionObject As Exception
            Dim errMsg1 As String = _
              "Error: " & exceptionObject.ToString & ControlChars.NewLine
            Dim errMsg2 As String = _
              "Message: " & exceptionObject.Message & ControlChars.NewLine
            Dim errMsg3 As String = ""
            If Not exceptionObject.InnerException Is Nothing Then
                errMsg3 = _
                    "Extra info: " & exceptionObject.InnerException.Message & _
                    ControlChars.NewLine
            End If
            Dim errMsg As String = errMsg1 & errMsg2 & errMsg3
            MsgBox(errMsg)
            Exit Sub
        End Try
    End Sub 'mnuPrevPTMposition_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSetPTMparameters_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuSetPTMparameters.Click

        Dim PTMparametersForm As New frmSpectrumReductionParameters( _
          mReductionParameters2, Me)
        PTMparametersForm.Show()
    End Sub 'mnuSetPTMparameters_Click


    'Changed PM_MANNREDUCTION_LEVEL 2005-09-05
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub setReductionParameters2( _
      ByVal aReductionParameters As reductionParametersStructure)

        mReductionParameters2 = aReductionParameters
    End Sub 'setReductionParameters()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Function buildTokenListForAllPeptides() _
      As List(Of visibleIndexStruct)

        'Changed PM_REFACTOR 2008-04-30
        'Old return value:
        '  As Integer()

        '  ByRef anInPeptideIDs As List(Of visibleAndPeptideTableIndexStruct), _

        'Prepare for scoring, etc. in raw file order.
        Dim len As Integer = lsvPeptides.Items.Count
        Dim lastIndex As Integer = len - 1

        'Changed PM_REFACTOR 2008-04-30
        'Dim toReturn() As Integer
        'ReDim toReturn(lastIndex)
        Dim toReturn As List(Of visibleIndexStruct) = _
          New List(Of visibleIndexStruct)(len)

        Dim i As Integer
        For i = 0 To lastIndex
            Dim token As Integer = Me.getPeptideTokenFromVisualIndex(i)

            'Changed PM_REFACTOR 2008-04-30
            'toReturn(i) = token
            Dim someItem As visibleIndexStruct
            someItem.visualIdx2 = i
            someItem.token3 = token

            someItem.fileID2 = -1 'For this purpose.
            someItem.spectrumNumber = -1 'For this purpose.

            toReturn.Add(someItem)
        Next
        Return toReturn
    End Function 'buildTokenListForAllPeptides()


    'Changed PM_MS3INTEGRATION 2004-06-03
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Function doUnattentedMS3scoring( _
      Optional ByVal aNewInstance As Boolean = True) _
      As Boolean

        Dim toReturn As Boolean = False

        Dim peptideTokens As List(Of visibleIndexStruct) = _
          Me.buildTokenListForAllPeptides()

        'For performance..
        Dim lastIndex As Integer = peptideTokens.Count() - 1

        'Changed PM_REFACTOR 2008-09-25. No need to preallocate, it happens
        '  in findOrderByRawFile().
        'Dim MS3ScoringOrderIndexes(lastIndex) As visibleIndexStruct
        Dim MS3ScoringOrderIndexes2 As List(Of visibleIndexStruct) = _
          Nothing 'Keep compiler happy.

        quantApplication.findOrderByRawFile( _
          peptideTokens, mProt, MS3ScoringOrderIndexes2)

        'Later: set up chunker, etc.
        Dim i As Integer
        For i = 0 To lastIndex
            Dim curIndexes As visibleIndexStruct = MS3ScoringOrderIndexes2(i)

            Dim peptToken As Integer = curIndexes.token3
            Dim visibleIndex As Integer = curIndexes.visualIdx2

            'Changed PM_MS3INTEGRATION 2004-06-15
            'Note: this check should no longer be necessary as we use filters.
            If peptToken >= 0 Then 'Ignore ZZZZ peptides...
                lsvPeptides.Items(visibleIndex).Selected = True 'We need this to
                '  be selected and it is visually more appealing.
                lsvPeptides.EnsureVisible(visibleIndex)

                Application.DoEvents()

                'Changed PM_MS3_SCORE_ORDER 2005-01-26
                'Note: ***is*** visual index
                mCurrentlySelectedPeptIdx = visibleIndex

                'Changed PM_REFACTOR 2006-03-16
                ''Currently happens (indirectly) in DisplayNthPeptide(). What
                ''  happens?
                ''  This might be OK after all....
                Dim pept As PeptideHitStructure = _
                  PeptideHitStructure.blankPeptide() 'Keep compiler happy.
                mProt.peptides.peptideByToken(peptToken, pept)

                'Probably not needed now. Shoould now be displayed when the
                'spectrum is updated.
                'Changed PM_REFACTOR 2006-01-03
                Dim msg1 As String = _
                  "Raw file: " & Path.GetFileName(pept.rawFileFullPath)
                Me.postInformation(msg1)

                'Changed PM_MS3SCORING_ONLYVALIDATEDPEPTIDES 2004-10-25
                If pept.verified Then 'Only do MS3 score on validated peptides...

                    Me.DisplayNthPeptide(visibleIndex, pept.AASequence, 0)

                    Try
                        MS3_NextSpecAndCalcExtraScore(pept.charge)
                        Application.DoEvents()

                    Catch exceptionObject As Exception
                        Dim errMsg1 As String = _
                          "Exception thrown during call of MS3_NextSpecAndCalcExtraScore() for peptide " & _
                          pept.AASequence & ". " & _
                          "Error: " & exceptionObject.ToString & _
                          ControlChars.NewLine
                        Dim errMsg2 As String = _
                          "Message: " & exceptionObject.Message & _
                          ControlChars.NewLine
                        Dim errMsg3 As String = ""
                        If Not exceptionObject.InnerException Is Nothing Then
                            errMsg3 = _
                                "Extra info: " & _
                                exceptionObject.InnerException.Message & _
                                ControlChars.NewLine
                        End If
                        Dim errMsg As String = errMsg1 & errMsg2 & errMsg3
                        MsgBox(errMsg)
                        Exit Function
                    End Try

                Else
                    Dim peter72 As Integer = 72
                End If
            Else
                Dim peter9 As Integer = 9
            End If

            Application.DoEvents()

            'Note: write-back happens in MS3_NextSpecAndCalcExtraScore()

            ProgressBar1.Value = _
              CInt(100 * (i + 1) / CDbl(lsvPeptides.Items.Count))

            If mStop Then
                btnStopMS3Scoring.ForeColor = Color.DarkRed
                mStop = False
                toReturn = True
                Exit For
            End If
        Next 'Peptides

        ProgressBar1.Value = 0
        'CalculateProteinRatio()  or similar
        'ColourPeptideItems()  ????
        'mProt.proteinHasBeenQuantified = True  ????

        'Forward to parent - where it needs to be updated
        'Write back protein
        mFrmProteinList.updateProtein(mProteinListIndex, mProt)

        Return toReturn
    End Function 'doUnattentedMS3scoring


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Function doUnattendedPTMscoring() _
      As Boolean
        'Return value: true if user cancelled...

        'Prepare for PTM scoring in raw file order. This is to save
        'the overhead of shifting between raw files and to reduce
        'resource exhaustion problems (leaks).

        Dim peptideTokens As List(Of visibleIndexStruct) = _
          Me.buildTokenListForAllPeptides()
        Dim lastIndex As Integer = peptideTokens.Count() - 1

        'For performance..
        'Changed PM_REFACTOR 2008-09-25. No need to preallocate, it happens
        '  in findOrderByRawFile().
        'Dim PTMScoringOrderIndexes(lastIndex) As visibleIndexStruct
        Dim PTMScoringOrderIndexes2 As List(Of visibleIndexStruct) = _
          Nothing 'Keep compiler happy.

        quantApplication.findOrderByRawFile( _
          peptideTokens, mProt, PTMScoringOrderIndexes2)

        Dim i As Integer
        For i = 0 To lastIndex
            Dim curIndexes As visibleIndexStruct = PTMScoringOrderIndexes2(i)

            'Dim peptDataIdx As Integer = curIndexes.pepIndex
            Dim peptToken2 As Integer = curIndexes.token3

            Dim visibleIndex2 As Integer = curIndexes.visualIdx2

            'Note: this check should no longer be necessary as we use filters.
            If peptToken2 >= 0 Then 'Ignore ZZZZ peptides...
                lsvPeptides.Items(visibleIndex2).Selected = True 'We need this to
                '  be selected and it is visually more appealing.
                lsvPeptides.EnsureVisible(visibleIndex2)
                Application.DoEvents()
                mCurrentlySelectedPeptIdx = visibleIndex2

                'Changed PM_REFACTOR 2006-03-16
                'Dim thePept As PeptideHitStructure = _
                '  DirectCast(mProt.pepts(peptDataIdx), _
                '  PeptideHitStructure)
                Dim pept As PeptideHitStructure = _
                  PeptideHitStructure.blankPeptide() 'Keep compiler happy.
                mProt.peptides.peptideByToken( _
                  peptToken2, pept)

                'Probably not needed now. Shoould now be displayed when
                'the spectrum is updated.
                'Changed PM_REFACTOR 2006-01-03
                Dim msg1 As String = _
                  "Raw file: " & Path.GetFileName(pept.rawFileFullPath)
                Me.postInformation(msg1)

                If pept.verified Then 'Only do PTM score on validated peptides...
                    Me.DisplayNthPeptide(visibleIndex2, pept.AASequence, 0)

                    Try
                        'Changed PM_PTM_FOR_ALL 2007-08-08
                        'If quantApplication.isFinnegan(mOptions.rawFileMode) Then
                        'End If
                        'Changed PM_BROADER_PTMSCORE_AUTOMATION 2007-04-16

                        'Now the new PTM scoring way...
                        'Me.doPTMscoring()
                        Me.doPTMscoring2(True)

                        Application.DoEvents()

                    Catch exceptionObject As Exception
                        Dim errMsg1 As String = _
                          "Exception thrown during call of " & _
                          "doUnattendedPTMscoring() for peptide " & _
                          pept.AASequence & ". " & _
                          "Error: " & exceptionObject.ToString & _
                          ControlChars.NewLine
                        Dim errMsg2 As String = _
                          "Message: " & exceptionObject.Message & _
                          ControlChars.NewLine
                        Dim errMsg3 As String = ""
                        If Not exceptionObject.InnerException Is Nothing Then
                            errMsg3 = _
                                "Extra info: " & _
                                exceptionObject.InnerException.Message & _
                                ControlChars.NewLine
                        End If
                        Dim errMsg As String = errMsg1 & errMsg2 & errMsg3
                        MsgBox(errMsg)
                        Exit Function
                    End Try
                End If

                Application.DoEvents()
                ProgressBar1.Value = _
                  CInt(100 * (i + 1) / CDbl(lsvPeptides.Items.Count))
            End If
        Next 'Peptides

        ProgressBar1.Value = 0
        'Write back protein
        mFrmProteinList.updateProtein(mProteinListIndex, mProt)

        'What about the return value??
        'Return value: true if user cancelled...

    End Function 'doUnattendedPTMscoring


    'Changed PM_QUANT_AUTOMATION 2003-03-11
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub doUnattentedQuantitation( _
      Optional ByVal aNewInstance As Boolean = True)

        quantLabeledProtein(aNewInstance)
        mCurrentQuantWindow.doQuantitateProtein()

        'mProt really changed?

        mCurrentQuantWindow.Show() 'Needed?
    End Sub 'doUnattentedQuantitation


    'Changed PM_QUANTITATE_NEXTPROTEIN 2004-11-16
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub NextProteinForQuantitation()
        Me.MoveNextProtein()
        Me.ResetValues()
        Me.quantLabeledProtein(False)
    End Sub 'NextProteinForQuantitation


    'For button...
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub btnQuantitate_Click( _
      ByVal sender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles btnQuantitate.Click

        quantLabeledProtein()
    End Sub 'btnQuantitate_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuOpenQuantitaionWindow_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuOpenQuantitaionWindow.Click

        quantLabeledProtein()
    End Sub 'mnuOpenQuantitaionWindow_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub stopMS3()
        mStop = True
        btnStopMS3Scoring.ForeColor = Color.DarkBlue

        If False Then 'Test code...
            'Dim xyz As New FinniganRawfile2WrapLib.SFinniganRawfile2WrapClass
            'Dim someNumber As Double
            'xyz.times2b(2.81, someNumber)
            'xyz.GetType()
        End If
    End Sub 'stopMS3


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub btnStopMS3Scoring_Click( _
      ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles btnStopMS3Scoring.Click

        Me.stopMS3()
    End Sub 'btnStopMS3Scoring_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuStopMS3Scoring_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuStopMS3Scoring.Click

        Me.stopMS3()
    End Sub 'mnuStopMS3Scoring_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuStopPTMScoring_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuStopPTMScoring.Click

        MsgBox("Sorry, not implemented.")
    End Sub 'mnuStopPTMScoring_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuScoreMS3_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuScoreMS3.Click

        MS3_NextSpecAndCalcExtraScore(mLastPeptHit.charge)
    End Sub 'mnuScoreMS3_Click


    'Changed PM_REFACTOR 2006-01-03
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub postInformation(ByRef aMsg As String)

        'lblMSMSMSInfo.Text = aMsg  Phased out...

        'Perhaps later: use segmented status bar, with items rawFile,
        '  spectrumNum, spectrumHeader, general.
        '
        'staSpectrumInfoEtc.Text = aMsg

        StatusBarPanel1.Text = aMsg 'Note: this panel is part of staSpectrumInfoEtc.
    End Sub 'postInformation


    'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-04
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuCommitPTMchanges_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuCommitPTMchanges.Click

        clbPTMcombinations.BackColor = System.Drawing.Color.Salmon

        Dim peptHit As PeptideHitStructure = _
          PeptideHitStructure.blankPeptide() 'Keep compiler happy.

        Dim onePTM As onePTMStructure
        onePTM.combinations2 = Nothing 'Keep compiler happy.

        If True Then
            Dim outIdx As Integer
            peptHit = getPeptideFromVisualIndex(mCurrentlySelectedPeptIdx, outIdx)
            onePTM = peptHit.PTMs2(0) 'Assume only one kind of PTM...
        End If

        Dim anyChange As Boolean = False
        Dim lastIndex As Integer = clbPTMcombinations.Items.Count - 1
        Dim j As Integer
        For j = 0 To lastIndex Step 1

            'Visual
            Dim someItem As Object = clbPTMcombinations.Items(j)

            Dim checkedStatus As Boolean = _
              CBool(clbPTMcombinations.GetItemCheckState(j))

            'Data structure
            Dim index As Integer = mSortedPTMIndices2(j)
            Dim someComb As onePTMcombinationStructure = _
              onePTM.combinations2(index)

            If checkedStatus <> someComb.checked7 Then
                'We need to update it.

                someComb.checked7 = checkedStatus
                onePTM.combinations2(index) = someComb 'Write back.
                anyChange = True
            End If
        Next

        If anyChange Then
            peptHit.PTMs2(0) = onePTM 'Write back. How is the protein updated??
            updateBestPTMinPeptideListGUI()
        End If
    End Sub 'mnuCommitPTMchanges_Click


    'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-04
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub clearPTMscoreSelected()

        clbPTMcombinations.Items.Clear()
        clbPTMcombinations.BackColor = System.Drawing.Color.White
    End Sub 'clearPTMscoreSelected


    'Changed PM_REFACTOR 2006-01-04. Note: two callers still need to use
    '  this function - requires refactoring in itself.
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub updateBestPTMinPeptideListGUI()

        Dim rowToUpdate As ListViewItem = lsvPeptides.SelectedItems(0)

        'Changed PM_MOD_PREFIX_AND_POSTFIX 2006-06-07
        Dim quantitationModesObject As QuantitationModes_moreGeneral = _
          mApplication.getQuantModes()

        'Later: refactor these 3 lines.
        'Changed PM_PHOSPHO_SCORING_DISPLAY 2005-10-19
        Dim PTMinfoSB As StringBuilder = New StringBuilder
        Dim highestPTMscore As Double
        PTMscorer.formatSomeCombinations( _
          mLastPeptHit.AASequence, mLastPeptHit.PTMs2, True, _
          quantitationModesObject, _
          PTMinfoSB, _
          highestPTMscore)

        mColumnMapper.updateListItem( _
          rowToUpdate, peptideColEnum2.enumPTMinfo, _
          PTMinfoSB.ToString)
    End Sub 'updateBestPTMinPeptideListGUI


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function getOnePTM(ByRef anOutAASequence As String) _
      As onePTMStructure

        Dim toReturn As onePTMStructure
        toReturn.combinations2 = Nothing

        Dim peptHit As PeptideHitStructure
        If True Then
            Dim outIdx As Integer
            peptHit = getPeptideFromVisualIndex(mCurrentlySelectedPeptIdx, outIdx)
            If Not peptHit.PTMs2 Is Nothing Then
                toReturn = peptHit.PTMs2(0) 'Assume only one kind of PTM...
            End If
            anOutAASequence = peptHit.AASequence
        End If
        Return toReturn
    End Function 'getOnePTM


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub updatePTM_GUIdisplay()

        'Changed PM_PTMDISLAY_TROUBLE 2006-02-28
        If Not mPTMscorer Is Nothing Then 'This does not
            ' solve CPs problem ("Error:
            ' System.ArgumentOutOfRangeException: Specified
            ' argument was out of the range of valid values.
            ' Parameter name: '0' is not a valid value of
            ' 'value'.".),
            '
            ' but is also necessary....

            Try
                Dim visualIndex As Integer = _
                  mPTMcombinationsCycler.getCurrentValue()
                Dim index As Integer = mSortedPTMIndices2(visualIndex)

                Dim AAsequence As String = Nothing 'Keep compiler happy.
                'Dim onePTM As onePTMStructure = Me.getOnePTM(AAsequence) not used..

                Dim someComb As ionSetStruct = _
                  mPTMscorer.getCombinationByIndex(index)

                'Changed PM_COMB_FOR_MS3 2006-08-01
                mCurrentComb = someComb

                Me.displayPTMcombination( _
                  someComb, someComb.score, visualIndex)

            Catch exceptionObject As Exception
                'For a newly opened protein validation window: this
                'will happen if another peptide is PTM scored
                'and then the PTM list for this peptide is clicked -
                'the problem is detected in displayPTMcombination():
                '
                '  "PIL ASSERT. Peptide length, 19, does not
                '   correspond to number of backward (y) ions,26."
                '   
                AppCommon2.displayStandardExceptionInfo( _
                  exceptionObject, _
                  "Could not display PTM combination. " & _
                  "You have to first PTM score again. " & _
                  "This will unfortunately result in loss of any manual changes." & _
                  ControlChars.NewLine)
                Exit Sub
            End Try
        Else
            MsgBox("Could not show PTM combination. " & _
              "There is not enough PTM scoring information is available " & _
                "(current limination). " & _
              "Please PTM score peptide again " & _
              "(this will, unfortunately, result in loss of any manual changes).")


            'Changed PM_REOPEN_PROTVAL_PTMSCORE 2007-04-19
            'Later:
            '  try to recover.



        End If
    End Sub 'updatePTM_GUIdisplay


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub resetOnePTM()
        Dim outIdx As Integer
        Dim peptHit As PeptideHitStructure = _
          getPeptideFromVisualIndex(mCurrentlySelectedPeptIdx, outIdx)

        If Not peptHit.PTMs2 Is Nothing Then
            Dim onePTM As onePTMStructure = peptHit.PTMs2(0)
            onePTM.combinations2 = Nothing
            peptHit.PTMs2(0) = onePTM

            'Assume only one kind of PTM...
        End If
    End Sub 'resetOnePTM


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub clbPTMcombinations_SelectedIndexChanged( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles clbPTMcombinations.SelectedIndexChanged

        Dim selIdx As Integer = clbPTMcombinations.SelectedIndex
        If selIdx >= 0 Then
            mPTMcombinationsCycler.setCurrentValue(selIdx)
            Me.updatePTM_GUIdisplay()
        End If
    End Sub 'clbPTMcombinations_SelectedIndexChanged


    'Changed PM_REINTRODUCE_BUTTONS 2006-03-06
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuOpenToolbar_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuOpenToolbar.Click

        Dim temp1Form As New frmToolBarProteinValidation(Me)
        temp1Form.Show()
    End Sub 'mnuOpenToolbar_Click


    'Changed PM_REINTRODUCE_BUTTONS 2006-03-06
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub commandEx(ByVal aCommand As proteinValidationCommandEnum)

        'Changed PM_REINTRODUCE_BUTTONS 2006-03-06
        Select Case aCommand
            Case proteinValidationCommandEnum.enumAcceptProtein
                proteinMoveToNextProtein(True)

            Case proteinValidationCommandEnum.enumRejectProtein
                proteinMoveToNextProtein(False)

            Case proteinValidationCommandEnum.enumAcceptPeptide
                MarkPeptVerifiedAndMoveToNext()

            Case proteinValidationCommandEnum.enumRejectPeptide
                MarkPeptNotVerifAndMoveNext()

            Case proteinValidationCommandEnum.enumQuantitateProtein
                quantLabeledProtein()

            Case Else
                Trace.Assert(False, _
                  "PIL ASSERT. Select Case never fall-through")
        End Select
    End Sub 'commandEx


    'Changed PM_OLD_BUTTONS 2006-11-12.
    '
    ' O L D   B U T T O N S , B E G I N


    'Changed PM_REFACTOR 2007-07-22. Not currently used.
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub btnNextMS1_Click( _
    '   ByVal aSender As System.Object, ByVal anEvent As System.EventArgs)
    ' 
    '     NextMS1()
    ' End Sub 'btnNextMS1_Click


    'Changed PM_REFACTOR 2007-09-25. No longer needed. If we again need
    '  a button in this form to zoom out in the spectrum then it should
    '  be implemented in another way.
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub btnZoomOut_Click( _
    '   ByVal aSender As System.Object, ByVal anEvent As System.EventArgs)
    ' 
    '     Select Case mOptions.rawFileMode
    '         Case rawFileModeEnum.enumAnalyst
    ' 
    '             'Changed PM_REFACTOR 2007-07-22
    '             ' mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.Min = _
    '             '   mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.DataMin
    '             ' mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.Max = _
    '             '   mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.DataMax
    '             ' mAxGraphControl_ANALYSTCOM_2.GraphArea.YAxis.Max = _
    '             '   mAxGraphControl_ANALYSTCOM_2.GraphArea.YAxis.DataMax
    '             Dim dataXmin As Double
    '             Dim dataXmax As Double
    '             Dim dataYmax As Double
    '             Dim minX As Double
    '             Dim maxX As Double
    '             mAnalystCOM_Graph.axControl_getAxisRanges( _
    '               dataXmin, dataXmax, dataYmax, minX, maxX)
    ' 
    '             Me.setAnalystAxes(dataXmin, dataXmax, dataYmax)
    ' 
    '         Case rawFileModeEnum.enumFinnegan, rawFileModeEnum.enumMicromass
    '             'Nothing for now..
    '         Case Else
    '             Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
    '     End Select
    ' End Sub 'btnZoomOut_Click


    'Changed PM_REFACTOR 2007-09-25. No longer needed. If we again need
    '  this functionality in this form then it should
    '  be implemented in another way.
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub btnZoomNext_Click( _
    '   ByVal aSender As System.Object, ByVal anEvent As System.EventArgs)
    ' 
    '     ZoomNextFragment()
    ' End Sub 'btnZoomNext_Click


    'Changed PM_REFACTOR 2007-07-22. Not currently used.
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub btnPrevMS1_Click( _
    '   ByVal aSender As System.Object, ByVal anEvent As System.EventArgs)
    ' 
    '     PreviousMS1()
    ' End Sub 'btnPrevMS1_Click


    'Changed PM_MS3INTEGRATION 2004-05-12
    'Button....
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub btnShowMS3_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs)

        'Is it OK to use mLastPeptHit at this point??????????????
        MS3_NextSpecAndCalcExtraScore(mLastPeptHit.charge)
    End Sub 'btnShowMS3_Click


    ' O L D   B U T T O N S , E N D


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuScorePTM2_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuScorePTM2.Click

        Me.doPTMscoring2(True)
    End Sub 'mnuScorePTM2_Click


    'Changed PM_AUTODOCUMENTATION 2007-04-17
    'This function could be anywhere.
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Shared Sub dumpFormAsPixels( _
      ByRef anInSomeForm As Form, ByRef anInSaveFileName As String)

        If True Then
            anInSomeForm.BringToFront() 'Will this happen immediately???

            Dim g1 As Graphics = anInSomeForm.CreateGraphics()
            Dim MyImage As Image = _
              New Bitmap( _
                anInSomeForm.ClientRectangle.Width, _
                anInSomeForm.ClientRectangle.Height, g1)
            Dim g2 As Graphics = Graphics.FromImage(MyImage)

            ' Gdi32.BitBlt(dc2, 0, 0, Me.ClientRectangle.Width, Me.ClientRectangle.Height, dc1, 0, 0, 13369376)
            '
            ' <ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_fxmclignrl/html/33b76910-13a3-4521-be98-5c097341ae3b.htm>:
            '
            ' With Windows Forms, bitblt is accomplished using
            ' the CopyFromScreen method of the Graphics class.
            '
            'Second parameters must be (0,0), otherwise the image
            'is shifted right and down.
            '
            'Note: copies pixels from the actual screen. Thus the form
            '      must be in front in order for this to work...
            g2.CopyFromScreen( _
              anInSomeForm.Location, New Point(0, 0), anInSomeForm.Size())

            MyImage.Save( _
              anInSaveFileName, System.Drawing.Imaging.ImageFormat.Png)

            'MessageBox.Show("Finished Saving Image")

            g2.Dispose()
            g1.Dispose()
            'What about MyImage??

        End If
    End Sub 'dumpFormAsPixels


    'Changed PM_AUTODOCUMENTATION 2007-04-17
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSaveAsPNG_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuSaveAsPNG.Click

        '  me.ClientRectangle
        '  me.Container
        '  me.CreateGraphics
        '  me.CreateHandle
        '  Me.DefWndProc()
        '  me.DisplayRectangle
        '  me.DrawToBitmap
        '  me.Handle
        '  me.Parent
        '  me.Region
        '  me.WndProc

        'From <http://dotnetpulse.blogspot.com/2006/12/how-to-capture-form-and-save-it-to.html>

        Dim saveFileName As String = _
          "c:\Captured" & mSaveCounter & ".png"
        dumpFormAsPixels(Me, saveFileName)
        mSaveCounter += 1

        'Does not really work, XCalibur spectrum is missing...:
        ' If False Then
        '     Dim point As Point = New Point()
        '     Dim rectangle As Rectangle = New Rectangle(point, Me.Size)
        '     Dim bitmap As Bitmap = _
        '       New Bitmap( _
        '         rectangle.Width, rectangle.Height, _
        '         System.Drawing.Imaging.PixelFormat.Format32bppRgb)
        ' 
        '     'Render the form to the bitmap.
        '     Me.DrawToBitmap(bitmap, rectangle)
        '     bitmap.Save("c:\MyForm.png")
        ' End If

        'Me.DrawToBitmap()
        'Dim g As Graphics = Me.CreateGraphics()
        'Dim i As Image = New Image
    End Sub 'mnuSaveAsPNG_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Function doDumpPeptideInfoAsGraphics( _
      ByRef anInDumpDir As String, _
      ByRef anInOutFileCounter As Integer, _
      ByVal aIsLastProtein As Boolean, _
      ByRef anInOutParameters As reportStructure) _
      As Boolean

        Dim writer As System.Xml.XmlTextWriter = anInOutParameters.XMLwriter

        If True Then 'Output to main DocBook document
            'Note: each protein is one "chapter" (in the Doc book sense)

            writer.WriteStartElement("chapter")

            Dim title1 As String = _
              "Protein " & mProt.hitNumber & ": " & mProt.accNum
            writer.WriteElementString( _
              "title", Nothing, title1)

            writer.WriteStartElement("sect1") 'Protein header

            writer.WriteElementString( _
              "title", Nothing, _
              "Protein information")

            writer.WriteElementString( _
              "para", Nothing, _
              "Description: " & mProt.description3)

            writer.WriteElementString( _
              "para", Nothing, _
              "Total number of peptides (not just validated): " & _
              mProt.effectivePeptideCount)

            writer.WriteEndElement() 'For sect1.
        End If

        'Do it in raw file order. This is to save
        'the overhead of shifting between raw files and to reduce
        'resource exhaustion problems (leaks).

        'Changed PM_AUTODOCUMENTATION 2007-04-17
        'Refactor idea: create some iterator, preparation & returning one  
        '  peptide at a time. There is a lot of repeated code 
        '  in doUnattentedQuantitation(), doUnattendedPTMscoring(), etc.

        Dim peptideTokens As List(Of visibleIndexStruct) = _
          Me.buildTokenListForAllPeptides()

        Dim lastIndex As Integer = peptideTokens.Count() - 1

        'For performance..
        'Changed PM_REFACTOR 2008-09-25. No need to preallocate, it happens
        '  in findOrderByRawFile().
        'Dim orderIndexes(lastIndex) As visibleIndexStruct
        Dim orderIndexes2 As List(Of visibleIndexStruct) = _
          Nothing 'Keep compiler happy.

        quantApplication.findOrderByRawFile( _
          peptideTokens, mProt, orderIndexes2)

        Dim i As Integer
        For i = 0 To lastIndex
            Dim lastPeptide As Boolean = i = lastIndex

            Dim curIndexes As visibleIndexStruct = orderIndexes2(i)
            Dim peptToken As Integer = curIndexes.token3
            Dim visibleIndex As Integer = curIndexes.visualIdx2

            lsvPeptides.Items(visibleIndex).Selected = True 'We need this to
            '  be selected and it is visually more appealing.
            lsvPeptides.EnsureVisible(visibleIndex)
            Application.DoEvents()
            mCurrentlySelectedPeptIdx = visibleIndex

            Dim pept As PeptideHitStructure = _
              PeptideHitStructure.blankPeptide() 'Keep compiler happy.
            mProt.peptides.peptideByToken( _
              peptToken, pept)

            'Probably not needed now. Shoould now be displayed when
            'the spectrum is updated.
            Dim msg1 As String = _
              "Raw file: " & Path.GetFileName(pept.rawFileFullPath)
            Me.postInformation(msg1)

            If pept.verified Then 'Only do it on validated peptides...
                Me.DisplayNthPeptide(visibleIndex, pept.AASequence, 0)

                Try
                    Application.DoEvents()
                    Application.DoEvents()
                    Application.DoEvents()

                    Dim saveFileNameNoExt As String = "pept" & anInOutFileCounter
                    Dim saveFileName As String = saveFileNameNoExt & ".png"
                    Dim saveFileNameFullPath As String = _
                      anInDumpDir & Path.DirectorySeparatorChar & _
                      saveFileName

                    dumpFormAsPixels(Me, saveFileNameFullPath)

                    anInOutFileCounter += 1

                    If True Then 'Output to DocBook document file.
                        Dim formatStr As String = anInOutParameters.massFormatStr

                        Dim peptLine As String = "Peptide " & pept.AASequence & "."
                        Dim qLine As String = "Query number " & pept.queryNumber & "."
                        Dim rfLine As String = "Raw file " & pept.rawFileFullPath & "."

                        Dim RTline As String = _
                          "Retention: " & _
                          pept.retentionTimeStartMinutes.ToString("0.000") & _
                          " minutes, spectrum " & pept.spectrumNumber & "."

                        Dim MCRline As String = _
                          "Observed mass to charge ratio: " & _
                          pept.measuredMCR.ToString(formatStr) & " Th."
                        Dim MCRline2 As String = _
                          "Calibrated observed mass to charge ratio: " & _
                          pept.calibratedMeasuredMCR.ToString(formatStr) & " Th."

                        Dim chargeLine As String = _
                          "Charge: " & pept.charge & "."

                        Dim calcMassLine As String = _
                          "Theoretical neutral mass: " & _
                          pept.MascotCalculatedMass.ToString(formatStr) & " Da."

                        'Refactor opportunity...
                        Dim massDiffAbs As Double = _
                          pept.MascotCalculatedMass - _
                          pept.calibratedMeasuredMass
                        Dim massDiffAbsLine As String = _
                          "Mass difference (after recalibration): " & _
                          massDiffAbs.ToString(formatStr) & _
                          " Da."

                        Dim massDiffRelativeLine As String = _
                          "Relative mass difference (after recalibration): " & _
                          pept.relativeErrorForPeptideMass_PPM.ToString("0.00") & _
                          " ppm."

                        writer.WriteStartElement("sect1")

                        writer.WriteElementString( _
                          "title", Nothing, peptLine)

                        writer.WriteElementString( _
                          "para", Nothing, qLine)

                        writer.WriteElementString( _
                          "para", Nothing, RTline)

                        writer.WriteElementString( _
                          "para", Nothing, rfLine)

                        writer.WriteElementString( _
                          "para", Nothing, MCRline)
                        writer.WriteElementString( _
                          "para", Nothing, MCRline2)

                        writer.WriteElementString( _
                          "para", Nothing, chargeLine)

                        writer.WriteElementString( _
                          "para", Nothing, calcMassLine)

                        writer.WriteElementString( _
                          "para", Nothing, massDiffAbsLine)

                        writer.WriteElementString( _
                          "para", Nothing, massDiffRelativeLine)

                        writer.WriteStartElement("figure")
                        writer.WriteAttributeString("id", Nothing, saveFileNameNoExt)
                        writer.WriteAttributeString("float", Nothing, "0")

                        writer.WriteElementString( _
                          "title", Nothing, _
                          "Identification spectrum for " & pept.AASequence & ".")

                        writer.WriteStartElement("mediaobject")

                        writer.WriteStartElement("imageobject")

                        'We really need attributes here!!!!
                        'Use "saveFileName"...
                        '
                        'Like:
                        '  <imagedata fileref="<appname>Misc/MSQ_ToolsOptions.gif" format="GIF"/>
                        'anInOutXmlWriter.WriteElementString( _
                        '  "imagedata", Nothing, _
                        '    "")
                        writer.WriteStartElement("imagedata")

                        writer.WriteAttributeString("fileref", Nothing, saveFileName)
                        writer.WriteAttributeString("format", Nothing, "PNG")

                        writer.WriteEndElement() 'For imagedata.

                        writer.WriteEndElement() 'For imageobject.

                        'Later:
                        '
                        '  <textobject><phrase>xyz</phrase></textobject>
                        '  <caption><para>
                        '     <caption>
                        '     <app name> options dialog.
                        '     'Quantitation mode' should match the type of datafiles
                        '     from which the search input to Mascot was generated.</para>
                        '  </caption>

                        writer.WriteEndElement() 'For mediaobject.

                        writer.WriteEndElement() 'For figure.

                        If aIsLastProtein AndAlso lastPeptide Then
                            writer.WriteElementString( _
                              "para", Nothing, "Last peptide. End of report.")
                        End If

                        writer.WriteEndElement() 'For sect1.
                    End If

                Catch exceptionObject As Exception
                    Dim errMsg1 As String = _
                      "Exception thrown during call of " & _
                      "doDumpPeptideInfoAsGraphics() for peptide " & _
                      pept.AASequence & ". " & _
                      "Error: " & exceptionObject.ToString & _
                      ControlChars.NewLine
                    Dim errMsg2 As String = _
                      "Message: " & exceptionObject.Message & _
                      ControlChars.NewLine
                    Dim errMsg3 As String = ""
                    If Not exceptionObject.InnerException Is Nothing Then
                        errMsg3 = _
                            "Extra info: " & _
                            exceptionObject.InnerException.Message & _
                            ControlChars.NewLine
                    End If
                    Dim errMsg As String = errMsg1 & errMsg2 & errMsg3
                    MsgBox(errMsg)
                    Exit Function
                End Try
            End If

            Application.DoEvents()
            ProgressBar1.Value = _
              CInt(100 * (i + 1) / CDbl(lsvPeptides.Items.Count))
        Next 'Peptides

        ProgressBar1.Value = 0

        writer.WriteEndElement() 'For chapter.
    End Function 'doDumpPeptideInfoAsGraphics


    'Changed PM_REFACTOR 2007-09-25. No longer needed. If we again need
    '  a button in this form to zoom out in the spectrum then it should
    '  be implemented in another way.
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Sub setAnalystAxes( _
    '   ByVal aXmin As Double, ByVal aXmax As Double, ByVal aYmax As Double)
    ' 
    '     'Changed PM_REFACTOR 2007-07-22
    '     ' mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.Min = aXmin
    '     ' mAxGraphControl_ANALYSTCOM_2.GraphArea.XAxis.Max = aXmax
    '     ' 
    '     ' mAxGraphControl_ANALYSTCOM_2.GraphArea.YAxis.Max = aYmin
    '     mAnalystCOM_Graph.axControl_setXaxisMin(aXmin)
    '     mAnalystCOM_Graph.axControl_setXaxisMax(aXmax)
    '     mAnalystCOM_Graph.axControl_setYaxisMax(aYmax)
    ' 
    ' End Sub 'setAnalystAxes


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '*    Note: this function is for the export filter.                         *
    '****************************************************************************
    Public Sub setProteinAndPeptidesFilter( _
      ByVal aInProteinAndPeptidesFilter2 As proteinAndPeptidesFilterStructure2, _
      ByVal aPeptideFilter As peptideFilterStructure)

        'Intended for use only from the Quantitation window, to persist
        'export dialog settings.
        '
        'Just route on, to Protein List window.
        mFrmProteinList.setProteinAndPeptidesFilter( _
          aInProteinAndPeptidesFilter2, aPeptideFilter)
    End Sub 'setProteinAndPeptidesFilter


    'Changed PM_ION_SERIES_DISPLAYOPTION 2008-05-26
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub chkShowMatchedIonsOnly_CheckedChanged( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles chkShowMatchedIonsOnly.CheckedChanged

        'Save new setting as global. 
        Dim displayOnlyMatched As Boolean = chkShowMatchedIonsOnly.Checked 'How
        '  to get it from the event??
        mApplication.setShowOnlyMatchedIons(displayOnlyMatched)

        If Not mStartingUp Then
            'asdad() 'Update by displaying current peptide again
            If True Then
                Dim visualIndex As Integer = lsvPeptides.SelectedIndices.Item(0)
                Me.DisplayNthPeptide(visualIndex, "", 0)
            Else
                DisplayNthPeptide(mCurrentlySelectedPeptIdx, "", 0)
            End If
        End If

    End Sub 'chkShowMatchedIonsOnly_CheckedChanged


    'Changed PM_COLUMNSORT_BY_KEYBOARD 2008-11-11
    '****************************************************************************
    '*    Common menu command handler for the sub items                         *
    '*    of the View menu (that are setup dynamically).                        *
    '****************************************************************************
    Private Sub arrangeProteinsMenuSubItemsOnClick( _
      ByVal aSender As Object, ByVal anEvent As EventArgs)

        Dim someMenuItem As MenuItem = DirectCast(aSender, MenuItem)
        Dim columnSortID As Integer = CInt(someMenuItem.Tag)
        mListViewColumnSorter.prepareSortAndSort(columnSortID, lsvPeptides)
    End Sub 'arrangeProteinsMenuSubItemsOnClick()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuScorePTM_Old_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuScorePTM_Old.Click

        'Changed PM_PTM_FOR_ALL 2007-06-21
        ' 'Is this because of neutral loss/MS3? After PTM has been
        ' 'generalised it should also work for other types(?)
        ' If quantApplication.isFinnegan(mOptions.rawFileMode) Then
        '     Me.doPTMscoring(True)
        ' End If
        Me.doPTMscoring_old(True)
    End Sub


    'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
    'This function should go away at some point; when we will have
    'an individual setting for each kind export.
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function getGlobalTargetSettings() _
      As exportTargetSettingsStruct

        'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
        'Note: we are using the settings for the proteins and
        '      peptide export. Essentially these are currently
        '      global for all kinds of exports.
        Dim exportTargetSettings As exportTargetSettingsStruct = _
          mOptions.proteinAndPeptidesFilter.exportTargetSettings4

        'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
        quantApplication.checkExportSettings(exportTargetSettings)
        '  This will present the target dialog to the user if
        '  the setting has not been persisted yet.

        Return exportTargetSettings
    End Function 'getGlobalTargetSettings()


End Class 'Class frmProtValidation


    

    

Generated by script codePublish.pl at 2009-01-05T15:20:59.