Source code for MSQuant: frmProteinList.vb, MSQuant/msquant/src/GUI/forms/frmProteinList.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 List window. User can select protein(s) for        *
'*          inspection or go direct to quantitation of their peptides.      *
'*                                                                          *
'****************************************************************************

'****************************************************************************
'*                               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:   frmProteinList.vb                                         *
'*    TYPE:  VISUAL_BASIC                                                   *
'*                                                                          *
'* CREATED: PM 2002-04-15   Vrs 1.0.  Estimated..                           *
'* UPDATED: PM 2004-xx-xx   Embedding of Finnegan spectra.                  *
'*                                                                          *
'****************************************************************************

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

Imports System.Runtime.Serialization.Formatters.Binary 'For BinaryFormatter
Imports System.IO
Imports System.Text  'For StringBuilder
Imports System.Collections.Generic 'For Dictionary and List.


'Changed PM_REFACTOR 2008-04-16
''Changed PM_FAST_SERIALISATION 2006-12-15
'Imports System.Runtime.Serialization 'For SerializationInfo and StreamingContext.


'Changed PM_AUTODOCUMENTATION 2007-04-18
Imports System.Xml 'For XmlTextWriter


'Changed PM_REFACTOR 2008-04-16
''Changed PM_FAST_SERIALISATION 2006-12-15
'Imports SimmoTech.Utils.Serialization 'For SerializationWriter


'Changed PM_CONSENSUSSCORE_NEW 2008-12-05
Imports DotNetMatrix 'For GeneralMatrix. Requires reference
'  to project GeneralMatrix or to GeneralMatrix.dll.
'  
'  Ref:
'    <http://www.codeproject.com/KB/recipes/psdotnetmatrix.aspx>
'      DotNetMatrix: Simple Matrix Library for .NET.
'      Simply a port of a public domain Java matrix
'        library, called JAMA.


'Changed PM_SUPERCHARGE 2003-11-03
'Imports Mascot_Parser.SDUPutility
Imports SDUPutility
Imports CEBI_generalGUI 'For ListViewColumnSorter
Imports massSpectrometryBase
Imports MolecularSharedStructures 'For ProteinHitStructure and xxx.

'Changed PM_SUPERCHARGE 2003-11-03
Imports App
Imports massSpectrometryBase.quantitation 'For QuantitationModes_moreGeneral

'Changed PM_REFACTOR 2007-05-03
Imports AppCommon2 'For SDUP_emptyCommentLine() and SDUPcomment().


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


    'Changed PM_CONSENSUSSCORE_NEW 2008-12-05
    Public Structure consensusDishInfoStruct 'Move to more general place.

        Dim profile As List(Of statsStructure) 'Implicit the
        '  average (or median) of each.

        'For computing new consensus score (as it is not enough to
        'only keep the average for each point).

        Dim invcov As GeneralMatrix 'Inverse covariance matrix.
        Dim mean As GeneralMatrix 'Mean vector.
    End Structure 'consensusDishInfoStruct


    'Changed PM_REFACTOR 2004-02-04
    Private Enum proteinColumnEnum
        enumProteinHitNumber = 233 'Note: protein hit number must
        '  be the first column.

        'Changed PM_PROTEINLIST_REALHEADERTEXTS 2005-03-01
        'ePeptsA
        'ePeptsB
        'ePeptsC

        enumProteinMass
        enumNumberOfPeptides
        enumProteinScore
        enumProteinAccessionNumber
        enumProteinDescription2

        'Changed PM_SEQUENCE_COVERAGE 2008-04-15
        enumSequenceCoverage

        'Changed PM_PROTEIN_TAGS 2008-10-29
        enumPrimaryProteinTag2

        'Note: these 3 must have a sufficient separation, e.g. 20 minumum.
        enumRatioBaseNumber3 = 1051
        enumRatioStdDevBaseNumber3 = 1259
        enumRatioRelErrBaseNumber4 = 1451

        'Changed PM_CONSENSUSSCORE_ALLDISHES 2008-11-11
        enumConsensusScoreBaseNumber2 = 1709

        'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
        enumConsensusNonZeroPoints = 2111
        enumPointsWithinConsensus = 2203

        enumTemp2
    End Enum 'proteinTbItmColEnum


    'Changed PM_GENERALISED_QUANT_MODE 2003-12-07
    'the actual parser. It will get the string from the file
    'Dim mMascotResultParser As New MascotResultParser()
    Private mMascotResultParser As MascotResultParser

    'status message to display at the bottom
    'Dim _statusStr As String = "Status: "   not currently used...

    Private mOptions As OptionsStruct2 'Needed. For passing the information on
    '                                       to frmProtValidation/frmProteinValidation.vb

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

    'Changed PM_REFACTOR 2004-04-06
    'Dim mMascotWebOutputFileName As String 'Note: does not seem
    ' to be used anywhere (?).
    'Private mMascotHTMFileName As String

    'Changed PM_TYPESAFE 2006-10-25
    'Private mParsedProts As ArrayList 'Type: ProteinHitStructure
    Private mParsedProts2 As List(Of ProteinHitStructure)

    'Changed PM_SEVERALWIFFS_EXPORT 2003-08-29
    Private mRawFiles2() As fileSpecStructure 'Note: serialised
    '  in mnuSaveProteinHitsAs_Click().

    Private mProteinHitsSaveStr As String 'Temp use for saving
    '  the results.

    Private mWiffFileQuantStr As String 'Path and name to the 2nd raw
    '  file for comparative quantitation.

    Private mRecalibrator As SDUPrecalibrator

    'Changed PM_INSTALLER 2004-01-23. Phased out. File
    '  containing frmMascotFiles has been removed.
    'Private mFileList As frmMascotFiles

    Private mWiffFile As rawFileInfoStruct

    'Changed PM_QUANT_AUTOMATION 2003-03-11
    Private mCurrentFrmProtValidation As frmProtValidation 'Last one
    '  used in openProtValForm()

    Private mAvoidHandlingProteinCheckedEvent As Boolean

    'Note: from hit number (not data structure index).
    Private mProteinHitNumber2dataIndex As Dictionary(Of Integer, Integer)

    '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

    'Changed PM_MEMORY_ALLOCATION 2004-08-02
    ''Changed PM_HANDLE_LEAK_WORKAROUND 2004-01-06
    'Dim mMenuQuantOneUsed As Boolean = False

    'Changed PM_MULTIPLE_FINNEGAN_TROUBLE 2004-01-18
    Private mRawDataFileHandling As rawDataFileHandling

    'Changed PM_REFACTOR 2005-03-01
    ''Changed PM_REFACTOR 2004-02-04
    ''Columns are now dynamic. We use this map (hash) to find
    ''the actual column index given an identifier.
    'Dim mColumnProteinMap3 As Hashtable
    Private mColumnMapper As listviewColumnMapper

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

    'Changed PM_REFACTOR 2008-11-06. Moved into ListViewColumnSorter.
    ''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.
    'Private mColumnSortSpecificationHash As Dictionary( _
    '  Of Integer, List(Of sortKeyStructure))

    'Changed PM_CLOSEWARNING 2004-04-21
    Private mDirty As Boolean

    'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-29. Now merged
    '  into options.
    ''Changed PM_GENERALISED_EXPORT 2005-03-08
    'Private mProteinAndPeptidesFilter2 As proteinAndPeptidesFilterStructure2

    'Changed PM_RECALIB_REPORT 2005-07-28
    Private mRecalibReport As System.Text.StringBuilder

    'Changed PM_FIND 2006-07-28
    Private mFindParameters As frmFind.findParametersStructure

    'Changed PM_REPORTS 2006-08-15
    Private mParseReport As SDUPstructuredReport
    Private mParentForm As frmMainForm

    'Changed PM_REFACTOR 2006-10-12
    Private mDishes As Integer 'Cached value, derived from current
    ' quantitation mode.

    'Changed PM_RETCORR_ANYTIME 2006-10-25
    Private mMultipleRawFilesHandling2 As MultipleRawFilesHandling

    'Changed PM_RETCORR_ANYTIME 2006-10-26
    Private mRetCorrParameters As retCorrParametersStructure

    'Changed PM_AUTODOCUMENTATION 2007-04-18
    'Make private and move into class?
    '
    'Purpose: collect report items.
    Private mReportInfo As reportStructure

    'Changed PM_FLEXIBLE_RAWFILE_LOC 2007-06-12
    Private mRawfile2RealRawFileHash As Dictionary( _
      Of String, String)

    'Changed PM_RECALIB_VISUAL_SAVE 2007-09-04
    Private WithEvents mCalibVisualForm As frmRecalibrationVisualisation

    'Changed PM_DOUBLE_RETURN_KEY 2007-09-08
    Private mKeyObserver As SDUPkeyObserver

    'Changed PM_RETRIEVE_PROTEIN_SEQUENCES 2008-04-15
    Private WithEvents mRetrieveProteinsParametersForm As frmRetrieveProteinsParameters

    'Changed PM_SPECTRAEXPORT_GENERALISED 2008-05-05
    Private WithEvents mExportProteinsAndPeptidesFiltersForm As frmExportFilters
    'Note: not generic export filters. Is very specific for 
    '      protein and peptide export.

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

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

    'Changed PM_PROTEIN_TAGS 2008-10-29
    Private WithEvents mTaggingForm As frmTagging
    Private mSsb As StringBuilder

    'Changed PM_CONSENSUSSCORE_NEW 2008-12-05
    ''Changed PM_PCP_CONSENSUS_PROFILE 2008-11-05
    'Private mConsensus As List(Of List(Of statsStructure)) 'Outer: per
    ''  dish (1/1, 2/1, 3/1, etc.). Inner: over dimension (profile) - e.g.
    ''  sucrose fraction.
    Private mConsensus As List(Of consensusDishInfoStruct) 'Outer: per
    '  dish (1/1, 2/1, 3/1, etc.). Inner: over dimension (profile) - e.g.
    '  sucrose fraction. And mean and covariance matrix.


    'Changed PM_PROTEIN_TAGS_USERDEFINED 2008-11-07
    Private mCurrentTags As List(Of taggingStruct)

    'Changed PM_MEMORY_EFFICIENCY 2008-11-12. Moved to class level
    '  instead of being repeated for every protein.
    '
    'Used in updateVisual_ProteinRow(). Setup in constructor.
    Private mProteinFormatStrings3() As String

    'Delete at any time.
    'Not used.
    ''To learn how it could work with initialisation lists.
    'Private mProteinFormatStrings2 As List(Of String)


    'Changed PM_SAVE_RAWFILE_MAPPING_MB4 2008-11-18
    Private WithEvents mDimensionsDialog As frmDimensions
    Private WithEvents mRawFileMappingDialog As frmRawFileMapping 'Member as we
    '  need a target for events from the dialog, e.g. when user OKs it.



#Region " Windows Form Designer generated code "

    'd$ <summary>
    'd$ Summary of New.
    'd$ </summary>
    'd$
    '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 MainMenu1 As System.Windows.Forms.MainMenu
    Friend WithEvents MenuItem4 As System.Windows.Forms.MenuItem
    Friend WithEvents ParserStatus As System.Windows.Forms.StatusBar
    Friend WithEvents mnuFile As System.Windows.Forms.MenuItem
    Friend WithEvents mnuOpenMascotFile As System.Windows.Forms.MenuItem
    Friend WithEvents mnuHelp As System.Windows.Forms.MenuItem
    Friend WithEvents mnuWiffInfo As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSearchStats As System.Windows.Forms.MenuItem
    Friend WithEvents mnuAction As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExportToSQL2000 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSaveProteinHitsAs As System.Windows.Forms.MenuItem
    Friend WithEvents mnuView As System.Windows.Forms.MenuItem
    Friend WithEvents mnuShowMascotResult As System.Windows.Forms.MenuItem
    Friend WithEvents OpenFileDialog1 As System.Windows.Forms.OpenFileDialog
    Friend WithEvents SaveFileDialog1 As System.Windows.Forms.SaveFileDialog
    Friend WithEvents mnuOptions As System.Windows.Forms.MenuItem
    Friend WithEvents ProgressBar1 As System.Windows.Forms.ProgressBar
    Friend WithEvents lstProtHits As ListViewCEBIExtended4
    Friend WithEvents ToolTip1 As System.Windows.Forms.ToolTip
    Friend WithEvents ContextMenu1 As System.Windows.Forms.ContextMenu
    Friend WithEvents mnuOpenProteinValWind As System.Windows.Forms.MenuItem
    Friend WithEvents mnuMarkAsChecked As System.Windows.Forms.MenuItem
    Friend WithEvents markAsReject As System.Windows.Forms.MenuItem
    Friend WithEvents mnuUnMarkProtein As System.Windows.Forms.MenuItem
    Friend WithEvents DisplayDBInfo As System.Windows.Forms.MenuItem
    Friend WithEvents mnuDisplaySeqandPepts As System.Windows.Forms.MenuItem
    Friend WithEvents mnuBlastProtein As System.Windows.Forms.MenuItem
    Friend WithEvents mnuRecalWiff As System.Windows.Forms.MenuItem
    Friend WithEvents mnuPeptideStats As System.Windows.Forms.MenuItem
    Friend WithEvents mnuQuantOptions As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSample As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSample1 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSample2 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSample3 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSample4 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuClose As System.Windows.Forms.MenuItem
    Friend WithEvents mnuParseAgain As System.Windows.Forms.MenuItem
    Friend WithEvents PanelProteinsParsed As System.Windows.Forms.StatusBarPanel
    Friend WithEvents PanelProteinsInTable As System.Windows.Forms.StatusBarPanel
    Friend WithEvents PanelFile As System.Windows.Forms.StatusBarPanel
    Friend WithEvents PanelStatus As System.Windows.Forms.StatusBarPanel
    Friend WithEvents PanelSecs As System.Windows.Forms.StatusBarPanel
    'd$  <summary>
    'd$  Summary of InitializeComponent.
    'd$  </summary>
    'd$
    Friend WithEvents mnuAutomation As System.Windows.Forms.MenuItem
    Friend WithEvents mnuQuantOne As System.Windows.Forms.MenuItem
    Friend WithEvents mnuQuantChecked As System.Windows.Forms.MenuItem
    Friend WithEvents mnuQuantExternal As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem2 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem3 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem5 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem6 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem8 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem10 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExportCorrelationReport As System.Windows.Forms.MenuItem
    Friend WithEvents mnuMS3ScoreChecked As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem13 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem14 As System.Windows.Forms.MenuItem
    Friend WithEvents MainMenu2 As System.Windows.Forms.MainMenu
    Friend WithEvents MenuItem11 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuEditSelectAll As System.Windows.Forms.MenuItem
    Friend WithEvents mnuEditUncheck As System.Windows.Forms.MenuItem
    Friend WithEvents mnuEditCheck As System.Windows.Forms.MenuItem
    Friend WithEvents mnuEditToggleChecked As System.Windows.Forms.MenuItem
    Friend WithEvents mnuEditSelectChecked As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExportProteinsAndPeptides As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSaveProteinsAndPeptides As System.Windows.Forms.MenuItem
    Friend WithEvents mnuEditInvertSelection As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem7 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExportRecalibReport As System.Windows.Forms.MenuItem
    Friend WithEvents mnuScoreMS3 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuScorePTM As System.Windows.Forms.MenuItem
    Friend WithEvents mnuRemovePeptides As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem16 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuFind As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem17 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuScrollToNextSelected As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExportParseReport As System.Windows.Forms.MenuItem
    Friend WithEvents mnuRetentionTimeCorrelation As System.Windows.Forms.MenuItem
    Friend WithEvents mnuRemoveInsertedPeptides As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem19 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSaveSelectedProteinHits As System.Windows.Forms.MenuItem
    Friend WithEvents mnuInsertProteins As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem22 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem21 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem23 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem24 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuReport As System.Windows.Forms.MenuItem
    Friend WithEvents mnuRecalibVisual As System.Windows.Forms.MenuItem
    Friend WithEvents mnuRecalibration As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExportRawFilesReport As System.Windows.Forms.MenuItem
    Friend WithEvents mnuRetrieveProteinSequences As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem26 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuComputeAndSetSequenceCoverage As System.Windows.Forms.MenuItem
    Friend WithEvents mnuUtility As System.Windows.Forms.MenuItem
    Friend WithEvents mnuOpenResultFileFolder As System.Windows.Forms.MenuItem
    Friend WithEvents mnuOpenRawFileFolder As System.Windows.Forms.MenuItem
    Friend WithEvents mnuDisplayProteinProfiles As System.Windows.Forms.MenuItem
    Friend WithEvents mnuAddTag As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem12 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuDeleteAllTags As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSetConsensusProfile As System.Windows.Forms.MenuItem
    Friend WithEvents mnuScoreConsensus As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem1 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuArrangeProteins As System.Windows.Forms.MenuItem
    Friend WithEvents mnuEditUnselectAll As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSaveProteinsInMB3 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem9 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem15 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuDimensions As System.Windows.Forms.MenuItem
    Friend WithEvents mnuRawFileMapping As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSelectExternal As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSelectExternal_Clipboard As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSelectExternalPartialMatch_Clipboard As System.Windows.Forms.MenuItem
    Friend WithEvents mnuZapQuantSpecResults 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(frmProteinList))
        Me.MainMenu1 = New System.Windows.Forms.MainMenu(Me.components)
        Me.mnuFile = New System.Windows.Forms.MenuItem
        Me.mnuOpenMascotFile = New System.Windows.Forms.MenuItem
        Me.mnuSaveProteinHitsAs = New System.Windows.Forms.MenuItem
        Me.mnuSaveSelectedProteinHits = New System.Windows.Forms.MenuItem
        Me.mnuInsertProteins = New System.Windows.Forms.MenuItem
        Me.MenuItem9 = New System.Windows.Forms.MenuItem
        Me.mnuSaveProteinsInMB3 = New System.Windows.Forms.MenuItem
        Me.MenuItem10 = New System.Windows.Forms.MenuItem
        Me.mnuRetrieveProteinSequences = New System.Windows.Forms.MenuItem
        Me.MenuItem26 = New System.Windows.Forms.MenuItem
        Me.mnuExportParseReport = New System.Windows.Forms.MenuItem
        Me.mnuExportRecalibReport = New System.Windows.Forms.MenuItem
        Me.mnuExportCorrelationReport = New System.Windows.Forms.MenuItem
        Me.mnuExportRawFilesReport = New System.Windows.Forms.MenuItem
        Me.mnuExportProteinsAndPeptides = New System.Windows.Forms.MenuItem
        Me.MenuItem2 = New System.Windows.Forms.MenuItem
        Me.mnuSaveProteinsAndPeptides = New System.Windows.Forms.MenuItem
        Me.mnuClose = New System.Windows.Forms.MenuItem
        Me.MenuItem11 = New System.Windows.Forms.MenuItem
        Me.MenuItem22 = New System.Windows.Forms.MenuItem
        Me.MenuItem21 = New System.Windows.Forms.MenuItem
        Me.mnuEditUncheck = New System.Windows.Forms.MenuItem
        Me.mnuEditCheck = New System.Windows.Forms.MenuItem
        Me.mnuEditToggleChecked = New System.Windows.Forms.MenuItem
        Me.MenuItem7 = New System.Windows.Forms.MenuItem
        Me.mnuEditSelectChecked = New System.Windows.Forms.MenuItem
        Me.mnuEditSelectAll = New System.Windows.Forms.MenuItem
        Me.mnuEditUnselectAll = New System.Windows.Forms.MenuItem
        Me.mnuEditInvertSelection = New System.Windows.Forms.MenuItem
        Me.MenuItem17 = New System.Windows.Forms.MenuItem
        Me.mnuScrollToNextSelected = New System.Windows.Forms.MenuItem
        Me.MenuItem16 = New System.Windows.Forms.MenuItem
        Me.mnuFind = New System.Windows.Forms.MenuItem
        Me.mnuView = New System.Windows.Forms.MenuItem
        Me.mnuSample = New System.Windows.Forms.MenuItem
        Me.mnuSample1 = New System.Windows.Forms.MenuItem
        Me.mnuSample2 = New System.Windows.Forms.MenuItem
        Me.mnuSample3 = New System.Windows.Forms.MenuItem
        Me.mnuSample4 = New System.Windows.Forms.MenuItem
        Me.mnuShowMascotResult = New System.Windows.Forms.MenuItem
        Me.MenuItem1 = New System.Windows.Forms.MenuItem
        Me.mnuArrangeProteins = New System.Windows.Forms.MenuItem
        Me.mnuWiffInfo = New System.Windows.Forms.MenuItem
        Me.mnuSearchStats = New System.Windows.Forms.MenuItem
        Me.mnuOptions = New System.Windows.Forms.MenuItem
        Me.mnuQuantOptions = New System.Windows.Forms.MenuItem
        Me.MenuItem15 = New System.Windows.Forms.MenuItem
        Me.mnuDimensions = New System.Windows.Forms.MenuItem
        Me.mnuRawFileMapping = New System.Windows.Forms.MenuItem
        Me.mnuAction = New System.Windows.Forms.MenuItem
        Me.mnuParseAgain = New System.Windows.Forms.MenuItem
        Me.MenuItem8 = New System.Windows.Forms.MenuItem
        Me.mnuPeptideStats = New System.Windows.Forms.MenuItem
        Me.MenuItem6 = New System.Windows.Forms.MenuItem
        Me.mnuRecalWiff = New System.Windows.Forms.MenuItem
        Me.MenuItem5 = New System.Windows.Forms.MenuItem
        Me.mnuExportToSQL2000 = New System.Windows.Forms.MenuItem
        Me.MenuItem3 = New System.Windows.Forms.MenuItem
        Me.mnuAutomation = New System.Windows.Forms.MenuItem
        Me.mnuQuantOne = New System.Windows.Forms.MenuItem
        Me.mnuScoreMS3 = New System.Windows.Forms.MenuItem
        Me.mnuScorePTM = New System.Windows.Forms.MenuItem
        Me.mnuScoreConsensus = New System.Windows.Forms.MenuItem
        Me.MenuItem24 = New System.Windows.Forms.MenuItem
        Me.mnuAddTag = New System.Windows.Forms.MenuItem
        Me.mnuDeleteAllTags = New System.Windows.Forms.MenuItem
        Me.MenuItem12 = New System.Windows.Forms.MenuItem
        Me.mnuComputeAndSetSequenceCoverage = New System.Windows.Forms.MenuItem
        Me.mnuReport = New System.Windows.Forms.MenuItem
        Me.mnuRecalibration = New System.Windows.Forms.MenuItem
        Me.mnuRecalibVisual = New System.Windows.Forms.MenuItem
        Me.MenuItem23 = New System.Windows.Forms.MenuItem
        Me.mnuRetentionTimeCorrelation = New System.Windows.Forms.MenuItem
        Me.mnuRemoveInsertedPeptides = New System.Windows.Forms.MenuItem
        Me.mnuDisplayProteinProfiles = New System.Windows.Forms.MenuItem
        Me.mnuSetConsensusProfile = New System.Windows.Forms.MenuItem
        Me.MenuItem19 = New System.Windows.Forms.MenuItem
        Me.mnuZapQuantSpecResults = New System.Windows.Forms.MenuItem
        Me.mnuRemovePeptides = New System.Windows.Forms.MenuItem
        Me.MenuItem13 = New System.Windows.Forms.MenuItem
        Me.mnuQuantChecked = New System.Windows.Forms.MenuItem
        Me.mnuMS3ScoreChecked = New System.Windows.Forms.MenuItem
        Me.MenuItem14 = New System.Windows.Forms.MenuItem
        Me.mnuQuantExternal = New System.Windows.Forms.MenuItem
        Me.mnuSelectExternal = New System.Windows.Forms.MenuItem
        Me.mnuSelectExternal_Clipboard = New System.Windows.Forms.MenuItem
        Me.mnuSelectExternalPartialMatch_Clipboard = New System.Windows.Forms.MenuItem
        Me.mnuUtility = New System.Windows.Forms.MenuItem
        Me.mnuOpenResultFileFolder = New System.Windows.Forms.MenuItem
        Me.mnuOpenRawFileFolder = New System.Windows.Forms.MenuItem
        Me.MenuItem4 = New System.Windows.Forms.MenuItem
        Me.mnuHelp = New System.Windows.Forms.MenuItem
        Me.ParserStatus = New System.Windows.Forms.StatusBar
        Me.PanelProteinsParsed = New System.Windows.Forms.StatusBarPanel
        Me.PanelProteinsInTable = New System.Windows.Forms.StatusBarPanel
        Me.PanelSecs = New System.Windows.Forms.StatusBarPanel
        Me.PanelFile = New System.Windows.Forms.StatusBarPanel
        Me.PanelStatus = New System.Windows.Forms.StatusBarPanel
        Me.OpenFileDialog1 = New System.Windows.Forms.OpenFileDialog
        Me.SaveFileDialog1 = New System.Windows.Forms.SaveFileDialog
        Me.ProgressBar1 = New System.Windows.Forms.ProgressBar
        Me.ContextMenu1 = New System.Windows.Forms.ContextMenu
        Me.mnuOpenProteinValWind = New System.Windows.Forms.MenuItem
        Me.mnuMarkAsChecked = New System.Windows.Forms.MenuItem
        Me.markAsReject = New System.Windows.Forms.MenuItem
        Me.mnuUnMarkProtein = New System.Windows.Forms.MenuItem
        Me.DisplayDBInfo = New System.Windows.Forms.MenuItem
        Me.mnuDisplaySeqandPepts = New System.Windows.Forms.MenuItem
        Me.mnuBlastProtein = New System.Windows.Forms.MenuItem
        Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components)
        Me.MainMenu2 = New System.Windows.Forms.MainMenu(Me.components)
        Me.lstProtHits = New ListViewCEBIExtended4
        CType(Me.PanelProteinsParsed, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.PanelProteinsInTable, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.PanelSecs, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.PanelFile, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.PanelStatus, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'MainMenu1
        '
        Me.MainMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuFile, Me.MenuItem11, Me.mnuView, Me.MenuItem15, Me.mnuAction, Me.mnuAutomation, Me.mnuUtility, Me.MenuItem4})
        '
        'mnuFile
        '
        Me.mnuFile.Index = 0
        Me.mnuFile.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuOpenMascotFile, Me.mnuSaveProteinHitsAs, Me.mnuSaveSelectedProteinHits, Me.mnuInsertProteins, Me.MenuItem9, Me.MenuItem10, Me.mnuRetrieveProteinSequences, Me.MenuItem26, Me.mnuExportParseReport, Me.mnuExportRecalibReport, Me.mnuExportCorrelationReport, Me.mnuExportRawFilesReport, Me.mnuExportProteinsAndPeptides, Me.MenuItem2, Me.mnuSaveProteinsAndPeptides, Me.mnuClose})
        Me.mnuFile.Text = "&File"
        '
        'mnuOpenMascotFile
        '
        Me.mnuOpenMascotFile.Enabled = False
        Me.mnuOpenMascotFile.Index = 0
        Me.mnuOpenMascotFile.Text = "&Open Mascot File"
        Me.mnuOpenMascotFile.Visible = False
        '
        'mnuSaveProteinHitsAs
        '
        Me.mnuSaveProteinHitsAs.Index = 1
        Me.mnuSaveProteinHitsAs.Text = "Save..."
        '
        'mnuSaveSelectedProteinHits
        '
        Me.mnuSaveSelectedProteinHits.Enabled = False
        Me.mnuSaveSelectedProteinHits.Index = 2
        Me.mnuSaveSelectedProteinHits.Text = "Save Special..."
        '
        'mnuInsertProteins
        '
        Me.mnuInsertProteins.Index = 3
        Me.mnuInsertProteins.Text = "Insert Proteins..."
        '
        'MenuItem9
        '
        Me.MenuItem9.Index = 4
        Me.MenuItem9.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuSaveProteinsInMB3})
        Me.MenuItem9.Text = "Legacy"
        '
        'mnuSaveProteinsInMB3
        '
        Me.mnuSaveProteinsInMB3.Index = 0
        Me.mnuSaveProteinsInMB3.Text = "Save in older format (MB3)"
        '
        'MenuItem10
        '
        Me.MenuItem10.Index = 5
        Me.MenuItem10.Text = "-"
        '
        'mnuRetrieveProteinSequences
        '
        Me.mnuRetrieveProteinSequences.Enabled = False
        Me.mnuRetrieveProteinSequences.Index = 6
        Me.mnuRetrieveProteinSequences.Text = "Retrieve protein sequences from Mascot server..."
        '
        'MenuItem26
        '
        Me.MenuItem26.Index = 7
        Me.MenuItem26.Text = "-"
        '
        'mnuExportParseReport
        '
        Me.mnuExportParseReport.Index = 8
        Me.mnuExportParseReport.Text = "Export Parsing Result..."
        '
        'mnuExportRecalibReport
        '
        Me.mnuExportRecalibReport.Index = 9
        Me.mnuExportRecalibReport.Text = "Export Recalibration Result..."
        '
        'mnuExportCorrelationReport
        '
        Me.mnuExportCorrelationReport.Index = 10
        Me.mnuExportCorrelationReport.Text = "Export Correlation of Raw Files Result..."
        '
        'mnuExportRawFilesReport
        '
        Me.mnuExportRawFilesReport.Index = 11
        Me.mnuExportRawFilesReport.Text = "Export Raw Files Information..."
        '
        'mnuExportProteinsAndPeptides
        '
        Me.mnuExportProteinsAndPeptides.Enabled = False
        Me.mnuExportProteinsAndPeptides.Index = 12
        Me.mnuExportProteinsAndPeptides.Shortcut = System.Windows.Forms.Shortcut.F2
        Me.mnuExportProteinsAndPeptides.Text = "Export &Proteins and Peptides Information..."
        '
        'MenuItem2
        '
        Me.MenuItem2.Index = 13
        Me.MenuItem2.Text = "-"
        Me.MenuItem2.Visible = False
        '
        'mnuSaveProteinsAndPeptides
        '
        Me.mnuSaveProteinsAndPeptides.Enabled = False
        Me.mnuSaveProteinsAndPeptides.Index = 14
        Me.mnuSaveProteinsAndPeptides.Shortcut = System.Windows.Forms.Shortcut.CtrlF2
        Me.mnuSaveProteinsAndPeptides.Text = "Proteins and Peptides Information (&save)..."
        Me.mnuSaveProteinsAndPeptides.Visible = False
        '
        'mnuClose
        '
        Me.mnuClose.Index = 15
        Me.mnuClose.Text = "&Close"
        '
        'MenuItem11
        '
        Me.MenuItem11.Index = 1
        Me.MenuItem11.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItem22, Me.MenuItem21, Me.mnuEditUncheck, Me.mnuEditCheck, Me.mnuEditToggleChecked, Me.MenuItem7, Me.mnuEditSelectChecked, Me.mnuEditSelectAll, Me.mnuEditUnselectAll, Me.mnuEditInvertSelection, Me.MenuItem17, Me.mnuScrollToNextSelected, Me.MenuItem16, Me.mnuFind})
        Me.MenuItem11.Text = "&Edit"
        '
        'MenuItem22
        '
        Me.MenuItem22.Enabled = False
        Me.MenuItem22.Index = 0
        Me.MenuItem22.Shortcut = System.Windows.Forms.Shortcut.CtrlX
        Me.MenuItem22.Text = "Cut"
        '
        'MenuItem21
        '
        Me.MenuItem21.Index = 1
        Me.MenuItem21.Text = "-"
        '
        'mnuEditUncheck
        '
        Me.mnuEditUncheck.Enabled = False
        Me.mnuEditUncheck.Index = 2
        Me.mnuEditUncheck.Shortcut = System.Windows.Forms.Shortcut.CtrlF6
        Me.mnuEditUncheck.Text = "&Uncheck"
        '
        'mnuEditCheck
        '
        Me.mnuEditCheck.Enabled = False
        Me.mnuEditCheck.Index = 3
        Me.mnuEditCheck.Shortcut = System.Windows.Forms.Shortcut.F6
        Me.mnuEditCheck.Text = "&Check"
        '
        'mnuEditToggleChecked
        '
        Me.mnuEditToggleChecked.Enabled = False
        Me.mnuEditToggleChecked.Index = 4
        Me.mnuEditToggleChecked.Text = "&Toogle Checked"
        '
        'MenuItem7
        '
        Me.MenuItem7.Index = 5
        Me.MenuItem7.Text = "-"
        '
        'mnuEditSelectChecked
        '
        Me.mnuEditSelectChecked.Index = 6
        Me.mnuEditSelectChecked.Shortcut = System.Windows.Forms.Shortcut.CtrlE
        Me.mnuEditSelectChecked.Text = "S&elect Checked"
        '
        'mnuEditSelectAll
        '
        Me.mnuEditSelectAll.Index = 7
        Me.mnuEditSelectAll.Shortcut = System.Windows.Forms.Shortcut.CtrlA
        Me.mnuEditSelectAll.Text = "Select &All"
        '
        'mnuEditUnselectAll
        '
        Me.mnuEditUnselectAll.Index = 8
        Me.mnuEditUnselectAll.Text = "U&nselect All"
        '
        'mnuEditInvertSelection
        '
        Me.mnuEditInvertSelection.Index = 9
        Me.mnuEditInvertSelection.Text = "&Invert Selection"
        '
        'MenuItem17
        '
        Me.MenuItem17.Index = 10
        Me.MenuItem17.Text = "-"
        '
        'mnuScrollToNextSelected
        '
        Me.mnuScrollToNextSelected.Index = 11
        Me.mnuScrollToNextSelected.Shortcut = System.Windows.Forms.Shortcut.F3
        Me.mnuScrollToNextSelected.Text = "Scroll to &Next Selected"
        '
        'MenuItem16
        '
        Me.MenuItem16.Index = 12
        Me.MenuItem16.Text = "-"
        '
        'mnuFind
        '
        Me.mnuFind.Index = 13
        Me.mnuFind.Shortcut = System.Windows.Forms.Shortcut.CtrlF
        Me.mnuFind.Text = "Find... (in protein description only)"
        '
        'mnuView
        '
        Me.mnuView.Index = 2
        Me.mnuView.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuSample, Me.mnuShowMascotResult, Me.MenuItem1, Me.mnuArrangeProteins, Me.mnuWiffInfo, Me.mnuSearchStats, Me.mnuOptions, Me.mnuQuantOptions})
        Me.mnuView.Text = "&View"
        '
        'mnuSample
        '
        Me.mnuSample.Index = 0
        Me.mnuSample.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuSample1, Me.mnuSample2, Me.mnuSample3, Me.mnuSample4})
        Me.mnuSample.Text = "Sample"
        '
        'mnuSample1
        '
        Me.mnuSample1.Index = 0
        Me.mnuSample1.Text = "Sample 1"
        '
        'mnuSample2
        '
        Me.mnuSample2.Index = 1
        Me.mnuSample2.Text = "Sample 2"
        '
        'mnuSample3
        '
        Me.mnuSample3.Index = 2
        Me.mnuSample3.Text = "Sample 3"
        '
        'mnuSample4
        '
        Me.mnuSample4.Index = 3
        Me.mnuSample4.Text = "Sample 4"
        '
        'mnuShowMascotResult
        '
        Me.mnuShowMascotResult.Enabled = False
        Me.mnuShowMascotResult.Index = 1
        Me.mnuShowMascotResult.Text = "Show Mascot Search Result"
        '
        'MenuItem1
        '
        Me.MenuItem1.Index = 2
        Me.MenuItem1.Text = "-"
        '
        'mnuArrangeProteins
        '
        Me.mnuArrangeProteins.Index = 3
        Me.mnuArrangeProteins.Text = "Arrange &Proteins"
        Me.mnuArrangeProteins.Visible = False
        '
        'mnuWiffInfo
        '
        Me.mnuWiffInfo.Enabled = False
        Me.mnuWiffInfo.Index = 4
        Me.mnuWiffInfo.Text = "Wiff file info"
        Me.mnuWiffInfo.Visible = False
        '
        'mnuSearchStats
        '
        Me.mnuSearchStats.Enabled = False
        Me.mnuSearchStats.Index = 5
        Me.mnuSearchStats.Text = "Search stats"
        Me.mnuSearchStats.Visible = False
        '
        'mnuOptions
        '
        Me.mnuOptions.Enabled = False
        Me.mnuOptions.Index = 6
        Me.mnuOptions.Text = "Options..."
        Me.mnuOptions.Visible = False
        '
        'mnuQuantOptions
        '
        Me.mnuQuantOptions.Enabled = False
        Me.mnuQuantOptions.Index = 7
        Me.mnuQuantOptions.Text = "Quant Options..."
        Me.mnuQuantOptions.Visible = False
        '
        'MenuItem15
        '
        Me.MenuItem15.Index = 3
        Me.MenuItem15.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuDimensions, Me.mnuRawFileMapping})
        Me.MenuItem15.Text = "E&xperiment"
        '
        'mnuDimensions
        '
        Me.mnuDimensions.Index = 0
        Me.mnuDimensions.Text = "&Dimensions..."
        '
        'mnuRawFileMapping
        '
        Me.mnuRawFileMapping.Index = 1
        Me.mnuRawFileMapping.Text = "Raw File &Mapping..."
        '
        'mnuAction
        '
        Me.mnuAction.Index = 4
        Me.mnuAction.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuParseAgain, Me.MenuItem8, Me.mnuPeptideStats, Me.MenuItem6, Me.mnuRecalWiff, Me.MenuItem5, Me.mnuExportToSQL2000, Me.MenuItem3})
        Me.mnuAction.Text = "&Action"
        '
        'mnuParseAgain
        '
        Me.mnuParseAgain.Enabled = False
        Me.mnuParseAgain.Index = 0
        Me.mnuParseAgain.Text = "Parse again"
        '
        'MenuItem8
        '
        Me.MenuItem8.Enabled = False
        Me.MenuItem8.Index = 1
        Me.MenuItem8.Text = "Report correlations"
        Me.MenuItem8.Visible = False
        '
        'mnuPeptideStats
        '
        Me.mnuPeptideStats.Index = 2
        Me.mnuPeptideStats.Text = "Peptide Stats..."
        '
        'MenuItem6
        '
        Me.MenuItem6.Index = 3
        Me.MenuItem6.Text = "-"
        '
        'mnuRecalWiff
        '
        Me.mnuRecalWiff.Index = 4
        Me.mnuRecalWiff.Text = "Recalibrate wiff"
        Me.mnuRecalWiff.Visible = False
        '
        'MenuItem5
        '
        Me.MenuItem5.Index = 5
        Me.MenuItem5.Text = "-"
        Me.MenuItem5.Visible = False
        '
        'mnuExportToSQL2000
        '
        Me.mnuExportToSQL2000.Enabled = False
        Me.mnuExportToSQL2000.Index = 6
        Me.mnuExportToSQL2000.Text = "Export to SQL DB"
        Me.mnuExportToSQL2000.Visible = False
        '
        'MenuItem3
        '
        Me.MenuItem3.Index = 7
        Me.MenuItem3.Text = "Export to database"
        '
        'mnuAutomation
        '
        Me.mnuAutomation.Index = 5
        Me.mnuAutomation.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuQuantOne, Me.mnuScoreMS3, Me.mnuScorePTM, Me.mnuScoreConsensus, Me.MenuItem24, Me.mnuAddTag, Me.mnuDeleteAllTags, Me.MenuItem12, Me.mnuComputeAndSetSequenceCoverage, Me.mnuReport, Me.mnuRecalibration, Me.mnuRecalibVisual, Me.MenuItem23, Me.mnuRetentionTimeCorrelation, Me.mnuRemoveInsertedPeptides, Me.mnuDisplayProteinProfiles, Me.mnuSetConsensusProfile, Me.MenuItem19, Me.mnuZapQuantSpecResults, Me.mnuRemovePeptides, Me.MenuItem13, Me.mnuQuantChecked, Me.mnuMS3ScoreChecked, Me.MenuItem14, Me.mnuQuantExternal, Me.mnuSelectExternal, Me.mnuSelectExternal_Clipboard, Me.mnuSelectExternalPartialMatch_Clipboard})
        Me.mnuAutomation.Text = "Auto&mation"
        '
        'mnuQuantOne
        '
        Me.mnuQuantOne.Enabled = False
        Me.mnuQuantOne.Index = 0
        Me.mnuQuantOne.Shortcut = System.Windows.Forms.Shortcut.F7
        Me.mnuQuantOne.Text = "&Quantitate"
        '
        'mnuScoreMS3
        '
        Me.mnuScoreMS3.Enabled = False
        Me.mnuScoreMS3.Index = 1
        Me.mnuScoreMS3.Shortcut = System.Windows.Forms.Shortcut.F8
        Me.mnuScoreMS3.Text = "Score MS&3"
        '
        'mnuScorePTM
        '
        Me.mnuScorePTM.Enabled = False
        Me.mnuScorePTM.Index = 2
        Me.mnuScorePTM.Shortcut = System.Windows.Forms.Shortcut.CtrlF9
        Me.mnuScorePTM.Text = "Score &PTM - broader"
        '
        'mnuScoreConsensus
        '
        Me.mnuScoreConsensus.Enabled = False
        Me.mnuScoreConsensus.Index = 3
        Me.mnuScoreConsensus.Text = "Score consensus"
        '
        'MenuItem24
        '
        Me.MenuItem24.Index = 4
        Me.MenuItem24.Text = "-"
        '
        'mnuAddTag
        '
        Me.mnuAddTag.Enabled = False
        Me.mnuAddTag.Index = 5
        Me.mnuAddTag.Shortcut = System.Windows.Forms.Shortcut.F11
        Me.mnuAddTag.Text = "Add tags..."
        '
        'mnuDeleteAllTags
        '
        Me.mnuDeleteAllTags.Enabled = False
        Me.mnuDeleteAllTags.Index = 6
        Me.mnuDeleteAllTags.Text = "Delete tags"
        '
        'MenuItem12
        '
        Me.MenuItem12.Index = 7
        Me.MenuItem12.Text = "-"
        '
        'mnuComputeAndSetSequenceCoverage
        '
        Me.mnuComputeAndSetSequenceCoverage.Enabled = False
        Me.mnuComputeAndSetSequenceCoverage.Index = 8
        Me.mnuComputeAndSetSequenceCoverage.Text = "Compute and Set Protein Sequence Coverage"
        '
        'mnuReport
        '
        Me.mnuReport.Enabled = False
        Me.mnuReport.Index = 9
        Me.mnuReport.Text = "Make MS-MS spectra and Peptide Information Report (e.g. for your MCP paper... ).." & _
            "."
        '
        'mnuRecalibration
        '
        Me.mnuRecalibration.Enabled = False
        Me.mnuRecalibration.Index = 10
        Me.mnuRecalibration.Text = "Do &Recalibration and validation"
        '
        'mnuRecalibVisual
        '
        Me.mnuRecalibVisual.Enabled = False
        Me.mnuRecalibVisual.Index = 11
        Me.mnuRecalibVisual.Text = "Display Recalibration Visualisation..."
        '
        'MenuItem23
        '
        Me.MenuItem23.Index = 12
        Me.MenuItem23.Text = "-"
        '
        'mnuRetentionTimeCorrelation
        '
        Me.mnuRetentionTimeCorrelation.Enabled = False
        Me.mnuRetentionTimeCorrelation.Index = 13
        Me.mnuRetentionTimeCorrelation.Text = "Do Retention Time Correlation"
        '
        'mnuRemoveInsertedPeptides
        '
        Me.mnuRemoveInsertedPeptides.Enabled = False
        Me.mnuRemoveInsertedPeptides.Index = 14
        Me.mnuRemoveInsertedPeptides.Text = "Remove Peptides Inserted by Retention Time Correlation"
        '
        'mnuDisplayProteinProfiles
        '
        Me.mnuDisplayProteinProfiles.Enabled = False
        Me.mnuDisplayProteinProfiles.Index = 15
        Me.mnuDisplayProteinProfiles.Shortcut = System.Windows.Forms.Shortcut.F12
        Me.mnuDisplayProteinProfiles.Text = "Display Protein Pro&files"
        '
        'mnuSetConsensusProfile
        '
        Me.mnuSetConsensusProfile.Enabled = False
        Me.mnuSetConsensusProfile.Index = 16
        Me.mnuSetConsensusProfile.Text = "Set Consensus Profile..."
        '
        'MenuItem19
        '
        Me.MenuItem19.Index = 17
        Me.MenuItem19.Text = "-"
        '
        'mnuZapQuantSpecResults
        '
        Me.mnuZapQuantSpecResults.Enabled = False
        Me.mnuZapQuantSpecResults.Index = 18
        Me.mnuZapQuantSpecResults.Text = "Zap intermediate quantitation results"
        '
        'mnuRemovePeptides
        '
        Me.mnuRemovePeptides.Enabled = False
        Me.mnuRemovePeptides.Index = 19
        Me.mnuRemovePeptides.Text = "Remove Peptides for &Good"
        '
        'MenuItem13
        '
        Me.MenuItem13.Index = 20
        Me.MenuItem13.Text = "-"
        '
        'mnuQuantChecked
        '
        Me.mnuQuantChecked.Index = 21
        Me.mnuQuantChecked.Shortcut = System.Windows.Forms.Shortcut.CtrlF10
        Me.mnuQuantChecked.Text = "Quantitate &checked - invisible"
        Me.mnuQuantChecked.Visible = False
        '
        'mnuMS3ScoreChecked
        '
        Me.mnuMS3ScoreChecked.Index = 22
        Me.mnuMS3ScoreChecked.Text = "MS3 score checked - invisible"
        Me.mnuMS3ScoreChecked.Visible = False
        '
        'MenuItem14
        '
        Me.MenuItem14.Index = 23
        Me.MenuItem14.Text = "-"
        Me.MenuItem14.Visible = False
        '
        'mnuQuantExternal
        '
        Me.mnuQuantExternal.Index = 24
        Me.mnuQuantExternal.Text = "Quantify from external &list"
        '
        'mnuSelectExternal
        '
        Me.mnuSelectExternal.Enabled = False
        Me.mnuSelectExternal.Index = 25
        Me.mnuSelectExternal.Text = "Select from external list"
        '
        'mnuSelectExternal_Clipboard
        '
        Me.mnuSelectExternal_Clipboard.Index = 26
        Me.mnuSelectExternal_Clipboard.Text = "Select proteins using external list - exact match (in clipboard)"
        '
        'mnuSelectExternalPartialMatch_Clipboard
        '
        Me.mnuSelectExternalPartialMatch_Clipboard.Index = 27
        Me.mnuSelectExternalPartialMatch_Clipboard.Text = "Select proteins using external list - partial matrch (in clipboard)"
        '
        'mnuUtility
        '
        Me.mnuUtility.Index = 6
        Me.mnuUtility.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuOpenResultFileFolder, Me.mnuOpenRawFileFolder})
        Me.mnuUtility.Text = "Utility"
        '
        'mnuOpenResultFileFolder
        '
        Me.mnuOpenResultFileFolder.Index = 0
        Me.mnuOpenResultFileFolder.Text = "Open Mascot Result File Folder"
        '
        'mnuOpenRawFileFolder
        '
        Me.mnuOpenRawFileFolder.Index = 1
        Me.mnuOpenRawFileFolder.Text = "Open Raw File Folder"
        '
        'MenuItem4
        '
        Me.MenuItem4.Index = 7
        Me.MenuItem4.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuHelp})
        Me.MenuItem4.Text = "&Help"
        '
        'mnuHelp
        '
        Me.mnuHelp.Enabled = False
        Me.mnuHelp.Index = 0
        Me.mnuHelp.Text = "Help"
        '
        'ParserStatus
        '
        Me.ParserStatus.Location = New System.Drawing.Point(0, 401)
        Me.ParserStatus.Name = "ParserStatus"
        Me.ParserStatus.Panels.AddRange(New System.Windows.Forms.StatusBarPanel() {Me.PanelProteinsParsed, Me.PanelProteinsInTable, Me.PanelSecs, Me.PanelFile, Me.PanelStatus})
        Me.ParserStatus.ShowPanels = True
        Me.ParserStatus.Size = New System.Drawing.Size(1048, 24)
        Me.ParserStatus.TabIndex = 7
        '
        'PanelProteinsParsed
        '
        Me.PanelProteinsParsed.Name = "PanelProteinsParsed"
        Me.PanelProteinsParsed.Text = "Proteins parsed: "
        Me.PanelProteinsParsed.Width = 110
        '
        'PanelProteinsInTable
        '
        Me.PanelProteinsInTable.Name = "PanelProteinsInTable"
        Me.PanelProteinsInTable.Text = "In table: "
        Me.PanelProteinsInTable.Width = 90
        '
        'PanelSecs
        '
        Me.PanelSecs.Name = "PanelSecs"
        Me.PanelSecs.Text = "Secs: "
        Me.PanelSecs.Width = 60
        '
        'PanelFile
        '
        Me.PanelFile.Name = "PanelFile"
        Me.PanelFile.Text = "File: "
        Me.PanelFile.Width = 150
        '
        'PanelStatus
        '
        Me.PanelStatus.Name = "PanelStatus"
        Me.PanelStatus.Width = 800
        '
        'SaveFileDialog1
        '
        Me.SaveFileDialog1.FileName = "doc1"
        '
        'ProgressBar1
        '
        Me.ProgressBar1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.ProgressBar1.Location = New System.Drawing.Point(0, 384)
        Me.ProgressBar1.Name = "ProgressBar1"
        Me.ProgressBar1.Size = New System.Drawing.Size(1048, 15)
        Me.ProgressBar1.TabIndex = 8
        '
        'ContextMenu1
        '
        Me.ContextMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuOpenProteinValWind, Me.mnuMarkAsChecked, Me.markAsReject, Me.mnuUnMarkProtein, Me.DisplayDBInfo, Me.mnuDisplaySeqandPepts, Me.mnuBlastProtein})
        '
        'mnuOpenProteinValWind
        '
        Me.mnuOpenProteinValWind.Index = 0
        Me.mnuOpenProteinValWind.Text = "Open Protein Validation Window"
        '
        'mnuMarkAsChecked
        '
        Me.mnuMarkAsChecked.Index = 1
        Me.mnuMarkAsChecked.Text = "Mark protein as validated"
        '
        'markAsReject
        '
        Me.markAsReject.Index = 2
        Me.markAsReject.Text = "Mark protein as rejected"
        '
        'mnuUnMarkProtein
        '
        Me.mnuUnMarkProtein.Index = 3
        Me.mnuUnMarkProtein.Text = "Unmark protein"
        '
        'DisplayDBInfo
        '
        Me.DisplayDBInfo.Enabled = False
        Me.DisplayDBInfo.Index = 4
        Me.DisplayDBInfo.Text = "Display database info"
        '
        'mnuDisplaySeqandPepts
        '
        Me.mnuDisplaySeqandPepts.Enabled = False
        Me.mnuDisplaySeqandPepts.Index = 5
        Me.mnuDisplaySeqandPepts.Text = "Display sequence"
        '
        'mnuBlastProtein
        '
        Me.mnuBlastProtein.Enabled = False
        Me.mnuBlastProtein.Index = 6
        Me.mnuBlastProtein.Text = "Blast this protein"
        '
        'lstProtHits
        '
        Me.lstProtHits.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.lstProtHits.CheckBoxes = True
        Me.lstProtHits.ContextMenu = Me.ContextMenu1
        Me.lstProtHits.FullRowSelect = True
        Me.lstProtHits.GridLines = True
        Me.lstProtHits.HideSelection = False
        Me.lstProtHits.Location = New System.Drawing.Point(0, 0)
        Me.lstProtHits.Name = "lstProtHits"
        Me.lstProtHits.Size = New System.Drawing.Size(1048, 384)
        Me.lstProtHits.TabIndex = 11
        Me.lstProtHits.UseCompatibleStateImageBehavior = False
        Me.lstProtHits.View = System.Windows.Forms.View.Details
        '
        'frmProteinList
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(1048, 425)
        Me.Controls.Add(Me.lstProtHits)
        Me.Controls.Add(Me.ProgressBar1)
        Me.Controls.Add(Me.ParserStatus)
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.Menu = Me.MainMenu1
        Me.Name = "frmProteinList"
        Me.Text = "xx"
        CType(Me.PanelProteinsParsed, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.PanelProteinsInTable, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.PanelSecs, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.PanelFile, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.PanelStatus, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub

#End Region


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub New( _
      ByRef anInParentForm As frmMainForm, _
      ByRef anApp As quantApplication, _
      ByVal aMascotParsOptions As OptionsStruct2, _
      ByVal anInExperimentSettings2 As experimentSettingsStruct)

        'Why no Init() for this object? No need to re-initialise?

        MyBase.New()

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

        'Changed PM_UNNECESSARY_CODE 2006-03-20
        ''Changed PM_USE_DEFAULT_OPTIONS_BUG 2004-02-09. Moved here
        ''from frmProteinList_Load(). Why do we need this at
        ''all when the default is set in defaultOptions()  ????.
        'With mOptions
        '    .scoreA = 33
        '    .scoreB = 25
        '    .scoreC = 20
        '    .dontShowIPI = False
        '    .dontShowMosquito = False
        '    .dontShowProtWithNoPeptInABC = True
        '    .inclBoldRedPepts = True
        '    .inclLightRedPepts = True
        '    .inclRedPeptsIfCheckedOnly = True
        '    .inclBoldBlackPeptsIfChecked = False
        '    .inclBoldBlackPepts = False
        '    .inclPeptsInParens = False
        '    .protDefaultValidation = 60
        '    .peptDefaultValidation = 25
        'End With

        mOptions = aMascotParsOptions 'This is needed because we are
        '  going to pass it on to frmProtValidation/frmProteinValidation.vb
        '  in openProtValForm().

        'Changed PM_HIGHER_LEVEL_PROCESSING 2008-09-04
        'Make a deep copy????? We have reference members in experimentSettingsStruct...
        Trace.Assert(Not anInExperimentSettings2.JAspace Is Nothing, _
          "PIL ASSERT. anInExperimentSettings2.JAspace is nothing. " & _
          "In constructor of frmProteinList.")
        Trace.Assert(Not anInExperimentSettings2.rawFileMapping3 Is Nothing, _
          "PIL ASSERT. anInExperimentSettings2.rawFileMapping3 is nothing. " & _
          "In constructor of frmProteinList.")

        mExperimentSettings = anInExperimentSettings2

        'Changed PM_SAVE_ALLRECALIB_MB4 2008-11-21
        mRecalibrator = Nothing 'To be explicit. Either assigned
        '  in OpenParsedProteinsEtc() or in setParsedProteinList() (conditionally).
        '  Loading from file and during parsing, respectively.

        'Changed PM_VARIABLE_XIC_WINDOW 2003-11-27
        mApplication = anApp

        'Changed PM_REPORTS 2006-08-15
        mParentForm = anInParentForm
        mParseReport = New SDUPstructuredReport

        'Add any initialization after the InitializeComponent() call

        'Later: move our own init code into an Init function, among others
        '       to separate our own members from the GUI/auto-generated.


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


        mAvoidHandlingProteinCheckedEvent = False

        mProteinHitNumber2dataIndex = Nothing 'Lazy instantiation

        'Changed PM_PROTEIN_TAGS 2008-10-29
        mTaggingForm = Nothing
        mSsb = New StringBuilder(100)

        'Changed PM_PCP_CONSENSUS_PROFILE 2008-11-05
        mConsensus = Nothing

        'Changed PM_PROTEIN_TAGS_USERDEFINED 2008-11-07
        mCurrentTags = Nothing 'Set later...


        'Changed PM_MEMORY_EFFICIENCY 2008-11-12.
        'Note: this would also work:
        '        new List<string>(){"abc","def","xyz"};
        '

        'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
        ''Orig:
        ''  Dim formatStringsArr() As String = _
        ''    {"0.0", "0.00", "0.000", "0.0000"}
        'Dim tempArr() As String = _
        '  {"0.00", "0.00", "0.00", "0.0"} 'For consensus score, ratio,
        ''  Standard deviation for ratio and relative error - in that order....
        Dim tempArr3() As String = _
          {"0.00", "0", "0", "0.00", "0.00", "0.0"} 'For consensus score,
        '  non-zero points, within consensus, ratio,
        '  Standard deviation for ratio and relative error - in that order....
        '
        'Note: temp in name because it should be possible to
        '      assign mProteinFormatStrings3 directly...

        mProteinFormatStrings3 = tempArr3 'How can the initialisation
        '  be made to work directly????

        'How can it work?
        'mProteinFormatStrings2 = _
        '  new List(Of String) {"0.00", "0.00", "0.00", "0.0"}

        'Changed PM_GENERALISED_QUANT_MODE 2003-12-07. Note: new() was
        '  in definition.
        mMascotResultParser = New MascotResultParser(anApp, mParseReport)

        'Changed PM_FLEXIBLE_RAWFILE_LOC 2007-06-12
        mRawfile2RealRawFileHash = New Dictionary(Of String, String)

        'Changed PM_DOUBLE_RETURN_KEY 2007-09-08
        mKeyObserver = New SDUPkeyObserver


        'Changed PM_REFACTOR 2005-03-01
        ''Changed PM_REFACTOR 2004-02-04
        'mColumnProteinMap = New Hashtable
        mColumnMapper = _
          New listviewColumnMapper( _
            DirectCast(lstProtHits, System.Windows.Forms.ListView))

        mListViewColumnSorter = _
          New ListViewColumnSorter(mColumnMapper)

        'Changed PM_REFACTOR 2006-10-12
        'Dim addTripleEncodingColumns As Boolean = _
        '  mApplication.isTripleEncoding(aMasParsOptions.quantModeCode)
        If True Then
            Dim quantitationModesObject As QuantitationModes_moreGeneral = _
              mApplication.getQuantModes()
            Dim curQuantMode As generalisedQuantModeStructure = _
              quantitationModesObject.getQuantitationMode( _
                aMascotParsOptions.quantModeCode)
            mDishes = _
              curQuantMode.dishes_StartingFromDish2.Count + 1
        End If
        setProteinListViewColumns(mDishes, mApplication)

        'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-29. Now set globally,
        '  in defaultOptions().
        ' 'Defaults. For now: per parse. But it should be saved. Either with
        ' '  the parse (MB3). Or be global for the program.
        ' If True Then
        '     mProteinAndPeptidesFilter2.includePeptides = True
        ' 
        '     mProteinAndPeptidesFilter2.includeProteinInformation = False
        ' End If

        mnuScorePTM.Visible = shv1b

        mnuScoreConsensus.Visible = shv2
        mnuDisplayProteinProfiles.Visible = shv2
        mnuSetConsensusProfile.Visible = shv2

        'Visual sorting.
        If True Then

            'Changed PM_SORT_BY_SELECTION_AND_CHECKED 2008-12-09
            'Sort by selected. Only to get it into the Sort By items
            mListViewColumnSorter.addColumnPrimaryKey( _
              specialSortKeyEnum.enumBySelected, _
              datatypeEnum.enumText, _
              sortingDirectionEnum.enumDescendingSort, _
              True)
            mListViewColumnSorter.addColumnSecondaryKey( _
              proteinColumnEnum.enumProteinHitNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort)

            'Changed PM_SORT_BY_SELECTION_AND_CHECKED 2008-12-09
            'Sort by checked. Only to get it into the Sort By items
            mListViewColumnSorter.addColumnPrimaryKey( _
              specialSortKeyEnum.enumByChecked, _
              datatypeEnum.enumText, _
              sortingDirectionEnum.enumDescendingSort, _
              True)
            mListViewColumnSorter.addColumnSecondaryKey( _
              proteinColumnEnum.enumProteinHitNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort)


            'Hit number.
            '  Should be unique. Only the primary key should be needed. Yes!
            mListViewColumnSorter.addColumnPrimaryKey( _
              proteinColumnEnum.enumProteinHitNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort, _
              True)

            'Accession number.
            mListViewColumnSorter.addColumnPrimaryKey( _
              proteinColumnEnum.enumProteinAccessionNumber, _
              datatypeEnum.enumText, _
              sortingDirectionEnum.enumAscendingSort, _
              False)

            'Changed PM_PROTEIN_TAGS 2008-10-29
            'Primary tag.
            mListViewColumnSorter.addColumnPrimaryKey( _
              proteinColumnEnum.enumPrimaryProteinTag2, _
              datatypeEnum.enumText, _
              sortingDirectionEnum.enumDescendingSort, _
              True) 'Note: descending to get proteins 
            '              with no tags at the end.
            mListViewColumnSorter.addColumnSecondaryKey( _
              proteinColumnEnum.enumProteinScore, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumDescendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              proteinColumnEnum.enumProteinHitNumber, _
                  datatypeEnum.enumInteger, _
                  sortingDirectionEnum.enumAscendingSort)

            'Number of peptides.
            mListViewColumnSorter.addColumnPrimaryKey( _
              proteinColumnEnum.enumNumberOfPeptides, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumDescendingSort, _
              False)
            mListViewColumnSorter.addColumnSecondaryKey( _
              proteinColumnEnum.enumProteinScore, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumDescendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              proteinColumnEnum.enumProteinHitNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort)

            'Changed PM_QUANTCOLUMNS_SORT 2007-04-03
            If True Then
                Dim keyBase As Integer = -5
                Dim n As Integer 'Is selector for type: ratio, stddev
                '  for ratio, and relative error.

                'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                'Changed PM_CONSENSUSSCORE_ALLDISHES 2008-11-11
                'For n = 0 To 2
                'For n = 0 To 3
                For n = 0 To 5

                    'Changed PM_COLUMNSORT_BY_KEYBOARD 2008-11-07
                    Dim useMenuKeyBoardShortcut As Boolean = False

                    Dim lastIndex As Integer = mDishes - 1
                    Dim dish As Integer
                    For dish = 0 To lastIndex

                        Dim dataTypeSpec As datatypeEnum = _
                          datatypeEnum.enumDecimalNumber 'For most. Is overriden
                        '   for integer columns.

                        Select Case n

                            'Changed PM_CONSENSUSSCORE_ALLDISHES 2008-11-11. 
                            'Note that this new one has been placed first; shifting
                            'the others.
                            Case 0 'Consensus score.
                                keyBase = _
                                  proteinColumnEnum.enumConsensusScoreBaseNumber2
                                useMenuKeyBoardShortcut = True

                            Case 1 'Number of non-zero points in protein profile.
                                'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                                keyBase = _
                                  proteinColumnEnum.enumConsensusNonZeroPoints
                                dataTypeSpec = datatypeEnum.enumInteger


                            Case 2 'Number of points within consensus in protein profile.
                                'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                                keyBase = _
                                  proteinColumnEnum.enumPointsWithinConsensus
                                dataTypeSpec = datatypeEnum.enumInteger

                            Case 3 'Ratio
                                keyBase = proteinColumnEnum.enumRatioBaseNumber3
                                useMenuKeyBoardShortcut = True

                            Case 4 'Std. for ratio
                                keyBase = proteinColumnEnum.enumRatioStdDevBaseNumber3

                            Case 5 'Intensity
                                keyBase = proteinColumnEnum.enumRatioRelErrBaseNumber4

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

                        Dim key2 As Integer = keyBase + dish

                        'Changed PM_COLUMNSORT_BY_KEYBOARD 2008-11-07
                        If useMenuKeyBoardShortcut Then
                            If dish = 0 Then
                                useMenuKeyBoardShortcut = False
                            End If
                        End If

                        'Changed PM_REFACTOR 2008-11-06
                        'Descending because most values are 0.0 and the interesting
                        'would end up at the end of the list. It is the initially
                        'direction anyway so it is not that important.
                        mListViewColumnSorter.addColumnPrimaryKey( _
                          key2, _
                          dataTypeSpec, _
                          sortingDirectionEnum.enumDescendingSort, _
                          useMenuKeyBoardShortcut)

                        'Secondary keys:
                        mListViewColumnSorter.addColumnSecondaryKey( _
                          proteinColumnEnum.enumProteinHitNumber, _
                          datatypeEnum.enumInteger, _
                          sortingDirectionEnum.enumAscendingSort)
                    Next 'dish
                Next n
            End If 'Block, quant columns.

            'Protein score.
            mListViewColumnSorter.addColumnPrimaryKey( _
              proteinColumnEnum.enumProteinScore, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumDescendingSort, _
              True)
            mListViewColumnSorter.addColumnSecondaryKey( _
              proteinColumnEnum.enumNumberOfPeptides, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumDescendingSort)
            mListViewColumnSorter.addColumnSecondaryKey( _
              proteinColumnEnum.enumProteinHitNumber, _
                  datatypeEnum.enumInteger, _
                  sortingDirectionEnum.enumAscendingSort)

            'Protein mass
            mListViewColumnSorter.addColumnPrimaryKey( _
              proteinColumnEnum.enumProteinMass, _
              datatypeEnum.enumDecimalNumber, _
              sortingDirectionEnum.enumAscendingSort, _
              True)
            mListViewColumnSorter.addColumnSecondaryKey( _
              proteinColumnEnum.enumProteinHitNumber, _
              datatypeEnum.enumInteger, _
              sortingDirectionEnum.enumAscendingSort)
        End If 'Block, visual sorting.

        'Changed PM_FIND 2006-07-28
        mFindParameters.initialised = False

        'Changed PM_REFACTOR 2007-01-08
        mMultipleRawFilesHandling2 = Nothing 'Just in case.

        'Changed PM_CLOSEWARNING 2004-04-21
        mDirty = False

        'Changed PM_DIRTY_ALWAYS 2007-09-10
        mDirty = True 'Now always, instead of only when the 
        '  protein validation window has been opened. The long 
        '  term solution would be to set it only when there is 
        '  change. E.g. after a parse, but not immediately 
        '  after an MB3 file has been opened.

        'Changed PM_RETCORR_ANYTIME 2006-10-26
        If True Then
            mRetCorrParameters.retentionTimeType = _
              retentionTimeTypeEnum.enumLCprofileCentroid
        End If

        'Changed PM_TWOLEVEL_WINDOWNUMBERING_PREFIX 2008-08-21
        mParseIDnumber = anApp.getUniqueNumberPlus()

        'Changed PM_VERSION_INFO 2007-04-19
        'Note: alternatively we could wait until
        'createMultipleRawFilesHandlingObject() as this function is
        'always called. And we could overwrite without appending.
        '
        'Window title for this window, Protein List:
        Me.Text = _
          "#" & mParseIDnumber & ". " & _
          AppConstants.LONG_APP & " " & _
          quantApplication.versionString_withDate() & _
          ". Protein List."
    End Sub 'New


    'Form overrides dispose to clean up the component list.
    'd$  <summary>
    'd$  Summary of Dispose.
    'd$  </summary>
    'd$  <param name="disposing"></param>
    'd$
    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


    'Changed PM_REFACTOR 2004-02-04
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub setProteinListViewColumns( _
      ByVal aSILACdishes As Integer, _
      ByRef anApplication As quantApplication)

        lstProtHits.Columns.Clear()

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


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



        'Note: this one MUST be the first one...
        mColumnMapper.newColumn("Hit", 43, _
          proteinColumnEnum.enumProteinHitNumber, _
          numberAlignment, False)

        'Changed PM_SORT_BY_SELECTION_AND_CHECKED 2008-12-09
        mColumnMapper.newColumn("Selected", 1, _
          specialSortKeyEnum.enumBySelected, _
          HorizontalAlignment.Left, True)
        mColumnMapper.newColumn("Checked", 1, _
          specialSortKeyEnum.enumByChecked, _
          HorizontalAlignment.Left, True)


        mColumnMapper.newColumn("Accession number", 76 + 14, _
          proteinColumnEnum.enumProteinAccessionNumber, _
          HorizontalAlignment.Left, False)

        'Changed PM_PROTEIN_TAGS 2008-10-29
        mColumnMapper.newColumn("Primary tag", 80, _
          proteinColumnEnum.enumPrimaryProteinTag2, _
          HorizontalAlignment.Left, False)

        'Now one per dish...
        ''Changed PM_PROTEIN_TAGS 2008-10-29
        'mColumnMapper.newColumn("Consensus score", 100, _
        '  proteinColumnEnum.enumConsensusScore, _
        '  HorizontalAlignment.Left)


        'Changed PM_PROTEINLISTCOLUMNS_ORDER 2006-07-28. Moved up
        '  here (from the end).
        mColumnMapper.newColumn("Description", 514 - 450, _
          proteinColumnEnum.enumProteinDescription2, _
          HorizontalAlignment.Left, False)

        'These 2 moved to here...
        mColumnMapper.newColumn("# Pepts", 50, _
          proteinColumnEnum.enumNumberOfPeptides, _
          numberAlignment, False)

        'Changed PM_SEQUENCE_COVERAGE 2008-04-15
        mColumnMapper.newColumn("Coverage", 30, _
          proteinColumnEnum.enumSequenceCoverage, _
          numberAlignment, False)

        If True Then
            Dim quantityString As String = Nothing
            Dim quantityString2 As String = Nothing
            Dim keyBase As Integer = -5

            Dim n As Integer 'Is selector for type: ratio, stddev
            '  for ratio, and relative error.

            Dim defaultWidth As Integer = 40

            'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
            ''Changed PM_CONSENSUSSCORE_ALLDISHES 2008-11-11.
            ''For n = 0 To 2
            'For n = 0 To 3
            For n = 0 To 5

                Dim lastIndex As Integer = aSILACdishes - 1
                Dim dish As Integer
                For dish = 0 To lastIndex

                    Dim dishOneBased As Integer = dish + 1

                    Dim pWidth As Integer = defaultWidth
                    Dim doAdd As Boolean = True

                    Select Case n

                        'Changed PM_CONSENSUSSCORE_ALLDISHES 2008-11-11. 
                        Case 0 'Consensus profile.
                            quantityString = "Consensus score "
                            quantityString2 = ""
                            keyBase = _
                              proteinColumnEnum.enumConsensusScoreBaseNumber2

                            ''Changed PM_NARROW_ONEOVERONE_COLUMNS 2008-11-27. Now
                            ''  for all.
                            ''If dish = 0 Then
                            ''    pWidth = 12
                            ''Else
                            ''    pWidth = 130
                            ''End If
                            ''pWidth = 130
                            pWidth = 130 - 33 + 5
                            doAdd = shv2

                        Case 1 'Number of non-zero points in protein profile.
                            'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                            quantityString = "Non-zero "
                            quantityString2 = ""
                            keyBase = _
                              proteinColumnEnum.enumConsensusNonZeroPoints
                            doAdd = shv2

                        Case 2 'Number of points within consensus in protein profile.
                            'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                            quantityString = "Within "
                            quantityString2 = ""
                            keyBase = _
                              proteinColumnEnum.enumPointsWithinConsensus
                            doAdd = shv2

                        Case 3 'Ratio
                            quantityString = ""
                            quantityString2 = "/1"
                            keyBase = proteinColumnEnum.enumRatioBaseNumber3
                        Case 4 'Std. for ratio
                            quantityString = "StDev "
                            quantityString2 = "/1"
                            keyBase = proteinColumnEnum.enumRatioStdDevBaseNumber3

                        Case 5 'Intensity
                            quantityString = "Rel Err "
                            quantityString2 = " [%]"
                            keyBase = proteinColumnEnum.enumRatioRelErrBaseNumber4
                        Case Else
                            Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
                    End Select

                    If doAdd Then
                        'Changed PM_NARROW_ONEOVERONE_COLUMNS 2008-11-27. Now for 
                        '  all 1/1 columns.
                        If dish = 0 Then
                            pWidth = 12
                        End If

                        Dim key2 As Integer = keyBase + dish
                        Dim header As String = _
                          quantityString & dishOneBased & quantityString2
                        mColumnMapper.newColumn(header, pWidth, key2, _
                        numberAlignment, False)
                    End If

                Next dish
            Next 'Selector
        End If

        mColumnMapper.newColumn("Score", 43, _
          proteinColumnEnum.enumProteinScore, _
          numberAlignment, False)

        mColumnMapper.newColumn("Mass [kDa]", 68, _
          proteinColumnEnum.enumProteinMass, _
          numberAlignment, False)
    End Sub 'setProteinListViewColumns()


    'Changed PM_REFACTOR 2004-09-07
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub saveOffAssoc( _
      ByVal aMascotWiffFileAss As MascotWiffAssociation, _
      ByVal aSampleNum As Integer)

        'Populate wiff file info object.
        mWiffFile.MascotFilePath = aMascotWiffFileAss.getMascotFileStr()
        mWiffFile.sampleNumberInRawFile = aSampleNum 'default

        'Changed PM_STRANGE_CODE_DISABLED 2006-11-15
        'mWiffFileStr = aMascotWiffFileAss.getWiffFileStr()
        mWiffFile.rawFilePath = aMascotWiffFileAss.getWiffFileStr()
    End Sub 'saveOffAssoc


    'Changed PM_REFACTOR 2007-01-08
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub createMultipleRawFilesHandlingObject(ByVal aSampleNum As Integer)

        'Use the object existence as a flag. There is no need to create it more
        'than once (?).
        If mMultipleRawFilesHandling2 Is Nothing Then
            'Used if the user chooses to do retention
            'time correlation.

            'Changed PM_RETCORR_ANYTIME 2006-11-03
            mMultipleRawFilesHandling2 = _
              New MultipleRawFilesHandling( _
               mOptions.rawFileMode, mApplication, _
               mOptions.COMversion)

            mMultipleRawFilesHandling2.SetGeneralSampleNumber( _
              aSampleNum)

            Dim isMultiple As Boolean = mRawFiles2.Length <> 1
            Dim lastIndex As Integer = mRawFiles2.Length - 1
            Dim j As Integer
            For j = 0 To lastIndex

                Dim someRawFileInfo As fileSpecStructure = mRawFiles2(j)
                Dim someRawFile As String = someRawFileInfo.path

                If j = 0 Then
                    mMultipleRawFilesHandling2.SetBaseDirFromFullFileNamePath( _
                      someRawFile)

                    ' Add Mascot result file name to title of the Protein
                    ' List Window...
                    If True Then
                        'Note: we don't have the Mascot result file name,
                        '      only one of the raw files...
                        Dim fileName As String = someRawFile
                        Dim newTitle As String = Me.Text & " " & fileName
                        Me.Text = newTitle
                    End If
                End If

                Dim dummyBoolean As Boolean = True
                Dim dummyErrCount As Integer = 0

                Dim periodString As String = "0"
                If isMultiple Then
                    periodString = Path.GetFileName(someRawFile)
                End If

                Dim someRawFileRefNum As Integer = _
                  mMultipleRawFilesHandling2.addPossibleFileName( _
                    periodString, _
                    dummyBoolean, dummyErrCount)

                Trace.Assert(dummyBoolean = True, _
                  "PIL ASSERT. dummyBoolean is not true...")
                Trace.Assert(dummyErrCount = 0, _
                  "PIL ASSERT. dummyErrCount is greater than 0...")
            Next j

            'For test only.
            Dim tempRawFiles() As fileSpecStructure = _
              mMultipleRawFilesHandling2.getRawFiles()
        Else
            Dim peter2 As Integer = 2 'It alread exists...
        End If
    End Sub 'createMultipleRawFilesHandlingObject


    'Changed PM_FLEXIBLE_RAWFILE_LOC 2007-06-12
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub buildRawFilesPathMap( _
      ByRef anInRawFiles2() As fileSpecStructure)

        Trace.Assert(Not anInRawFiles2 Is Nothing, _
          "PIL ASSERT. anInRawFiles2 is Nothing...")

        Dim lastIndex As Integer = mRawFiles2.Length - 1
        Dim j As Integer
        For j = 0 To lastIndex

            Dim someRawFileInfo As fileSpecStructure = anInRawFiles2(j)
            Dim someRawFile As String = someRawFileInfo.path

            Dim realRawFilePath As String = Nothing
            If AppCommon.SDUPcheckFileExists_withSearch( _
                 someRawFile, _
                 "should never happen...", _
                 realRawFilePath) Then

                Dim peter1 As Integer = 1 'Already exists
            Else
                Dim peter2 As Integer = 2 'Does not exist, not even in
                '  alternative folders.
            End If

            realRawFilePath = realRawFilePath.ToLower() 'Note: this
            '  must be done for later code to work - the "period" field
            '  in the tooltip is expected to be in lower case; match
            '  strings are wiff, raw and idx (lower case).
            mRawfile2RealRawFileHash.Add(someRawFile, realRawFilePath)

            'Side-effect...
            someRawFileInfo.path = realRawFilePath
            anInRawFiles2(j) = someRawFileInfo
        Next
    End Sub 'buildRawFilesPathMap()


    'Changed PM_MORE_MEMORY_WORKAROUND 2004-09-07
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub OpenParsedProteinsEtc( _
      ByVal aMascotWiffFileAss As MascotWiffAssociation, _
      ByVal aSampleNum As Integer, _
      ByRef anInLoadedDoc2 As MSQuantDocumentStructure, _
      ByRef anInPanelMessage As String)

        'This is Open/Load of a saved parse/protein list...

        saveOffAssoc(aMascotWiffFileAss, aSampleNum)

        Dim someResultStr As String = ""

        'Changed PM_SAVE_RAWFILE_MAPPING_MB4 2008-11-18
        mExperimentSettings = anInLoadedDoc2.experimentSettings2 'Note: this
        '  will overwrite any setting passed to the constructor.

        'Changed PM_SAVE_RECALIBRATION 2005-01-27
        'Changed PM_TYPESAFE 2006-10-25
        'Dim loadedProteinsEtc As ArrayList
        Dim loadedProteinsEtc2 As List(Of ProteinHitStructure) = _
          anInLoadedDoc2.parsedProts3

        mRawFiles2 = anInLoadedDoc2.rawFiles2 'Must this be before 
        '  call to buildRawFilesPathMap()???

        'Changed PM_FLEXIBLE_RAWFILE_LOC 2007-06-12
        buildRawFilesPathMap(anInLoadedDoc2.rawFiles2)

        'Changed PM_REFACTOR 2007-01-08. Separate function to also use
        'when mMultipleRawFilesHandling2 is required by a post-parse
        'correlation right after a parse (right after a load it worked OK).

        Me.createMultipleRawFilesHandlingObject(aSampleNum)


        'Changed PM_RECALIB_VISUAL_TRENDLINE 2007-12-07
        'Moved this block before setParsedProteinList() so the recalibrator
        'is setup before recalibration visualisation happens in the function.
        'This change was required because we now need the recalibrator in
        'the visualisation (before we only used the stored uncalibrated and
        'calibrated values in the peptide structure).

        'Changed PM_SAVE_ALLRECALIB_MB4 2008-11-21
        mRecalibrator = anInLoadedDoc2.recalibrator
        If mRecalibrator Is Nothing Then 'Assume is does not exist for loaded MB3...

            'For MB3 files only, loading of. We still need to keep this 
            'in order to load MB3 files...

            'Note: we depend on proper settings in the (global) options dialog...
            mRecalibrator = _
              New SDUPrecalibrator( _
                mOptions.recalibDomain, mOptions.recalibLimits)

            Dim lastIndex As Integer = anInLoadedDoc2.rawFiles2.Length() - 1
            Dim j As Integer
            For j = 0 To lastIndex
                Dim someRawFile As fileSpecStructure = anInLoadedDoc2.rawFiles2(j)

                Dim tagForRecalib As Integer = someRawFile.tag2

                'Not so elegant. Assume that setParsedProteinList() overwrites
                'any existing mRecalibrator (creates a new uninitialised one), so
                'we have to assign after the call....
                mRecalibrator.setLinearCalibrationConstants( _
                  anInLoadedDoc2.recalibSlope2, _
                  anInLoadedDoc2.recalibOffset2, _
                  tagForRecalib) 'Note: when loaded from MB3 constants are not
                '  for the raw file, but rather for all.
            Next j 'Through raw files.

            'Not so elegant. Assume that setParsedProteinList() overwrites
            'any existing mRecalibrator (creates a new uninitialised one), so
            'we have to assign after the call....
            '
            'This actually correct..
            'Note: for global (not per raw file) recalibration.
            mRecalibrator.setLinearCalibrationConstants( _
              anInLoadedDoc2.recalibSlope2, _
              anInLoadedDoc2.recalibOffset2, _
              SDUPrecalibrator.ALL_TAGCODE)
        End If 'Block. Recalibration stuff.

        'Note: the peptide filter does not matter as it is not
        '      used when the second parameter is False.
        Dim dummyPeptideFilter As peptideFilterStructure = _
          peptideFilterStructure.noPepFilter()

        'This is when loading from saved parse.
        Me.setParsedProteinList( _
          loadedProteinsEtc2, _
          False, _
          dummyPeptideFilter, _
          anInLoadedDoc2.rawFiles2) 'Note: the last two parameters 
        '  are default values only - if not loaded from the MBx file; that 
        '  is the case for MB3.

        PanelStatus.Text = anInPanelMessage
    End Sub 'OpenParsedProteinsEtc()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub ParseMascotFile( _
      ByVal aMascotWiffFileAss As MascotWiffAssociation, _
      ByVal aSampleNum As Integer, _
      ByRef aCorrSettings As correlationSettingsStructure)

        'Changed PM_MEMORY_ALLOCATION 2004-07-27
        quantApplication.stopNow("Before reading file", False)

        'Changed PM_REPORTS 2006-08-15
        mParseReport.AddItem2(0, 0, AppConstants.LONG_APP & " parsing report")

        mParseReport.AddItem2(1, 0, _
          "Mascot result file: " & ControlChars.Tab & _
            aMascotWiffFileAss.getMascotFileStr())

        'Later: state information from mOptions and aCorrSettings as well.

        'Note: side effect is to set mWiffFileStr.....
        saveOffAssoc(aMascotWiffFileAss, aSampleNum)

        mParseReport.AddItem2(2, 0, _
          "Raw file (may also include others): " & ControlChars.Tab & _
            mWiffFile.rawFilePath)

        'Changed PM_PARSE_CHUNKED 2004-04-05
        'Chunked operation

        'Changed PM_NO_CORELLATION 2005-09-22
        'Warn user if peptides from different raw files are going
        'to be eliminated by checkbox "Parenthesized peptides" in
        '"menu/Tools/Include in preselected peptides (PSPs)" being cleared.
        If aCorrSettings.doNotInsertNewPeptides = False Then
            If mOptions.inclPeptsInParens = False Then

                Dim msgStr As String = _
                  "Warning: if peptides are going to be inserted " & _
                  "(based on correlation between 2 or more raw files) then " & _
                  "it probably does not make sense to have " & _
                  "checkbox ""Parenthesized peptides"" in " & _
                  "menu/Tools/""Include in preselected " & _
                  "peptides (PSPs)"" cleared. " & _
                  AppConstants.LONG_APP & _
                  " will probably not able to do any correlation between " & _
                  "the raw files."

                MsgBox(msgStr)
            End If
        End If

        mMascotResultParser.initParsingProcessing( _
          aMascotWiffFileAss.getMascotFileStr(), _
          mWiffFile.rawFilePath, _
          aSampleNum, _
          mOptions, _
          aCorrSettings)

        'Changed PM_MEMORY_ALLOCATION 2004-07-26
        'Const BUFSIZE As Integer = 100
        'Const BUFSIZE As Integer = 4 * 1024
        Const BUFSIZE As Integer = 256
        Dim buffer(BUFSIZE - 1) As Char
        Dim eols(1) As Char
        eols(0) = Chr(10)
        eols(1) = Chr(13)

        Dim baseProgressRelative As Double = -200.0
        Dim progressSizeInPhase As Double = -200.0
        Dim progressPrefix As String = ""

        Dim processedCount As Integer
        Dim estimatedEndCount As Integer
        Dim phaseTransition As Boolean
        Dim stats As MascotResultParser.parsingStatsStructure
        stats.parsingErrorInfo = Nothing 'Keep compiler happy.

        While mMascotResultParser.doChunkParsing( _
          processedCount, estimatedEndCount, stats, phaseTransition, _
          buffer, BUFSIZE, eols)

            Dim relProgress As Double = _
              100.0 * processedCount / estimatedEndCount

            If stats.curState <> _
              MascotResultParser.parsingPhaseEnum.enumReadingFile Then

                Dim peter8 As Integer = 8
            End If

            Select Case stats.curState
                Case MascotResultParser.parsingPhaseEnum.enumReadingFile
                    baseProgressRelative = 0.0
                    progressSizeInPhase = 25.0
                    progressPrefix = "Read [KB]: "

                    processedCount = _
                      CInt(processedCount / 1024) 'Change unit to KByte.

                    Dim progTxt As String = _
                      "Reading file. " & relProgress.ToString("0.0") & " %"
                    PanelStatus.Text = progTxt

                Case MascotResultParser.parsingPhaseEnum.enumParsingToolTips
                    baseProgressRelative = 25.0
                    progressSizeInPhase = 25.0
                    progressPrefix = "Queries parsed: "

                    If phaseTransition Then
                        'This means that reading the file just completed
                        PanelStatus.Text = "Reading file completed"
                        Application.DoEvents()
                    Else
                        'Dim progTxt As String = _
                        '  "Parsing tooltips. " & processedCount & ", " & _
                        '  relProgress.ToString("0.0") & " %"
                        Dim progTxt As String = _
                          "Parsing tooltips. " & _
                          relProgress.ToString("0.0") & " %"
                        PanelStatus.Text = progTxt
                    End If

                Case MascotResultParser.parsingPhaseEnum.enumParsingProteins
                    baseProgressRelative = 50.0
                    progressSizeInPhase = 50.0
                    progressPrefix = "Proteins parsed: "

                    If phaseTransition Then

                        PanelStatus.Text = "Parsing tooltips completed"
                        Application.DoEvents()
                    Else
                        Dim progTxt As String = _
                          "Parsing proteins. " & _
                          relProgress.ToString("0.0") & " %"
                        PanelStatus.Text = progTxt
                    End If

                Case MascotResultParser.parsingPhaseEnum.enumOtherParsingXYZ
                    'End state....
                    If phaseTransition Then
                        PanelStatus.Text = "Parsing completed"
                        Application.DoEvents()
                    Else
                        Dim peter9 As Integer = 9
                    End If

                Case MascotResultParser.parsingPhaseEnum.enumParsingError
                    'Later: more information....

                    Dim numErrors As Integer
                    Dim errStr As String = ""
                    mMascotResultParser.getParseErrorInfo(numErrors, errStr)

                    Dim msgStr As String = _
                      AppConstants.LONG_APP & " can not continue the parsing. " & _
                      " One or more parsing errors happend. " & _
                      ControlChars.NewLine & _
                      numErrors & " errors: " & errStr & _
                      ControlChars.NewLine & ControlChars.NewLine & _
                      "Check that the Mascot result file (.htm/.html) has " & _
                      "the right format. " & _
                      "E.g. that 'Peptide Summary' was chosen, " & _
                      "that 'turn off pop-up' is OFF, " & _
                      "the tooltips contain the retention time information " & _
                      "for " & AppConstants.LONG_APP & ", etc."

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

            Trace.Assert(baseProgressRelative >= 0.0, _
              "PIL ASSERT. Base progress not set!.")
            Trace.Assert(progressSizeInPhase >= 0.0, _
              "PIL ASSERT. Progress in phase not set!.")
            Trace.Assert(progressPrefix <> "", _
              "PIL ASSERT. Progress prefix not set!.")

            Dim effectiveProgress As Double = _
              baseProgressRelative + relProgress * progressSizeInPhase / 100
            updateProg(effectiveProgress, processedCount, estimatedEndCount, _
              progressPrefix, stats.curState = _
                MascotResultParser.parsingPhaseEnum.enumParsingProteins)

            Application.DoEvents()
            Application.DoEvents()
            Application.DoEvents()

            'updatesForOneOrMoreDTAfiles(processedCount, estimatedEndCount, stats)
        End While

        'Changed PM_PARSEERROR_HANDLING 2004-12-14
        If True Then
            Dim numErrors As Integer
            Dim errStr As String = ""
            mMascotResultParser.getParseErrorInfo(numErrors, errStr)
            If numErrors > 0 Then

                'Assume fatal errors have already been reported.
                If stats.curState <> _
                   MascotResultParser.parsingPhaseEnum.enumParsingError Then

                    MsgBox( _
                      numErrors & " errors occured during parsing. " & _
                      ControlChars.NewLine & ControlChars.NewLine & _
                      "Some errors: " & errStr)
                End If
            End If
        End If

        'Changed PM_TYPESAFE 2006-10-25
        'Dim parsedProteins As ArrayList = mMascotResultParser.getParsedProteins()
        Dim parsedProteins As List(Of ProteinHitStructure) = _
          mMascotResultParser.getParsedProteins()

        If parsedProteins.Count = 0 Then
            MsgBox( _
              "No proteins were added to the protein list. " & _
              "E.g. this can happen if the peptide filter for preselected " & _
              "peptides (menu Tools/Options) is set such that no " & _
              "peptides match the criteria. " & _
              "Change the settings of the peptide filter.")
        End If

        'Changed PM_RAWFILE_PEPFILTER 2007-11-17. Moved before
        ' setParsedProteinList() as the list of raw files is
        'needed for the peptide filter in the recalibration
        'visualisation window.
        If True Then 'Moved from openProtValForm()
            Dim rawFiles() As fileSpecStructure = Nothing 'Keep
            '  compiler happy.
            mMascotResultParser.GetRawFiles(rawFiles)
            mRawFiles2 = rawFiles
        End If

        'Changed PM_RECALIB_FILTER 2007-09-04
        Dim recalibPeptideFilter As peptideFilterStructure = _
          mOptions.peptideFilters(peptideFilterEnum.enumRecalibParse)

        'Recalibration will happen here...
        'This is after parsing of the Mascot result file.
        Me.setParsedProteinList( _
          parsedProteins, _
          True, _
          recalibPeptideFilter, _
          mRawFiles2)

        Cursor = Cursors.Default
        mnuSaveProteinHitsAs.Enabled = True

        'Changed PM_PROGRESS_NOT_RESET 2004-06-15
        ProgressBar1.Value = 0

        'Changed PM_CODENOTE 2006-09-01. Note: MsgBox can
        '  have return value and several buttons, e.g.:
        '
        'If MsgBox( _
        '    "This item does not have Continue?", _
        '    MsgBoxStyle.OkCancel, "No file association") = _
        '  MsgBoxResult.Cancel Then Exit Function
        '
        'Can we replace frmEndOfParse with use of MsgBox()??

        'Changed PM_REPORTS 2006-08-15
        If mOptions.doNotShowDialogAfterParsing = False Then
            Dim someDlg As frmEndOfParse = New frmEndOfParse(Me)
            'Me.AddOwnedForm(someDlg)
            'someDlg.Show()

            Dim parentFormPos As Point = Me.Location
            someDlg.SetDesktopLocation( _
              parentFormPos.X + 30, parentFormPos.Y + 30)
            someDlg.BringToFront()
            someDlg.ShowDialog()
        Else
            Dim peter8 As Integer = 8 'Turned off!
        End If
    End Sub 'ParseMascotFile()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub endOfParseDialogResult(ByVal aDoNotShowTheDialog As Boolean)

        'We must get an updated version as the user may have changed the options
        'since we opened this parse.
        Dim someOptions As OptionsStruct2 = mParentForm.getOptions()
        someOptions.doNotShowDialogAfterParsing = aDoNotShowTheDialog

        mApplication.newOptions2(someOptions)

        'If it is later allowed to turn back the dialog (in the Options dialog):
        '  What to do?
    End Sub 'endOfParseDialogResult()


    '<Obsolete> Public Sub appendTextToProteinHits(ByVal theText As String)
    '    'the textBox sometimes only displays part of the string. Why??
    '    mProteinHitsSaveStr = theText
    '    ' txtProteinHits.AppendText(theText)
    'End Sub


    'Changed PM_PROTEINRATIO_DISPLAY 2004-02-04
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub updateVisual_ProteinRow( _
      ByRef aRow As ListViewItem, _
      ByRef aProt As ProteinHitStructure, _
      ByVal aProteinWasQuantified As Boolean)

        Dim massKDa As Double = aProt.monoIsotopicMass / 1000.0
        mColumnMapper.updateListItem( _
          aRow, proteinColumnEnum.enumProteinMass, _
          massKDa.ToString)

        If Not aProt.quantResults3 Is Nothing Then
            'Changed PM_CODEMARKER_PROTEINLIST_COLOURS 2006-11-21
            'Later: adding the colours, as in the old code.

            Dim value As Double = -10.0
            Dim keyBase As Integer = -5

            Dim lastIndex As Integer = aProt.quantResults3.Count - 1

            Dim qCount As Integer = lastIndex + 1
            Trace.Assert( _
              qCount < 25, _
              "PIL ASSERT. " & qCount & _
                "is probably too many SILAC dishes") 'For now, for error detection.
            If qCount > 3 Then
                Dim peter3 As Integer = 3
            End If

            Dim n As Integer 'Is selector for type: ratio, stddev
            '  for ratio, and relative error.

            'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
            ''Changed PM_CONSENSUSSCORE_ALLDISHES 2008-11-11.
            ''For n = 0 To 2
            'For n = 0 To 3
            For n = 0 To 5

                Dim dish As Integer
                For dish = 0 To lastIndex
                    Dim oneDishResult As oneDishResultStructure = _
                      aProt.quantResults3(dish)

                    Dim someItem As _
                      protSILACresultStructure = _
                        AppCommon.getProteinQuantValues( _
                          dish, _
                          MultipleRawFilesHandling.REF_WHOLEPROTEIN, _
                          aProt.quantResults3)

                    'Why not use a hash instead? This could also remove
                    'the redundancy between adding the columns and updating
                    'the content.
                    Select Case n

                        'Changed PM_CONSENSUSSCORE_ALLDISHES 2008-11-11.
                        Case 0 'Consensus score

                            'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                            'value = _
                            '  ProteinHitStructure.getConsensusScore( _
                            '    aProt.consensusScore2, dish)
                            Dim cons As consensusScoreStruct = _
                              ProteinHitStructure.getConsensusScore2( _
                                aProt.consensusScore3, dish)
                            value = cons.consensusScore

                            keyBase = _
                              proteinColumnEnum.enumConsensusScoreBaseNumber2

                        Case 1 'Number of non-zero points in protein profile.
                            'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                            Dim cons As consensusScoreStruct = _
                              ProteinHitStructure.getConsensusScore2( _
                                aProt.consensusScore3, dish)
                            value = cons.nonZeroPoints

                            keyBase = _
                              proteinColumnEnum.enumConsensusNonZeroPoints

                        Case 2 'Number of points within consensus in protein profile.
                            'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                            Dim cons As consensusScoreStruct = _
                              ProteinHitStructure.getConsensusScore2( _
                                aProt.consensusScore3, dish)
                            value = cons.pointsWithInConsensus

                            keyBase = _
                              proteinColumnEnum.enumPointsWithinConsensus

                        Case 3 'Ratio
                            value = someItem.averageRatioToBase
                            keyBase = proteinColumnEnum.enumRatioBaseNumber3
                        Case 4 'Std. for ratio
                            value = someItem.stdDevAverageRatioToBase
                            keyBase = proteinColumnEnum.enumRatioStdDevBaseNumber3
                        Case 5 'Rel. err.
                            value = _
                              100.0 * _
                              someItem.stdDevAverageRatioToBase / _
                              someItem.averageRatioToBase
                            keyBase = proteinColumnEnum.enumRatioRelErrBaseNumber4
                        Case Else
                            Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
                    End Select

                    Dim key2 As Integer = keyBase + dish
                    mColumnMapper.updateListItem( _
                      aRow, key2, value.ToString(mProteinFormatStrings3(n)) _
                      )
                Next dish
            Next 'Selector.
        Else
            Dim peter1 As Integer = 1 'No quantitaion results yet.
        End If

        'Changed PM_NUMBER_PEPTIDES_FOR_PEPTIDE_FILTER_BUG 2007-01-03.
        'Note: scoreInABC (sum of peptide score) below is still incorrect.
        Dim pepCount1 As Integer = aProt.peptsInABC
        Dim pepCount2 As Integer = aProt.effectivePeptideCount
        mColumnMapper.updateListItem( _
          aRow, proteinColumnEnum.enumNumberOfPeptides, _
          pepCount2.ToString)

        'Changed PM_SEQUENCE_COVERAGE 2008-04-15
        mColumnMapper.updateListItem( _
          aRow, proteinColumnEnum.enumSequenceCoverage, _
          aProt.sequenceCoverage.ToString("0.0"))

        'Note: scoreInABC is not correct if a peptide filter is in effect...
        mColumnMapper.updateListItem( _
          aRow, proteinColumnEnum.enumProteinScore, _
          aProt.scoreInABC.ToString)

        mColumnMapper.updateListItem( _
          aRow, proteinColumnEnum.enumProteinAccessionNumber, _
          aProt.accNum)

        mColumnMapper.updateListItem( _
          aRow, proteinColumnEnum.enumProteinDescription2, _
          aProt.description3)

        'Changed PM_PROTEIN_TAGS 2008-10-29
        'For now: on-demand extraction. Should we cache it instead?
        Dim tags As List(Of taggingStruct) = _
          tagging.extractTags(aProt.description3)
        Dim primaryTagStr As String = tagging.primaryTag(tags, mSsb)
        mColumnMapper.updateListItem( _
          aRow, proteinColumnEnum.enumPrimaryProteinTag2, _
          primaryTagStr)

        'Now one per dish.
        ''Changed PM_PCP_CONSENSUS_PROFILE 2008-11-06
        'mColumnMapper.updateListItem( _
        '  aRow, proteinColumnEnum.enumConsensusScore, _
        '  aProt.consensusScore.ToString("0.000"))
    End Sub 'updateVisual_ProteinRow()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub recalibrateAndAdjustMassesAndValidation2( _
      ByRef aProteinsSubset_dataStructureIndices2 As List(Of Integer), _
      ByVal aParsedProtList As List(Of ProteinHitStructure), _
      ByRef anInRecalibPeptideFilter As peptideFilterStructure, _
      ByVal aAddToParseReport As Boolean)

        Me.recalibrate2( _
          aProteinsSubset_dataStructureIndices2, _
          aParsedProtList, _
          anInRecalibPeptideFilter, _
          aAddToParseReport)

        Dim validationFilter As peptideFilterStructure = _
          mOptions.peptideFilters(peptideFilterEnum.enumValidationParse)

        SDUPrecalibrator.setCalibratedValues( _
          aParsedProtList, _
          mRecalibrator, _
          mOptions.protDefaultValidationScoreThr, _
          validationFilter, _
          mOptions.scoreA, _
          mOptions.scoreB, _
          mOptions.scoreC _
          )
    End Sub 'recalibrateAndAdjustMassesAndValidation2


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub setParsedProteinList( _
      ByVal aParsedProtList As List(Of ProteinHitStructure), _
      ByVal aDoRecalibrate As Boolean, _
      ByRef anInRecalibPeptideFilter As peptideFilterStructure, _
      ByRef anInRawFiles2() As fileSpecStructure)

        'Old:
        '  ByVal aParsedProtList As ArrayList
        '  ByVal aPeptideMaximumRelativeError_PPM As Double, _
        '
        '  ByVal aRecalibDomain2 As SDUPrecalibrator.recalibDomainEnum, _
        '  ByVal aRecalibLimits2 As SDUPrecalibrator.recalibLimitsStructure


        If mRecalibrator Is Nothing Then

            'This is for used at the end of a parse (in contrast to
            'loading from a file).

            mRecalibrator = _
              New SDUPrecalibrator( _
                mOptions.recalibDomain, mOptions.recalibLimits) 'Note: if it 
            '  is not fed data below then the client sets to the calibration 
            '  constants after this function.
        End If

        mParsedProts2 = aParsedProtList

        mProteinHitNumber2dataIndex = New Dictionary(Of Integer, Integer)

        'Changed PM_VALIDATION_AFTER_RECALIBRATION 2007-09-24. Moved
        '  up to here so the protein validation is correct.
        'Changed PM_MORE_MEMORY_WORKAROUND 2004-09-07
        If aDoRecalibrate Then

            'Changed PM_REFACTOR 2007-11-07
            'Nothing: flag for all proteins (not some subset).
            Dim flagForAllProteins As List(Of Integer) = Nothing
            Me.recalibrateAndAdjustMassesAndValidation2( _
              flagForAllProteins, _
              mParsedProts2, _
              anInRecalibPeptideFilter, _
              True)
        Else
            'Changed PM_REFACTOR 2007-10-24. Default now in SDUPrecalibrator.
        End If

        lstProtHits.Items.Clear()

        'Changed PM_MB3LOAD_SPEEDUP 2008-10-01
        lstProtHits.BeginUpdate()

        'Dim alternateLinesColour As Color = Color.LightBlue
        '300  Hue
        '4    Saturation
        '247  Value
        '
        '247  Red
        '243  Green
        '247  Blue
        Dim alternateLinesColour As Color = Color.FromArgb(247, 243, 247)

        'Changed PM_PROTEIN_TAGS_USERDEFINED 2008-11-07
        If True Then 'Some default tags...

            Dim defaultTags() As String = _
              { _
                "contaminant", _
                "keratin family", _
                "BSA family", _
                "trypsin family", _
                "myosin family", _
                "albumin family", _
                "centrosome", _
                "proteasome", _
                "autophagosome", _
                "mitochondrium", _
                "nucleolus", _
                "transcription factor", _
                "ubiquitin related", _
                "kinase", _
                "phosphatase", _
                "secreted", _
                "heat shock", _
                "", _
                "" _
              }

            Dim len As Integer = defaultTags.GetLength(0)
            mCurrentTags = New List(Of taggingStruct)(len + 5)

            Dim someTagStr As String
            For Each someTagStr In defaultTags

                If someTagStr.Length > 0 Then
                    Dim someItem As taggingStruct
                    someItem.tag2 = someTagStr
                    mCurrentTags.Add(someItem)
                End If
            Next 'Through checkBoxInfoList

        End If 'Block. Setting up some predefined tags.

        Dim someProt As ProteinHitStructure

        Dim lastProteinIndex As Integer = mParsedProts2.Count - 1
        Dim i As Integer
        Dim visualIndex As Integer = 0
        For i = 0 To lastProteinIndex
            someProt = mParsedProts2(i)

            'Silently ignore proteins with no (effective peptides).
            If someProt.effectivePeptideCount > 0 Then
                Dim protItem As New ListViewItem(someProt.hitNumber.ToString)

                'Changed PM_PROTEIN_TAGS_USERDEFINED 2008-11-07
                If True Then 'Block.
                    'As we are iterating through all proteins: use the opportunity
                    'to collect the different tags.
                    Dim tags As List(Of taggingStruct) = _
                      tagging.extractTags(someProt.description3)
                    If Not tags Is Nothing Then

                        Dim someTag As taggingStruct
                        For Each someTag In tags

                            Dim alreadyExist As Boolean = False

                            'Linear search, but the number of different tags
                            'are usually limited. If it becomes a problem
                            'then we could use a guard hash.
                            If True Then 'Block.
                                Dim someItem2 As taggingStruct
                                For Each someItem2 In mCurrentTags
                                    If someItem2.tag2 = someTag.tag2 Then

                                        alreadyExist = True
                                        Exit For
                                    End If
                                Next 'Through mCurrentTags
                            End If 'Block.

                            If Not alreadyExist Then
                                mCurrentTags.Add(someTag)
                            Else
                                Dim peter2 As Integer = 2
                            End If
                        Next 'Through tags
                    Else
                        Dim peter2 As Integer = 2 'No tags for current protein.
                    End If 'One or more tags in current protein.
                End If 'Block. Updating tags.

                If True Then
                    Dim savedHandleStatus As Boolean = _
                      mAvoidHandlingProteinCheckedEvent
                    mAvoidHandlingProteinCheckedEvent = True

                    protItem.Checked = someProt.proteinHasBeenChecked 'This will
                    '   result in event handler lstProtHits_ItemCheck being called,
                    '  through ListViewCEBIExtended4/OnItemCheck(). But
                    '  mAvoidHandlingProteinCheckedEvent is set, so it will do nothing.

                    Dim newItem2 As ListViewItem = lstProtHits.Items.Add(protItem)
                    '  Protein hit number.

                    mAvoidHandlingProteinCheckedEvent = savedHandleStatus 'Must be
                    '  after ".Add".

                    Dim columns As Integer = mColumnMapper.columnCount()

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

                    'Changed PM_REFACTOR 2004-02-04
                    updateVisual_ProteinRow(newItem2, someProt, False)

                    visualIndex += 1
                End If

                If visualIndex Mod 2 = 0 Then
                    protItem.BackColor = alternateLinesColour
                End If
            Else
                'Not added to visual list...
                Dim peter4 As Integer = 4
            End If
            mProteinHitNumber2dataIndex.Add(someProt.hitNumber, i)
        Next 'Through proteins.

        'Changed PM_MB3LOAD_SPEEDUP 2008-10-01
        lstProtHits.EndUpdate()
        Dim prots As Integer = lstProtHits.Items.Count 'Work-around for a 
        '  bug in ListView. Ref is
        '  <http://www.codeproject.com/KB/list/ObjectListView.aspx?msg=2525783>, 
        '    "... ways around this bug: Don't use a 
        '    BeginUpdate()/EndUpdate() pair. Make a call to Items.Count, 
        '    which does flush the cache, before iterating over the 
        '    collection."

        If True Then
            'Changed PM_REFACTOR 2008-11-06
            ' 'Changed PM_TYPESAFE_HASH 2006-11-06
            ' Dim keylist As List(Of sortKeyStructure) = _
            '   mColumnSortSpecificationHash( _
            '     proteinTbItmColEnum.enumProteinHitNumber)
            ' 
            ' mListViewColumnSorter.prepareSort(keylist)
            mListViewColumnSorter.prepareSortAndSort( _
              proteinColumnEnum.enumProteinHitNumber, Nothing)

            'Changed PM_COLUMNSORT_BY_KEYBOARD_FLATTEN 2008-11-08
            ''Changed PM_COLUMNSORT_BY_KEYBOARD 2008-11-06
            'Dim menuItemToAddTo As MenuItem = mnuArrangeProteins
            Dim menuItemToAddTo As MenuItem = mnuView

            mListViewColumnSorter.menuItemsForSortableColumns( _
              menuItemToAddTo, _
              AddressOf arrangeProteinsMenuSubItemsOnClick)

            'Why does this result in call of
            'the Compare() function (in ListViewColumnSorter.vb) ???
            'Implicit sorting?
            lstProtHits.ListViewItemSorter() = mListViewColumnSorter
        End If

        lstProtHits.Refresh()

        'Changed PM_RAWFILE_PEPFILTER 2007-11-17
        Trace.Assert(Not anInRawFiles2 Is Nothing, _
          "PIL ASSERT. anInRawFiles Is Nothing.")

        'Changed PM_HIDE_RECALIBVISUALISATION_WINDOW 2008-01-06
        If mOptions.endOfParseAction.openRecalibrationVisualisationWindow Then

            'Changed PM_REFACTOR 2007-11-07
            Me.visualiseRecalibration(anInRawFiles2)
        End If

        'Changed PM_HIGHER_LEVEL_PROCESSING 2008-09-04
        'Fix up raw files with .
        If True Then

            Dim rawFile2nPointKey2 As Dictionary(Of String, Integer) = _
              New Dictionary(Of String, Integer)
            If True Then 'Make helper hash.
                Dim hashEnumerator2 As Dictionary( _
                  Of Integer, rawFileStruct4).Enumerator = _
                    mExperimentSettings.rawFileMapping3.GetEnumerator()
                While (hashEnumerator2.MoveNext())
                    Dim curKey As Integer = hashEnumerator2.Current.Key
                    Dim curValue As rawFileStruct4 = _
                       hashEnumerator2.Current.Value

                    'ToLower(): this assumes the other list has lowercase
                    '  raw file paths. This happens during parsing.
                    Dim outKey As String = curValue.rawFile.ToLower()
                    If outKey <> "" Then
                        If Not rawFile2nPointKey2.ContainsKey(outKey) Then
                            rawFile2nPointKey2(outKey) = curKey
                        Else
                            Dim msg As String = _
                              "Raw file " & outKey & "  defined more than once..."
                            MsgBox(msg)
                        End If
                    End If
                End While 'Through raw file mapping.
            End If 'Block. Making, creating helper hash.

            If Not anInRawFiles2 Is Nothing Then

                Dim len As Integer = anInRawFiles2.Length()

                Dim mMap As Dictionary(Of Integer, Integer) = _
                  New Dictionary(Of Integer, Integer)

                Dim missSB As StringBuilder = Nothing 'Lazy instantiation. We
                '  also use it as a flag below.
                Dim missingCount As Integer = 0
                Dim maxMissing As Integer = anInRawFiles2.Length

                Dim someItem As fileSpecStructure
                For Each someItem In anInRawFiles2

                    Dim rawFilePath As String = someItem.path
                    Dim rawFilePathLowerCase As String = rawFilePath.ToLower()
                    Dim rawFileID As Integer = someItem.tag2

                    Dim NpointKey2 As Integer
                    If rawFile2nPointKey2.TryGetValue( _
                      rawFilePathLowerCase, NpointKey2) Then

                        'Fix-up...

                        Dim someExperimentItem As rawFileStruct4 = _
                          mExperimentSettings.rawFileMapping3(NpointKey2)

                        someExperimentItem.rawFile = rawFilePath 'Store in
                        '  same case as the rest of the system (?).
                        someExperimentItem.rawFileID7 = rawFileID

                        'Write back...
                        mExperimentSettings.rawFileMapping3(NpointKey2) = _
                          someExperimentItem

                        mMap(rawFileID) = NpointKey2
                    Else
                        missingCount += 1
                        'Lazy instantiation.
                        If missSB Is Nothing Then
                            missSB = New StringBuilder(300)
                        End If

                        Dim noPathFileName As String = _
                          Path.GetFileName(rawFilePath)

                        missSB.Append(noPathFileName)

                        If maxMissing > 1 Then 'Most common is a single
                            '  raw file (not combined). Avoid it in that case...

                            missSB.Append(", ")
                        End If
                    End If
                Next 'Through raw files (set of in current parse).

                'Changed PM_EXPANDED_MSG_MISSING_EXPERIMENT_POINT 2008-10-22. Now
                '  one message box instead of one per missing raw file mapping.
                If Not missSB Is Nothing Then
                    Dim rawFiles As String = missSB.ToString

                    missSB.Length = 0 'Reusing buffer object...

                    missSB.Append("No experiment points are defined for ")
                    missSB.Append(missingCount)
                    missSB.Append(" raw files (see below)")
                    missSB.Append(". This is harmless, but is required for PCP plot ")
                    missSB.Append("and for meaningful information in the experiment ")
                    missSB.Append("point column in the Quantitation window. ")
                    missSB.Append("Define the raw file to experiment point mapping in ")
                    missSB.Append("menu Experiment/Raw File Mapping.")
                    missSB.Append(ControlChars.NewLine)
                    missSB.Append(ControlChars.NewLine)
                    missSB.Append("Raw files not mapped: ")
                    missSB.Append(ControlChars.NewLine)
                    missSB.Append(rawFiles) 'Note: there will be a trailing comma...
                    Dim msg As String = missSB.ToString
                    MsgBox(msg)
                End If
                'ControlChars.NewLine

                mExperimentSettings.INTERNAL_rawFileID2NpointHash = mMap

                'Alternate loop...
                'Dim lastIndex As Integer = anInRawFiles.Length() - 1
                'Dim j As Integer
                'For j = 0 To lastIndex
                '    Dim rawFileID As Integer = anInRawFiles(j).tag2
                'Next j
            End If
        Else
            Dim peter2 As Integer = 2 'No raw files. Ever expected? Single raw file?
        End If 'Fix up raw files with experiment definitions (N-space, etc.)
    End Sub 'setParsedProteinList()


    'Changed PM_REFACTOR 2007-11-07
    '****************************************************************************
    '*    Parameters: anInRawFiles is for the peptide filter.                   *
    '****************************************************************************
    Private Sub visualiseRecalibration( _
      ByRef anInRawFiles() As fileSpecStructure)

        'Note: using the parse filter (preselected peptides (PSPs)), not the
        '      parse recalibration filter.

        'Changed PM_RECALIB_VISUAL 2007-09-02
        Dim parsePeptideFilter As peptideFilterStructure = _
          mOptions.peptideFilters(peptideFilterEnum.enumRecalibVisual)

        'Changed PM_SILAC_AWARE_PEPTIDEFILTERDIALOG 2008-10-05
        Dim SILACmods As Dictionary(Of Integer, Integer) = _
          Me.constructSILACmods()

        mCalibVisualForm = _
          New frmRecalibrationVisualisation( _
            Me, _
            Nothing, mParsedProts2, parsePeptideFilter, _
            mApplication, _
            mWiffFile.MascotFilePath, _
            anInRawFiles, _
            mRecalibrator, _
            SILACmods, _
            mParseIDnumber)
        mCalibVisualForm.Show()
    End Sub 'visualiseRecalibration


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub updateProg( _
      ByVal aValue As Double, ByVal aProtParsed As Integer, _
      ByVal aNumProtInTable As Integer, _
      ByVal aValuePrefix As String, ByVal aIsProtein As Boolean)

        If Not (aValue < 0 Or aValue > 100) Then
            ProgressBar1.Value = CInt(aValue)

            'Changed PM_PARSE_CHUNKED 2004-04-13
            'PanelProteinsParsed.Text = "Proteins parsed: " & aProtParsed.ToString
            PanelProteinsParsed.Text = aValuePrefix & aProtParsed.ToString

            If aIsProtein Then
                PanelProteinsInTable.Text = "In table: " & aNumProtInTable.ToString
                'PanelProteinsInTable.Refresh()
            Else
                Dim peter9 As Integer = 9
            End If
        End If
    End Sub 'updateProg


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    <Obsolete()> Public Sub setOptions( _
      ByVal aOptions As OptionsStruct2)

        mOptions = aOptions
    End Sub 'setOptions


    'Changed PM_REFACTOR 2006-11-15
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Function getCurPrValFrm() _
      As frmProtValidation

        Return mCurrentFrmProtValidation
    End Function 'getCurPrValFrm


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function openProtValForm3( _
      ByVal aNewInstance As Boolean, _
      ByRef aDataStructureIndex7 As Integer, _
      ByVal aDisplayQueryNumber As Integer) _
      As Boolean 'True: OK to open.

        Dim toReturn As Boolean = False

        'Changed PM_COMMANDLINE 2006-11-15
        'Old:
        '  Optional ByVal aNewInstance As Boolean = True
        '  ByRef aVisualIndex2 As Integer

        Try
            'Changed PM_RECALIBVIS_FEEDBACK 2008-10-03
            Cursor.Current = Cursors.WaitCursor

            'We pass the proteinHitStruct to the Protein validation dialog.
            If mWiffFile.rawFilePath = "" Then
                Trace.Assert(False, "PIL ASSERT. This should never happen...")
                'Me.openRawDataWiffFile()
            End If
            'Pass it the recalibration values, too.

            'Changed PM_VISUAL_COLUMNSORT 2006-02-24
            ''Changed PM_QUANT_AUTOMATION 2003-03-11
            ''Dim curProt As ProteinHitStructure = _
            ''    CType(mParsedProts(aSelectedIdx), ProteinHitStructure)
            'Dim curProt As Object = mParsedProts(aSelectedIdx)

            'Changed PM_COMMANDLINE 2006-11-15
            'Dim dataStructureIndex As Integer
            'Dim curProt As ProteinHitStructure = _
            '  Me.getProteinFromVisualIndex(aVisualIndex, dataStructureIndex)
            Dim curProt2 As ProteinHitStructure = _
              mParsedProts2(aDataStructureIndex7)

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

            Dim peptideCount As Integer = _
              curProt2.peptides.peptideCount2(iterToken)
            If peptideCount > 0 Then
                toReturn = True

                'Moved to mnuOpenMascotFile_Click().
                ''Changed PM_SEVERALWIFFS 2003-08-26
                'Dim rawFiles() As fileSpecStruct
                'mMascotResultParser.GetRawFiles(rawFiles)
                ''Changed PM_SEVERALWIFFS_EXPORT 2003-08-29
                'mRawFiles = rawFiles

                'Changed PM_MULTIPLE_FINNEGAN_TROUBLE 2004-01-18. Create only one
                'raw object for each protein-list/parse. In the past one was
                'created for each protein.

                If mRawDataFileHandling Is Nothing Then
                    Dim sharedSpectrumClassifier As spectrumClassifier = _
                      mApplication.getClassifierObject()

                    quantApplication.createAndInitRawFileObject( _
                      mOptions.rawFileMode, mRawFiles2, mRawDataFileHandling, _
                      mWiffFile.sampleNumberInRawFile, _
                      sharedSpectrumClassifier, _
                      mOptions.COMversion)
                End If

                Dim proteinValForm As frmProtValidation
                If aNewInstance Or mCurrentFrmProtValidation Is Nothing Then
                    proteinValForm = New frmProtValidation( _
                        curProt2, mWiffFile.rawFilePath, mWiffFileQuantStr, Me, _
                        mWiffFile, mOptions, _
                        aDataStructureIndex7, mRawFiles2, _
                        mApplication, mRawDataFileHandling, _
                        mRecalibrator, _
                        aDisplayQueryNumber, _
                        mParseIDnumber, _
                        mExperimentSettings)
                Else
                    proteinValForm = mCurrentFrmProtValidation
                    proteinValForm.Init( _
                        curProt2, mWiffFile.rawFilePath, _
                        mWiffFileQuantStr, Me, _
                        mWiffFile, mOptions, _
                        aDataStructureIndex7, mRawFiles2, _
                        mApplication, mRawDataFileHandling, _
                        mRecalibrator, _
                        aDisplayQueryNumber, _
                        mParseIDnumber)
                End If
                mCurrentFrmProtValidation = proteinValForm 'This is a side-effect
                '  of calling this function...

                'Changed PM_QUANT_AUTOMATION 2003-03-11
                'Old. Delete.
                'Dim proteinValForm As New frmProtValidation( _
                '    CType(mParsedProts(aSelectedIdx),
                '      ProteinHitStructure), mWiffFileStr, _
                '    mWiffFileQuantStr, Me, mA, mB, mWiffFile, mOptions)

                'Changed PM_CLOSEWARNING 2004-04-21
                'Simple for now: only close warnings if protein valdation has
                'been opened.
                mDirty = True

                proteinValForm.Show()
            Else
                Dim peter2 As Integer = 2 'No peptides! Do not display. Clients
                '  are alerted through the return value.
            End If

            'Changed PM_RECALIBVIS_FEEDBACK 2008-10-03
            Cursor.Current = Cursors.Default

        Catch exceptionObject As Exception

            Dim stdStr As String = Nothing 'Keep compiler happy.
            If True Then
                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)

                stdStr = errMsg & ControlChars.NewLine
            End If

            Dim stackStr As String = _
              "Details: stacktrace=" & ControlChars.NewLine & _
              exceptionObject.StackTrace
            Dim strOrig As String = _
              "Problem opening the raw data file (wiff, raw or idx). Likely reasons: " & _
              ControlChars.NewLine & _
              "1. raw file mode (Tools/Options) is Analyst or Micromass for a .raw file " & _
                "or it is Finnegan or Micromass for .wiff file or it is Finnegan or " & _
                "Analyst for .idx file." & ControlChars.NewLine & _
              "2. Analyst is prior to SP7 (Analyst v. 1.3)" & ControlChars.NewLine & _
              "3. The Analyst raw file contains more than one sample. " & _
                "The first sample may be nearly empty and the retention times " & _
                "in the Mascot result file refers to the second sample." & _
                "Remedy: set the sample number to 2 by using the dialog " & _
                "menu Edit/Set sample number." & ControlChars.NewLine & _
              "4. The specified sample number may not exist in one or " & _
                "more raw data files " & ControlChars.NewLine & _
              ControlChars.NewLine

            'stackStr is already in stdStr.
            MsgBox(strOrig & stdStr)

            'PM note: may not have anything
            '         to do with the wiff file - it happend for an array
            '         index out of bounds.
        End Try
        'HACK:  'how to prevent it from selecting?

        'Changed PM_NO_OFF_BY_OPENPROTEINWINDOW 2003-08-04
        ' lstProtHits.Items(aSelectedIdx).Checked = False
        '   Note: opening the protein validation dialog will uncheck the protein. Why????

        'Changed PM_NO_PROTEINLINE_COLOUR 2006-11-15
        'Changed PM_COMMANDLINE 2006-11-15
        ''Changed PM_EXPORT_QUANTIFIED 2003-03-12. XXXXXXXXXXXXx
        ''lstProtHits.Items(aSelectedIdx).BackColor() = System.Drawing.Color.ForestGreen
        'lstProtHits.Items(aVisualIndex).BackColor() = _
        '  System.Drawing.Color.LightGreen

        Return toReturn
    End Function 'openProtValForm


    'Changed PM_REFACTOR 2006-02-24
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function hitnumber2VisualIndex( _
      ByVal anInHitNum As Integer) _
      As Integer

        Dim toReturn As Integer = -1

        Dim lastVisualIndex As Integer = lstProtHits.Items.Count - 1
        Dim i As Integer
        For i = 0 To lastVisualIndex
            If anInHitNum = CInt(lstProtHits.Items(i).Text) Then
                toReturn = i
                Exit For
            End If
        Next i

        Return toReturn
    End Function 'hitnumber2VisualIndex


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Friend Sub MarkProteinAsChecked( _
      ByVal anInHitNum As Integer, ByVal aChecked As Boolean)

        'Go through entries in table and entries in data struct and mark
        'this protein as checked.

        'Changed PM_PROTEINS_CHECK_SQL_PROBLEM 2003-08-04
        'Note: only changes the visual display, NOT the data structure.


        'Changed PM_REFACTOR 2006-02-24
        'Dim lastVisualIndex As Integer = lstProtHits.Items.Count - 1
        'Dim i As Integer
        'For i = 0 To lastVisualIndex
        '    If anInHitNum = CInt(lstProtHits.Items(i).Text) Then
        '
        '        If aChecked Then
        '            lstProtHits.Items(i).Checked = True
        '        Else
        '            lstProtHits.Items(i).Checked = False
        '        End If
        '
        '        Exit For
        '    End If
        'Next i
        Dim visualIndex As Integer = hitnumber2VisualIndex(anInHitNum)
        lstProtHits.Items(visualIndex).Checked = aChecked
    End Sub 'MarkProteinAsChecked


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Function GetNextProtein( _
      ByRef anInOutprotHitStru As ProteinHitStructure, _
      ByRef anOutDataStructureIndex As Integer) As Boolean

        Dim toReturn As Boolean = True 'Default: that we have not reached the end.

        'Find visual index from specified hitnumber
        Dim hitNumber As Integer = anInOutprotHitStru.hitNumber
        Dim oldVisualIndex As Integer = hitnumber2VisualIndex(hitNumber)

        'Changed PM_ARRIVED_LAST_PROTEIN_BUG 2004-07-15

        'Reset multiple selection if any, and only select the first.
        If False Then
            'Dim firstSelectedIdx As Integer = lstProtHits.SelectedIndices.Item(0)
            'Dim selectedCount As Integer = lstProtHits.Items.Count
            'If selectedCount > 1 Then
            '    Dim lastIndex2 As Integer = lstProtHits.Items.Count - 1
            '    Dim j As Integer
            '    For j = 0 To lastIndex2
            '        lstProtHits.Items(j).Selected = False
            '    Next j
            'End If
        End If

        'Changed PM_SELECTION_INDEPENDENT 2005-02-04
        'Don't depend on or use selected protein. Instead find next **Checked** protein
        'after the specified current protein. The selection is ignored.

        'Dim dataIndex As Integer = _
        '  Me.proteinIndexFromHitNumber(anInOutprotHitStru.hitNumber)

        'Determine the currently selected protein in the table (or data struct)
        'and select and return the next one.

        'Changed PM_SELECTION_INDEPENDENT 2005-02-04
        'Dim idx As Integer = lstProtHits.SelectedIndices.Item(0)

        'Dim lastIndex As Integer = lstProtHits.Items.Count - 1

        'Dim lastProteinIndex As Integer = mParsedProts.Count - 1
        Dim lastVisualIndex As Integer = lstProtHits.Items.Count - 1
        If oldVisualIndex = lastVisualIndex Then
            'At the end.
            'Leave it unchanged. Is this good?
            toReturn = False
        Else
            'Changed PM_ARRIVED_LAST_PROTEIN_BUG 2004-07-15
            'When multiple selection is on we must reset the current first,
            'otherwise this code will not work when called the second time.
            lstProtHits.Items(oldVisualIndex).Selected = False

            'Changed PM_SELECTION_INDEPENDENT 2005-02-04
            ''Changed PM_REFACTOR 2004-08-04
            Dim newVisualIndex As Integer
            If True Then 'Find next checked
                newVisualIndex = oldVisualIndex + 1
                Dim i As Integer
                For i = newVisualIndex To lastVisualIndex
                    Dim dataIndex As Integer = _
                      Me.getProteinIndexFromVisualIndex(i)

                    If mParsedProts2(dataIndex).proteinHasBeenChecked Then
                        newVisualIndex = i
                        Exit For
                    End If
                Next
            End If

            lstProtHits.Items(newVisualIndex).Selected = True 'Move up one.

            'Changed PM_SELECTION_INDEPENDENT 2005-02-04
            lstProtHits.EnsureVisible(newVisualIndex)

            'Dim dataIndex2 As Integer = _
            '  Me.getProteinIndexFromVisualIndex(newVisualIndex)
            'anInOutprotHitStru = _
            '  DirectCast(mParsedProts(dataIndex2), _
            '    ProteinHitStructure)
            ''Changed PM_PROTEIN_OVERWRITE_BUG 2004-08-04
            'anOutDataStructureIndex = dataIndex2
            anInOutprotHitStru = _
              Me.getProteinFromVisualIndex( _
                newVisualIndex, anOutDataStructureIndex)
        End If

        Return toReturn
    End Function 'GetNextProtein


    'Changed PM_REFACTOR 2007-11-07
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub recalibrate2( _
      ByRef aProteinsSubset_dataStructureIndices2 As List(Of Integer), _
      ByRef anInParsedProts As List(Of ProteinHitStructure), _
      ByRef anInRecalibPeptideFilter As peptideFilterStructure, _
      ByVal aAddToParseReport As Boolean)

        'Changed PM_REFACTOR 2007-11-07
        SDUPrecalibrator.feedCalibratorWithPeptides( _
          aProteinsSubset_dataStructureIndices2, _
          anInParsedProts, anInRecalibPeptideFilter, mRecalibrator)


        'Note: the calibrator compute the calibration the first time
        '      a calibration value is asked for, like the call below.
        Dim panelStr As String = mRecalibrator.getAccuracyStatsStr()
        PanelStatus.Text = panelStr


        'Changed PM_SECOND_RE_RECALIB_BUG 2008-12-17
        If aAddToParseReport Then 'Only add to parse report at parse time (not when the user do recalibration after parsing).
            Dim recalibStr As String = mRecalibrator.getRecalibMsgStr()
            mParseReport.AddItem2(1000, 0, recalibStr)
        End If

        mRecalibReport = mRecalibrator.getRecalibReport()
    End Sub 'recalibrate2()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub ClearAndCheckSubSampleMenu(ByVal theItem As Integer)
        Dim i As Integer
        For i = 0 To 3 'Four different samples possible.
            mnuSample.MenuItems(i).Checked = False
        Next i
        mnuSample.MenuItems(theItem).Checked = True
    End Sub 'ClearAndCheckSubSampleMenu


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Function pushToUserSelectedFile2( _
      ByVal aStr As String, _
      ByVal aOKStatusStr 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, ParserStatus.Text, aOKStatusStr, "")
        Return toReturn
    End Function 'pushToUserSelectedFile2()


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

        'Changed PM_PROTEIN_OVERWRITE_BUG 2004-08-04
        'Accession number is read-only, it should not change.
        Dim origAcc As String = mParsedProts2(aProteinDataIndex).accNum
        Trace.Assert( _
           origAcc = aProt.accNum, _
            "PIL ASSERT. Protein with accession number " & origAcc & _
            " is about to be overwritten...")

        mParsedProts2(aProteinDataIndex) = aProt

        'Some screen updates needed? Not at the moment as this
        'change is for export.

        If True Then 'Visual part
            'Changed PM_PROTEINRATIO_DISPLAY 2004-02-04
            ''Changed PM_REFACTOR 2004-02-04
            'd$ Changed PM_PROTEIN_RATIOS 2003-06-27
            'd$ Indexes into protein list columns: hard coded for now!!!!!!!!!!!!!!!!!!!
            ''lstProtHits.Items(aProteinListIndex).SubItems(2).Text = relError1.ToString("0.0")
            ''lstProtHits.Items(aProteinListIndex).SubItems(2).ForeColor = colour1
            ''lstProtHits.Items(aProteinListIndex).SubItems(3).Text = relError2.ToString("0.0")
            ''lstProtHits.Items(aProteinListIndex).SubItems(3).ForeColor = colour2

            Dim hitNumber As Integer = mParsedProts2(aProteinDataIndex).hitNumber
            Dim visualIndex As Integer = hitnumber2VisualIndex(hitNumber)

            'Changed PM_EXTERNAL_QUANT_TROUBLE 2006-08-10
            Trace.Assert( _
              visualIndex >= 0, "PIL ASSERT. visualIndex is invalid: " & _
              visualIndex & ". ")

            Dim row As ListViewItem = lstProtHits.Items(visualIndex)
            'updateProteinListItem( _
            '  row, proteinTbItmColEnum.ePeptsA, relError1.ToString("0.0"))
            'proteinListItemForeColor(row, proteinTbItmColEnum.ePeptsA, colour1)
            'updateProteinListItem( _
            '  row, proteinTbItmColEnum.ePeptsB, relError2.ToString("0.0"))
            'proteinListItemForeColor(row, proteinTbItmColEnum.ePeptsB, colour2)

            'Changed PM_PROTEINRATIO_DISPLAY 2004-02-04
            updateVisual_ProteinRow(row, aProt, True)

            'lstProtHits.Items(aProteinListIndex).BackColor = commonColorBackColour
        End If
    End Sub 'updateProtein()


    '****************************************************************************
    '*                                                                          *
    '*    E V E N T   H A N D L E R S ,   B E G I N                             *
    '*                                                                          *
    '****************************************************************************


    '****************************************************************************
    '*    E V E N T   H A N D L E R S ,   menus                                 *
    '****************************************************************************


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

        Me.Close()
    End Sub


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

        MsgBox("Sorry, no longer available...")
        'OpenFileDialog1.Filter = "Web Pages (*.html; *.htm)|*.html;*.htm|All files (*.*)|*.*"
        'OpenFileDialog1.ShowDialog()
        'Dim Str As String = OpenFileDialog1.FileName
        'If Not Str.Length = 0 Then
        '    Dim MascotResultFrm As New frmWebMascotResult   'doesn't work with a constructor and calling MyBase.New (then the form doesn't get contructed)
        '    MascotResultFrm.NavigateTo(Str)
        '    MascotResultFrm.Show()
        'End If
    End Sub 'mnuShowMascotResult_Click


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

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

    End Sub 'mnuOpenMascotFile_Click


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

        'Changed PM_STRUCTURED_PROGRAMMING 2005-12-05

        If mParsedProts2 Is Nothing Then
            MsgBox("No proteins parsed yet")
        Else
            Dim prot As ProteinHitStructure
            Dim countVerified, countOver24 As Integer
            Dim pept As PeptideHitStructure = _
              PeptideHitStructure.blankPeptide() 'Keep compiler happy.

            For Each prot In mParsedProts2

                Dim pepIter As peptideListIterator = _
                  New peptideListIterator(prot.peptides)
                'For Each pept In prot.pepts
                While Not pepIter.nextPeptide(pept)

                    If pept.verified Then
                        countVerified += 1
                    End If
                    If pept.MascotScore2 >= 24.0 Then
                        countOver24 += 1
                    End If

                End While 'Through peptides.

            Next 'Through proteins
            MsgBox(countVerified.ToString & "  verified peptides and " & vbCrLf & _
                countOver24.ToString & " peptides with score of more than 24")
        End If
    End Sub 'mnuPeptideStats_Click


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

        Dim quantOptionsForm As New frmQuantOptions
        '  frmOptions(mOptions, Me)
        quantOptionsForm.Show()
    End Sub 'mnuQuantOptions_Click


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

        'Changed PM_PROTEINS_CHECK_SQL_PROBLEM 2003-08-04
        'Note: only changes the visual display, NOT the data structure.

        Dim visualIndex As Integer = lstProtHits.SelectedIndices.Item(0)
        lstProtHits.Items(visualIndex).Checked = True
    End Sub 'mnuMarkAsChecked_Click


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

        'Note: only changes the visual display, NOT the data structure.
        Dim visualIndex As Integer = lstProtHits.SelectedIndices.Item(0)
        lstProtHits.Items(visualIndex).Checked = False
    End Sub 'mnuUnMarkProtein_Click


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

        'Changed PM_DISABLE_RECALIBRATEWIFF 2007-11-07
        'Menu item made invisible. Can we delete it now that we
        'have post-parse recalibration?
        Trace.Assert(False, "Stop!", _
          "PIL ASSERT. Internal/development assert for stopping execution......")

        'Dim recalibPeptideFilter As peptideFilterStructure = _
        '  mOptions.peptideFilters(peptideFilterEnum.enumRecalibParse)
        'Me.recalibrate2(mParsedProts2, recalibPeptideFilter)
    End Sub 'mnuRecalWiff_Click


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

        ClearAndCheckSubSampleMenu(0)
        mWiffFile.sampleNumberInRawFile = 1
    End Sub 'mnuSample1_Click


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

        ClearAndCheckSubSampleMenu(1)
        mWiffFile.sampleNumberInRawFile = 2
    End Sub 'mnuSample2_Click


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

        ClearAndCheckSubSampleMenu(2)
        mWiffFile.sampleNumberInRawFile = 3
    End Sub 'mnuSample3_Click


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

        ClearAndCheckSubSampleMenu(3)
        mWiffFile.sampleNumberInRawFile = 4
    End Sub 'mnuSample4_Click


    'Changed PM_REFACTOR 2006-11-15
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Function auto_openPrValFrm2( _
      ByRef aDataStructureIndex7 As Integer, _
      ByRef anInOutFirstTime As Boolean, _
      ByVal aDisplayQueryNumber As Integer) _
      As Boolean

        'Do we really need aDisplayQueryNumber???


        'Changed PM_NO_INIT_TWICE 2005-02-28
        Dim openNew As Boolean = anInOutFirstTime
        If anInOutFirstTime Then
            'Ensure that we get a fresh quantitation window.
            'This is to avoid getting in trouble when the user has
            'opened and closed a quantitation window. It also avoids
            'touching quantitation windows that are already open.
            anInOutFirstTime = False
        End If

        'Changed PM_REFACTOR 2006-11-15
        'openProtValForm(visualIndex3, openNew)
        Dim toReturn As Boolean = _
          openProtValForm3(openNew, aDataStructureIndex7, aDisplayQueryNumber)
        Return toReturn
    End Function 'auto_openPrValFrm2


    'Changed PM_QUANT_AUTOMATION 2003-03-11
    'Menu Automation/Quantitate one
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuQuantOne_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuQuantOne.Click

        'Changed PM_AVOID_ARRAYINDEX_OUTOFRANGE 2003-03-31
        'For now we just refuse if there is no selection, but the real 
        'solution should be to disable menu item when there
        'is no protein selection.
        If lstProtHits.SelectedIndices.Count > 0 Then

            'Changed PM_MEMORY_ALLOCATION 2004-08-02
            Dim firstTime As Boolean = True

            'Changed PM_REMEMBER_SELECTION 2005-03-01
            Dim visualSelection4 As List(Of visibleIndexStruct) = _
              quantApplication.copySelectedIndices3(lstProtHits)


            'Changed PM_CODEMARKER 2008-10-27. Sort protein list by raw file? Less
            '  raw file change for single peptide proteins. Is this worth the
            '  change?


            'Changed PM_REMEMBER_SELECTION 2005-03-01
            ''Changed PM_WORK_ON_SELECTION 2004-07-06. Added this next loop.
            'Dim lastIndex As Integer = lstProtHits.SelectedIndices.Count - 1
            Dim lastVisualIndex3 As Integer = visualSelection4.Count - 1

            Dim i As Integer
            For i = 0 To lastVisualIndex3

                'Changed PM_REMEMBER_SELECTION 2005-03-01
                ''Is this really a protein index???
                ''Dim proteinIndex As Integer = lstProtHits.SelectedIndices.Item(0)
                'Dim proteinIndex As Integer = lstProtHits.SelectedIndices.Item(i)
                Dim visualIndex3 As Integer = visualSelection4(i).visualIdx2
                Dim dataStructureIndex3 As Integer = _
                  Me.getProteinIndexFromVisualIndex(visualIndex3)

                Dim OKtoUse As Boolean = _
                  Me.auto_openPrValFrm2(dataStructureIndex3, firstTime, 0)

                'Changed PM_CMD_EMPTY_PROTEINS 2006-11-22
                'We don't expect empty protein (no peptides) when it is
                'from the visual protein list.
                Trace.Assert(OKtoUse = True, "PIL ASSERT. Empty protein!")

                'Is set as a side-effect of
                'calling openProtValForm(): mCurrentFrmProtValidation.
                mCurrentFrmProtValidation.doUnattentedQuantitation(False)

                mParsedProts2(dataStructureIndex3) = _
                  mCurrentFrmProtValidation.getCurrentProtein_quant() 'Write-back.
            Next i 'Through user selected proteins.
        End If
    End Sub 'mnuQuantOne_Click


    '*****************************menus******************************************

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

        'Note: only changes the visual display, NOT the data structure.
        Dim visualIndex As Integer = lstProtHits.SelectedIndices.Item(0)
        lstProtHits.Items(visualIndex).Checked = False
    End Sub


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub ExportToDatabase_Click( _
      ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles MenuItem3.Click

        'Dim myProteinHits As ProteinHitStructure
        DataExportFunctions.AddData(mParsedProts2, "Test", "Test")
    End Sub 'ExportToDatabase_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub frmProteinList_Closing( _
      ByVal sender As Object, _
      ByVal anEvent As System.ComponentModel.CancelEventArgs) _
      Handles MyBase.Closing

        'Currently we don't close the child windows. We should...

        'Changed PM_CLOSEWARNING 2004-04-21
        If mDirty Then
            If MessageBox.Show( _
              "Close the parse?", AppConstants.LONG_APP, _
              MessageBoxButtons.YesNo, _
              MessageBoxIcon.Warning, _
              MessageBoxDefaultButton.Button2) = _
              Windows.Forms.DialogResult.Yes Then
                'OK to close
                Dim peter92 As Integer = 92
            Else
                ' Cancel the Closing event from closing the form.
                anEvent.Cancel = True
            End If ' Call method to save file...
        Else
            Dim peter91 As Integer = 91
        End If

        Dim peter2 As Integer = 2
    End Sub 'frmProteinList_Closing


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub frmProteinList_Closed( _
      ByVal sender As Object, ByVal e As System.EventArgs) _
      Handles MyBase.Closed

        Dim peter3 As Integer = 3
    End Sub 'frmProteinList_Closed


    '****************************************************************************
    '*    E V E N T   H A N D L E R S ,   lstProtHits                           *
    '****************************************************************************


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

        If False Then
            'Test only!!!!!!!!!
            Dim index As Integer = Me.getProteinIndexFromVisualIndex(0)
            Dim parsProt As ProteinHitStructure = mParsedProts2(index)
            Dim peter2 As Integer = 2
        End If

        Dim physicalIndex As Integer = anEvent.Column
        Dim ID As proteinColumnEnum = _
          CType(mColumnMapper.columnIndex2itemID(physicalIndex), _
            proteinColumnEnum) 'Cast needed because we use the column
        'mapper in many windows, each with their own enumeration type.


        'Changed PM_REFACTOR 2008-11-06
        'Dim keylist As List(Of sortKeyStructure) = Nothing
        'If mColumnSortSpecificationHash.TryGetValue(ID, keylist) Then
        '    mListViewColumnSorter.prepareSort(keylist)
        '    lstProtHits.Sort()
        'Else
        '    'We have not defined sorting for the column in question.
        '    'Simply ignore the request. Should we throw a message
        '    'box instead?
        '    Dim peter1 As Integer = 1
        'End If
        mListViewColumnSorter.prepareSortAndSort(ID, lstProtHits)
    End Sub 'lstProtHits_ColumnClick


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub lstProtHits_DoubleClick(ByVal sender As Object, _
      ByVal anEvent As System.EventArgs) _
      Handles lstProtHits.DoubleClick

        Dim visualIndex As Integer = lstProtHits.SelectedIndices.Item(0)
        Dim proteinIndex As Integer = _
          Me.getProteinIndexFromVisualIndex(visualIndex)

        'Changed PM_DOUBLE_OFFCLICK 2003-12-16
        If mStateDbl = STATE_DBL_SINGLECLICK Then
            Dim prot As ProteinHitStructure = mParsedProts2(proteinIndex)

            'Re-establish check status - it
            'was changed in lstProtHits_ItemCheck().
            Dim savedHandleStatus As Boolean = mAvoidHandlingProteinCheckedEvent
            mAvoidHandlingProteinCheckedEvent = True
            lstProtHits.Items(visualIndex).Checked = mRecentCheckedStatus
            mAvoidHandlingProteinCheckedEvent = savedHandleStatus

            'Also set underlying datastructure just in case.
            prot.proteinHasBeenChecked = mRecentCheckedStatus
            mParsedProts2(proteinIndex) = prot 'Write-back.
        Else
            Dim peter4 As Integer = 4
        End If

        ''Changed PM_DOUBLE_OFFCLICK 2003-12-16
        ''Re-establish check status from underlying datastructure.
        'If False Then
        '    'Dim clickIndex As Integer = anEvent.Index
        '    Dim underLyingCheckStatus As Boolean = prot.proteinHasBeenChecked
        '    lstProtHits.Items(visualIndex).Checked = underLyingCheckStatus
        'End If

        'protItem.Checked = parsProt.proteinHasBeenChecked
        'lstProtHits.Items.Add(protItem)
        'lstProtHits.Items(aSelectedIdx).BackColor() = _
        'Private Function GetProteinArrayIdxFromListIndex(

        'Changed PM_REFACTOR 2006-11-15
        'openProtValForm(visualIndex)
        Dim OKtoUse As Boolean = _
          openProtValForm3(True, proteinIndex, 0)

        'Changed PM_CMD_EMPTY_PROTEINS 2006-11-22
        'We don't expect empty protein (no peptides) when it is
        'from the visual protein list.
        Trace.Assert(OKtoUse = True, "PIL ASSERT. Empty protein!")

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


    'Changed PM_DOUBLE_RETURN_KEY 2007-09-08
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub lstProtHits_KeyDown( _
      ByVal aSender As Object, _
      ByVal anEvent As System.Windows.Forms.KeyEventArgs) _
      Handles lstProtHits.KeyDown

        mKeyObserver.keyDown(anEvent.KeyCode)
    End Sub 'lstProtHits_KeyDown


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

        'Changed PM_DOUBLE_RETURN_KEY 2007-09-08
        If mKeyObserver.keyUp(anEvent.KeyCode) Then
            If lstProtHits.SelectedIndices.Count > 0 Then

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

                Dim dataStructureIndex As Integer = _
                  Me.getProteinIndexFromVisualIndex(visualIndex)
                Dim OKtoUse As Boolean = _
                  openProtValForm3(True, dataStructureIndex, 0)

                'Changed PM_CMD_EMPTY_PROTEINS 2006-11-22
                'We don't expect empty protein (no peptides) when it is
                'from the visual protein list.
                Trace.Assert(OKtoUse = True, "PIL ASSERT. Empty protein!")
            Else
                Dim peter63 As Integer = 63
            End If
        End If
    End Sub 'lstProtHits_KeyUp


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    'Private Sub lstProtHits_DoubleClick(ByVal sender As Object, _
    '  ByVal e As System.Windows.Forms.ItemCheckEventArgs)
    '  Handles lstProtHits.DoubleClick
    '
    '    PanelStatus.Text = _
    '      "TEST. In lstProtHits_DoubleClick(). Value: " & e.NewValue.ToString
    '
    'End Sub 'lstProtHits

    'Changed PM_PROTEINCHECK_SQL 2003-08-15
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub lstProtHits_ItemCheck(ByVal sender As Object, _
      ByVal anEvent As System.Windows.Forms.ItemCheckEventArgs) _
      Handles lstProtHits.ItemCheck

        If Not mAvoidHandlingProteinCheckedEvent Then
            Dim newVal As Boolean = CBool(anEvent.NewValue)
            'Dim newVal As Boolean = CBool(anEvent.CurrentValue)

            Dim visualIndex As Integer = anEvent.Index
            Dim proteinIndex2 As Integer = _
              Me.getProteinIndexFromVisualIndex(visualIndex)

            Dim prot As ProteinHitStructure = mParsedProts2(proteinIndex2)

            'Changed PM_DOUBLE_OFFCLICK 2003-12-16
            mRecentCheckedStatus = prot.proteinHasBeenChecked
            mStateDbl = STATE_DBL_SINGLECLICK

            prot.proteinHasBeenChecked = newVal

            mParsedProts2(proteinIndex2) = prot 'write-back.
        Else
            Dim peter5 As Integer = 5
        End If
    End Sub 'lstProtHits_ItemCheck


    '*****************************lstProtHits************************************

    '****************************************************************************
    '*                                                                          *
    '*    E V E N T   H A N D L E R S ,   E N D                                 *
    '*                                                                          *
    '****************************************************************************

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

        'Idea: make separate object/class to handle this. Then we would
        '      also avoid having to remember to set Enabled to false in the
        '      designer. And the same class could be used in other
        '      windows with menu items that work on a selection, e.g.
        '      the peptide list in the Quantitation window.

        Dim newEnabledState As Boolean = False
        If lstProtHits.SelectedIndices.Count > 0 Then
            newEnabledState = True
        Else
            Dim peter8 As Integer = 8
        End If

        If True Then 'Edit menu
            mnuEditUncheck.Enabled = newEnabledState
            mnuEditCheck.Enabled = newEnabledState
            mnuEditToggleChecked.Enabled = newEnabledState
        End If 'Block, Edit menu

        If True Then 'Automation menu
            mnuQuantOne.Enabled = newEnabledState

            'Changed PM_WORK_ON_SELECTION 2004-07-08
            mnuScoreMS3.Enabled = newEnabledState

            mnuScorePTM.Enabled = newEnabledState

            'Changed PM_AUTODOCUMENTATION 2007-04-17
            mnuReport.Enabled = newEnabledState

            'Changed PM_RECALIB_AFTERPARSE 2007-11-07
            mnuRecalibration.Enabled = newEnabledState

            'Changed PM_RECALIB_VISUAL 2007-09-02
            mnuRecalibVisual.Enabled = newEnabledState

            'Changed PM_RETCORR_ANYTIME 2006-10-25
            mnuRetentionTimeCorrelation.Enabled = newEnabledState
            mnuRemoveInsertedPeptides.Enabled = newEnabledState

            'Changed PM_ZAP_SPECS 2005-02-17
            mnuZapQuantSpecResults.Enabled = newEnabledState

            'Changed PM_ZAP_PEPTIDES 2005-12-01
            mnuRemovePeptides.Enabled = newEnabledState

            'Changed PM_RETRIEVE_PROTEIN_SEQUENCES 2008-04-07
            mnuRetrieveProteinSequences.Enabled = newEnabledState

            'Changed PM_SEQUENCE_COVERAGE 2008-04-16
            mnuComputeAndSetSequenceCoverage.Enabled = newEnabledState

            'Changed PM_PCP_PLOT 2008-09-30
            mnuDisplayProteinProfiles.Enabled = newEnabledState

            'Changed PM_PCP_CONSENSUS_PROFILE 2008-11-05
            mnuSetConsensusProfile.Enabled = newEnabledState
            mnuScoreConsensus.Enabled = newEnabledState

            'Changed PM_PROTEIN_TAGS 2008-10-29
            mnuAddTag.Enabled = newEnabledState
            mnuDeleteAllTags.Enabled = newEnabledState



            'Find if protein sequence is stored in
            '  the dat file. The answer is: no!.
        End If 'Block, Automation menu

        If True Then 'File menu
            mnuExportProteinsAndPeptides.Enabled = newEnabledState
            mnuSaveProteinsAndPeptides.Enabled = newEnabledState

            'Changed PM_DIMMED_EMPTYSELECTION_SAVESPECIAL 2008-01-22
            mnuSaveSelectedProteinHits.Enabled = newEnabledState
        End If


        'Changed PM_DISABLE_EXPORT 2008-05-14. Until export works
        '  again: disable the menu item as we know for certain it
        '   is going tofail.
        '  mnuExportProteinsAndPeptides.Enabled = False

    End Sub 'lstProtHits_SelectedIndexChanged


    'Changed PM_WORK_ON_SELECTION 2004-07-06
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuEditUncheck_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuEditUncheck.Click

        'Changed PM_REFACTOR 2008-05-01
        quantApplication.setCheckedStatusForSelected( _
          DirectCast(lstProtHits, ListView), False)

        'Old code. Delete at any time.
        'Dim lastIndex As Integer = lstProtHits.Items.Count - 1
        'Dim i As Integer
        'For i = 0 To lastIndex
        '    If lstProtHits.Items(i).Selected Then
        '        lstProtHits.Items(i).Checked = False
        '    End If
        'Next
    End Sub 'mnuEditUncheck_Click


    'Changed PM_WORK_ON_SELECTION 2004-07-06
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuEditCheck_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuEditCheck.Click

        'Changed PM_REFACTOR 2008-05-01
        quantApplication.setCheckedStatusForSelected( _
          DirectCast(lstProtHits, ListView), True)

        'Old code. Delete at any time.
        'Dim lastIndex As Integer = lstProtHits.Items.Count - 1
        'Dim i As Integer
        'For i = 0 To lastIndex
        '    If lstProtHits.Items(i).Selected Then
        '        lstProtHits.Items(i).Checked = True
        '    End If
        'Next
    End Sub 'mnuEditCheck_Click


    'Changed PM_WORK_ON_SELECTION 2004-07-06
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuEditToggleChecked_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuEditToggleChecked.Click

        'Changed PM_REFACTOR 2008-05-01
        quantApplication.toggleCheckedStatusForSelected( _
          DirectCast(lstProtHits, ListView))

        'Old code. Delete at any time.
        'Dim lastIndex As Integer = lstProtHits.Items.Count - 1
        'Dim i As Integer
        'For i = 0 To lastIndex
        '    If lstProtHits.Items(i).Selected Then
        '        lstProtHits.Items(i).Checked = Not (lstProtHits.Items(i).Checked)
        '    End If
        'Next
    End Sub 'mnuEditToggleChecked_Click


    'Changed PM_WORK_ON_SELECTION 2004-07-06
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuEditSelectAll_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuEditSelectAll.Click

        quantApplication.selectOrUnselect( _
          DirectCast(lstProtHits, ListView), False, True)

        'Changed PM_REFACTOR 2008-05-01
        'Dim lastIndex As Integer = lstProtHits.Items.Count - 1
        'Dim i As Integer
        'For i = 0 To lastIndex
        '    lstProtHits.Items(i).Selected = True
        'Next
    End Sub 'mnuEditSelectAll_Click()


    'Changed PM_UNSELECT_ALL 2008-11-08
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuEditUnselectAll_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuEditUnselectAll.Click

        quantApplication.selectOrUnselect( _
          DirectCast(lstProtHits, ListView), False, False)

    End Sub 'mnuEditUnselectAll_Click()


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

        'Changed PM_REFACTOR 2008-05-01. Note: the sync check is
        '  now no longer in effect. We have never detected a problem.
        quantApplication.selectOrUnselect( _
          DirectCast(lstProtHits, ListView), True, True)
    End Sub 'mnuEditSelectChecked_Click


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

        'Changed PM_REFACTOR 2008-05-01
        quantApplication.invertSelection(DirectCast(lstProtHits, ListView))

        'Changed PM_REFACTOR 2008-05-01
        'Dim lastIndex As Integer = lstProtHits.Items.Count - 1
        'Dim i As Integer
        'For i = 0 To lastIndex
        '    lstProtHits.Items(i).Selected = Not lstProtHits.Items(i).Selected
        'Next
    End Sub 'mnuEditInvertSelection_Click


    '****************************************************************************
    '****************************************************************************
    '****************************************************************************


    'Start
    '****************************************************************************
    '****************************************************************************
    '****************************************************************************
    '****************************************************************************
    '****************************************************************************
    '****************************************************************************
    '****************************************************************************
    '****************************************************************************
    '****************************************************************************
    '****************************************************************************
    '****************************************************************************
    '****************************************************************************



    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function selectedIndices2DatastructureIndices2( _
      ByRef anInVisualIndices2 As List(Of visibleIndexStruct)) _
      As List(Of Integer)
        'Old:
        '  ByRef anInVisualIndices As ArrayList
        '  As ArrayList

        'Changed PM_MEMORY_EFFICIENCY 2008-09-25
        'Dim toReturn As List(Of Integer) = New List(Of Integer)
        Dim len As Integer = anInVisualIndices2.Count
        Dim toReturn As List(Of Integer) = New List(Of Integer)(len)

        'Changed PM_DEADCODE 2008-05-06
        'Not used???
        'Dim protein_visualIndices As List(Of Integer) = _
        '  quantApplication.copySelectedIndices2( _
        '    lstProtHits.SelectedIndices)

        Dim visualIndex4 As visibleIndexStruct
        For Each visualIndex4 In anInVisualIndices2
            Dim dataStructureIndex4 As Integer = _
              Me.getProteinIndexFromVisualIndex(visualIndex4.visualIdx2)


            If dataStructureIndex4 < 0 Then
                Dim peter2 As Integer = 2
            End If

            toReturn.Add(dataStructureIndex4)
        Next

        Return toReturn
    End Function 'selectedIndices2DatastructureIndices2


    'Changed PM_COMMANDLINE_EXPORT 2008-08-22
    '****************************************************************************
    '*    Used when the application is called with command line parameters.     *
    '*                                                                          *
    '****************************************************************************
    Public Sub exportProteinsAndPeptides2( _
      ByRef aProteinDataIndexes As List(Of Integer))

        'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
        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.
        '
        'This will halt the automatic run!!!. But otherwise it would
        'probably fail a little bit later...

        PILInputOutput.pushToTarget( _
 _
          Me.exportProteinsAndPeptides_Common3( _
            mOptions.proteinAndPeptidesFilter, _
            aProteinDataIndexes), _
 _
          exportTargetSettings, _
          appPath() _
        )
    End Sub 'exportProteinsAndPeptides2()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function exportProteinsAndPeptides_Common3( _
      ByVal aInProteinAndPeptidesFilter2 As proteinAndPeptidesFilterStructure2, _
      ByRef aProteinDataIndexes As List(Of Integer)) _
      As String

        Dim toReturn As String = ""
        Dim selLen As Integer = -1

        Try
            selLen = aProteinDataIndexes.Count
            If selLen > 0 Then

                'Changed PM_EXPORTED_FEEDBACK 2008-09-25
                mApplication.startStopWatch()

                toReturn = quantApplication.xxFormatTextPeptides3( _
                  aInProteinAndPeptidesFilter2, _
                  aProteinDataIndexes, mParsedProts2, _
                  mRecalibrator, mOptions.quantModeCode, mApplication, _
                  mOptions, _
                  Nothing)

                'Changed PM_EXPORTED_FEEDBACK 2008-09-25
                'Output message to window about the completed export.
                If True Then
                    'For now we just need some feedback. If more detailed 
                    'information is needed (e.g. the name of the file exported
                    'to, number of peptides, size of export in bytes, number
                    'of spectra, etc. then we would need 
                    'xxFormatTextPeptides3() to generate it.

                    Dim memDiff_MB As Double
                    Dim parseTimeSecs As Double = _
                      mApplication.stopStopWatch(memDiff_MB)

                    'Candidate for refactor (for other menu items)?:
                    Dim msg As String = _
                      """" & "Export Protein and Peptides Information" & _
                      """ menu command completed. Time: " & _
                      parseTimeSecs.ToString("0.00") & " seconds. " & _
                      "Exported information for " & selLen & " proteins."

                    PanelStatus.Text = msg
                End If 'Block.

            End If 'Any selected proteins (for export).

        Catch exceptionObject As Exception
            displayStandardExceptionInfo( _
              exceptionObject, _
              "Could not export the selected " & selLen & " proteins.")
        End Try

        Return toReturn
    End Function 'exportProteinsAndPeptides_Common3


    'Changed PM_PARSINGREPORT_FAILS_MB3 2007-11-26
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function checkRecalibReport(ByRef anOutReport As String) _
      As Boolean

        anOutReport = ""
        Dim toReturn As Boolean = False

        If Not mRecalibReport Is Nothing Then
            toReturn = True
            anOutReport = mRecalibReport.ToString()
        Else
            MsgBox( _
              "The recalibration report could not be generated. " & _
              "The report is not saved along with a saved parse. " & _
              "Re-parse or use menu Automation/Recalibration and Validation " & _
              "in order to be able to generate the report.")
        End If

        Return toReturn
    End Function 'saveRecalibReportCommon


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

        'Changed PM_PARSINGREPORT_FAILS_MB3 2007-11-26
        Dim reportStr As String = Nothing 'Keep compiler happy.
        If checkRecalibReport(reportStr) Then

            'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
            Dim exportTargetSettings As exportTargetSettingsStruct = _
              Me.getGlobalTargetSettings()

            PILInputOutput.pushToTarget(reportStr, _
              exportTargetSettings, _
              appPath())
        End If
    End Sub 'mnuExportRecalibReport_Click


    'Changed PM_MS3INTEGRATION 2004-06-03
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuScoreMS3_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuScoreMS3.Click

        'For now we just refuse if there is no selection, but the real
        'solution should be to disable menu item when
        'there is no selection.
        If lstProtHits.SelectedIndices.Count > 0 Then

            'Changed PM_MEMORY_ALLOCATION 2004-08-02
            Dim firstTime As Boolean = True

            'Changed PM_REMEMBER_SELECTION 2005-03-01
            Dim visualSelection4 As List(Of visibleIndexStruct) = _
              quantApplication.copySelectedIndices3(lstProtHits)

            'Changed PM_REMEMBER_SELECTION 2005-03-01
            ''Changed PM_WORK_ON_SELECTION 2004-07-08. Added this next loop.
            'Dim lastIndex As Integer = lstProtHits.SelectedIndices.Count - 1
            Dim lastVisualIndex3 As Integer = visualSelection4.Count - 1

            Dim i As Integer
            For i = 0 To lastVisualIndex3
                'Changed PM_REMEMBER_SELECTION 2005-03-01
                ''Dim proteinIndex As Integer = lstProtHits.SelectedIndices.Item(0)
                'Dim proteinIndex As Integer = lstProtHits.SelectedIndices.Item(i)
                Dim visualIndex3 As Integer = visualSelection4(i).visualIdx2
                Dim dataStructureIndex3 As Integer = _
                  Me.getProteinIndexFromVisualIndex(visualIndex3)

                Dim OKtoUse As Boolean = _
                  Me.auto_openPrValFrm2( _
                    dataStructureIndex3, firstTime, 0)

                'Changed PM_CMD_EMPTY_PROTEINS 2006-11-22
                'We don't expect empty protein (no peptides) when it is
                'from the visual protein list.
                Trace.Assert(OKtoUse = True, "PIL ASSERT. Empty protein!")

                'Dim useNewWindows As Boolean = True 'Not mMenuQuantOneUsed
                'openProtValForm(proteinIndex, useNewWindows) 'Note: with this change
                ''  only ONE protein validation can be opened......

                Dim toStop As Boolean = _
                  mCurrentFrmProtValidation.doUnattentedMS3scoring(False)

                'What about recomputing of protein score???????????

                'Note: this may already be done, by calling of updateProtein from child....
                mParsedProts2(dataStructureIndex3) = _
                  mCurrentFrmProtValidation.getCurrentProtein_ms3() 'Write-back.
            Next
        Else
            MsgBox("Could not complete action. No protein or proteins is/are selected. Select one or more proteins first.")
        End If
    End Sub 'mnuScoreMS3_Click


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

        If lstProtHits.SelectedIndices.Count > 0 Then
            Dim firstTime As Boolean = True
            Dim visualSelection4 As List(Of visibleIndexStruct) = _
              quantApplication.copySelectedIndices3(lstProtHits)

            Dim lastVisualIndex3 As Integer = visualSelection4.Count - 1
            Dim i As Integer
            For i = 0 To lastVisualIndex3
                Dim visualIndex3 As Integer = visualSelection4(i).visualIdx2

                'Changed PM_REFACTOR 2006-11-15
                'openProtValForm(visualIndex3, openNew)
                Dim dataStructureIndex As Integer = _
                  Me.getProteinIndexFromVisualIndex(visualIndex3)

                Dim OKtoUse As Boolean = _
                  Me.auto_openPrValFrm2( _
                    dataStructureIndex, firstTime, 0)

                'Changed PM_CMD_EMPTY_PROTEINS 2006-11-22
                'We don't expect empty protein (no peptides) when it is
                'from the visual protein list.
                Trace.Assert(OKtoUse = True, "PIL ASSERT. Empty protein!")

                Dim toStop As Boolean = _
                  mCurrentFrmProtValidation.doUnattendedPTMscoring()
            Next
        End If
    End Sub 'mnuScorePTM_Click


    'Changed PM_ZAP_SPECS 2005-02-17
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuZapQuantSpecResults_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuZapQuantSpecResults.Click


        'Changed PM_MISPLACED_CODE 2008-07-14
        ''Changed PM_SEQUENCE_COVERAGE 2008-04-15
        'computeAndSetSequenceCoverage() 'Temp!!!!!!!!!!!!!!!!


        'Changed PM_AVOID_ARRAYINDEX_OUTOFRANGE 2003-03-31
        'For now we just refuse if there is no selection, but the real 
        'solution should be to disable menu item when there is no selection.
        If lstProtHits.SelectedIndices.Count > 0 Then

            Dim zapCounter As Integer = 0
            Dim zapCounter_peptides As Integer = 0
            Dim zapCounter_proteins As Integer = 0

            'Changed PM_REMEMBER_SELECTION 2005-03-01
            Dim visualSelection4 As List(Of visibleIndexStruct) = _
              quantApplication.copySelectedIndices3(lstProtHits)

            Dim lastVisualIndex3 As Integer = visualSelection4.Count - 1

            Dim i As Integer
            For i = 0 To lastVisualIndex3

                'Changed PM_REMEMBER_SELECTION 2005-03-01
                ''Is this really a protein index???
                'Dim proteinIndex As Integer = lstProtHits.SelectedIndices.Item(i)
                Dim visualIndex3 As Integer = visualSelection4(i).visualIdx2
                Dim dataStructureIndex3 As Integer = _
                  Me.getProteinIndexFromVisualIndex(visualIndex3)

                Dim someProt As ProteinHitStructure = _
                  mParsedProts2(dataStructureIndex3)

                Dim dirty As Boolean = False

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

                Dim pepIter As peptideListIterator = _
                  New peptideListIterator(someProt.peptides)
                'For j = 0 To lastIndex2
                While Not pepIter.nextPeptide(pept)

                    'Changed PM_REFACTOR 2006-03-15
                    'If Not DirectCast( _
                    '        someProt.pepts(j), _
                    '        PeptideHitStructure _
                    '    ).specs Is Nothing Then
                    If Not pept.spectra Is Nothing Then
                        zapCounter += pept.spectra.Count

                        pept.spectra = Nothing

                        'Changed PM_NOQUANTEXPORT_AFTER_ZAPPED_BUG 2007-04-13
                        'Do not zap this - contains peptide quant values
                        'that we want to keep for exporting.
                        'pept.LCprofilesProperties = Nothing

                        pept.LCpeakProfiles = Nothing
                        pept.quantValues2 = Nothing

                        'Changed PM_REFACTOR 2006-03-15
                        'someProt.pepts(j) = somePeptide 'Write-back...
                        pepIter.updateCurrentPeptide(pept)

                        dirty = True
                        zapCounter_peptides += 1
                    End If

                End While 'Through peptides.

                If dirty Then
                    mParsedProts2(dataStructureIndex3) = someProt 'Write-back...

                    Application.DoEvents()
                End If
                zapCounter_proteins += 1
            Next i

            If True Then
                Dim memDiffMB As Double
                Dim tickTimeSecs As Double
                quantApplication.GarbageCollect(Nothing, memDiffMB, tickTimeSecs)

                MsgBox("Zapped information from " & zapCounter & " spectra from " & _
                       zapCounter_peptides & " quantified peptides from " & _
                       zapCounter_proteins & " selected proteins. " & _
                       "Purged " & memDiffMB.ToString("0.00") & " MB.")
            End If
        Else
            MsgBox("Could not complete action. No protein or proteins is/are selected. Select one or more proteins first.")
        End If 'mnuZapQuantSpecResults_Click
    End Sub 'mnuZapQuantSpecResults_Click


    'Changed PM_ZAP_PEPTIDES 2005-12-01
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuRemovePeptides_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuRemovePeptides.Click

        'Changed PM_SAVING_REMOVEDPEPTIDES_BUG 2007-09-07.
        'Only needed if we continue using preparePeptideForQuantitation() below.
        Dim quantitationModesObject As QuantitationModes_moreGeneral = _
          mApplication.getQuantModes()
        Dim curQuantMode As generalisedQuantModeStructure = _
          quantitationModesObject.getQuantitationMode( _
            mOptions.quantModeCode)

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

        someEmptyPeptide.AASequence = "ZZZDELETEDALLPEPTIDES"

        'someEmptyPeptide.MSMSretentionTimeMinutes = 5.0
        'someEmptyPeptide.retentionTimeStartMinutes = 5.0
        'someEmptyPeptide.spectrumNumber = 800
        'someEmptyPeptide.experimentNumber = 1
        'someEmptyPeptide.rawFileID = _
        '  MultipleRawFilesHandling.RAWFILEREF_NOTMULTIPLE

        someEmptyPeptide.charge = 2

        someEmptyPeptide.MascotScore2 = 5.0
        someEmptyPeptide.verified = False

        'Changed PM_ASSERT_DELETING_PEPTIDES_FOR_COMBININED_FILES 2006-03-24
        'Flag so we can copy fields from some valid peptide
        someEmptyPeptide.queryNumber = -1

        Dim zapCounter_peptides As Integer = 0
        Dim zapCounter_proteins As Integer = 0

        Dim visualSelection4 As List(Of visibleIndexStruct) = _
          quantApplication.copySelectedIndices3(lstProtHits)
        Dim lastVisualIndex3 As Integer = visualSelection4.Count - 1

        Dim i As Integer
        For i = 0 To lastVisualIndex3
            Dim visualIndex3 As Integer = visualSelection4(i).visualIdx2
            Dim dataStructureIndex3 As Integer = _
              Me.getProteinIndexFromVisualIndex(visualIndex3)

            Dim someProt As ProteinHitStructure = _
              mParsedProts2(dataStructureIndex3)

            'Changed PM_ASSERT_DELETING_PEPTIDES_FOR_COMBININED_FILES 2006-03-24
            'We need a valid spectrum number or retention time as the
            'spectrum for the first peptide in a protein will be displayed
            'if the user opens the protein after the peptides have been deleted.
            Dim pepIter As peptideListIterator = _
              New peptideListIterator(someProt.peptides)
            If someEmptyPeptide.queryNumber < 0 Then
                someEmptyPeptide.queryNumber = 9999

                Dim firstPeptide As PeptideHitStructure = _
                  PeptideHitStructure.blankPeptide()

                pepIter.nextPeptide(firstPeptide)

                someEmptyPeptide.MSMSretentionTimeMinutes = _
                  firstPeptide.MSMSretentionTimeMinutes
                someEmptyPeptide.retentionTimeStartMinutes = _
                  firstPeptide.retentionTimeStartMinutes
                someEmptyPeptide.retentionTimeEndMinutes = _
                  firstPeptide.retentionTimeEndMinutes
                someEmptyPeptide.spectrumNumber = firstPeptide.spectrumNumber
                someEmptyPeptide.experimentNumber = firstPeptide.experimentNumber
                someEmptyPeptide.period2 = firstPeptide.period2
                someEmptyPeptide.cycle = firstPeptide.cycle

                'This needed. Otherwise we would get an ASSERT for
                'combined files.
                someEmptyPeptide.rawFileID = firstPeptide.rawFileID

                someEmptyPeptide.MascotCalculatedMass = _
                  firstPeptide.MascotCalculatedMass
                someEmptyPeptide.measuredMCR = firstPeptide.measuredMCR

                someEmptyPeptide.missedCleavages = firstPeptide.missedCleavages

                someEmptyPeptide.leftFlankAA = firstPeptide.leftFlankAA
                someEmptyPeptide.rightFlankAA = firstPeptide.rightFlankAA

                'Changed PM_SAVING_REMOVEDPEPTIDES_BUG 2007-09-07. Needed, 
                '  otherwise we get an exception during save.
                'To avoid exceptions and ASSERT later when saving...
                Dim dummy1 As FindLCpeaks.multModCounterStructure
                Dim peptideInvalidated As Boolean
                someEmptyPeptide = _
                  FindLCpeaks.preparePeptideForQuantitation( _
                    someEmptyPeptide, _
                    curQuantMode, _
                    dummy1, _
                    peptideInvalidated) 'Reuse pept.... OK?

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

                'Changed PM_ELIMINATE_PEPTIDEFIELD 2008-11-25. Delete at any time.
                'someEmptyPeptide.version = 100 'Vers. 1.00.  With
                'this change: redundancy...
            End If

            'Changed PM_REFACTOR 2006-03-15
            'Dim peptides As Integer = someProt.pepts.Count
            'someProt.pepts = Nothing 'Zap 'em !
            'someProt.pepts = New ArrayList
            'someProt.pepts.Add(someEmptyPeptide)

            'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-27
            Dim iterToken As Integer = pepIter.getIterToken()

            Dim peptides As Integer = someProt.peptides.peptideCount2(iterToken)

            someProt.peptides = Nothing 'Zap 'em !
            someProt.peptides = New PILpeptides(1) '1 for the lone empty peptide...
            someProt.peptides.addPeptide(someEmptyPeptide)

            mParsedProts2(dataStructureIndex3) = someProt 'Write-back...

            zapCounter_peptides += peptides
            zapCounter_proteins += 1
        Next

        If True Then
            Dim memDiffMB As Double
            Dim tickTimeSecs As Double
            quantApplication.GarbageCollect(Nothing, memDiffMB, tickTimeSecs)

            MsgBox("Removed " & _
                   zapCounter_peptides & " peptides for good from " & _
                   zapCounter_proteins & " selected proteins. " & _
                   "Purged " & memDiffMB.ToString("0.00") & " MB.")
        End If
    End Sub 'mnuRemovePeptides_Click


    'Changed PM_REFACTOR 2005-03-15
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function proteinIndexFromHitNumber( _
      ByVal anInProteinHitNumber As Integer) As Integer

        Dim toReturn As Integer = -1

        'Changed PM_VISUAL_COLUMNSORT 2006-02-24. This is much easier....
        'Dim lastProteinIndex As Integer = mParsedProts.Count - 1
        ''Linear search.... As the datastructure is sorted by hitnumber we
        ''  could use binary search instead.
        'Dim i As Integer
        'For i = 0 To lastProteinIndex
        '    If DirectCast(mParsedProts(i), _
        '                  ProteinHitStructure).hitNumber = _
        '            anInProteinHitNumber Then
        '
        '        toReurn = i
        '        Exit For
        '    End If
        'Next

        Trace.Assert(mProteinHitNumber2dataIndex.Count > 0, _
          "PIL ASSERT. mProteinHitNumberHash is empty!.")

        'Changed PM_TYPESAFE_HASH 2008-09-25
        'toReturn = CInt(mProteinHitNumberHash(anInProteinHitNumber))
        toReturn = mProteinHitNumber2dataIndex(anInProteinHitNumber)

        Return toReturn
    End Function 'proteinIndexFromHitNumber


    'Changed PM_VISUAL_COLUMNSORT 2006-02-24
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function getProteinIndexFromVisualIndex( _
      ByVal aVisualIndex As Integer) _
      As Integer

        Dim toReturn As Integer = -1

        Dim rowToRead As ListViewItem = lstProtHits.Items(aVisualIndex)
        Dim hitNumStr As String = _
          mColumnMapper.readOffListItem( _
            rowToRead, _
            proteinColumnEnum.enumProteinHitNumber)

        Dim hitNum As Integer
        If IsNumeric(hitNumStr) Then
            hitNum = CInt(hitNumStr)
        Else
            MsgBox("Could not extract hitNum number from table")
        End If

        toReturn = Me.proteinIndexFromHitNumber(hitNum)

        Return toReturn
    End Function 'getProteinIndexFromVisualIndex


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function getProteinFromVisualIndex( _
      ByVal aVisualIndex As Integer, _
      ByRef anOutDatastructureIndex As Integer) _
      As ProteinHitStructure

        Dim idx As Integer = Me.getProteinIndexFromVisualIndex(aVisualIndex)
        Dim prot As ProteinHitStructure = mParsedProts2(idx)
        anOutDatastructureIndex = idx
        Return prot
    End Function 'getProteinFromVisualIndex


    'Changed PM_FIND 2006-07-28
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuFind_Click( _
      ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles mnuFind.Click

        Dim findDlg As frmFind = New frmFind(Me, mFindParameters)

        'Changed PM_OWNEDFORM 2006-07-27
        Me.AddOwnedForm(findDlg)
        findDlg.Show()
    End Sub 'mnuFind_Click


    'Changed PM_FIND 2006-07-28
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub SetFindParams( _
      ByVal aFindParameters As frmFind.findParametersStructure)

        mFindParameters = aFindParameters 'To save for next find.

        'Do the find...

        Dim ignoreCase As Boolean = Not aFindParameters.matchCase2

        Dim clearSelection As Boolean = _
          aFindParameters.clearSelectionBeforeSearch

        Dim onlyInSelection As Boolean = aFindParameters.onlySearchSelection

        'If we search only in the selection then it only makes sense to
        'clear the selection first before the search.
        Trace.Assert(Not onlyInSelection Or clearSelection = True, _
          "PIL ASSERT. Selection must be cleared before the search.")

        Dim findStr As String = aFindParameters.toFind
        If ignoreCase Then
            findStr = findStr.ToUpper()
        End If

        Dim lastVisualIndex As Integer = lstProtHits.Items.Count - 1

        Dim matchesFound As Integer = 0
        Dim consideredCount As Integer = 0

        Dim visualIndex As Integer
        For visualIndex = 0 To lastVisualIndex Step 1

            Dim considerThisItem As Boolean = True
            If onlyInSelection Then
                Dim itemIsSelected As Boolean = _
                  DirectCast(lstProtHits.Items(visualIndex), _
                    System.Windows.Forms.ListViewItem).Selected
                If Not itemIsSelected Then
                    considerThisItem = False
                End If
            End If

            If considerThisItem Then
                consideredCount += 1

                Dim dataStructureIndex As Integer = _
                  Me.getProteinIndexFromVisualIndex(visualIndex)

                Dim parsProt As ProteinHitStructure = _
                  mParsedProts2(dataStructureIndex)

                Dim descr As String = Nothing
                If ignoreCase Then
                    descr = parsProt.description3.ToUpper()
                Else
                    descr = parsProt.description3
                End If

                Dim changeValue As Boolean = False
                Dim newValue As Boolean = False

                If clearSelection Then
                    changeValue = True
                    newValue = False
                End If

                Dim idx As Integer = descr.IndexOf(findStr)
                If idx >= 0 Then
                    changeValue = True
                    newValue = True
                    matchesFound += 1
                End If

                If changeValue Then
                    DirectCast(lstProtHits.Items(visualIndex), _
                      System.Windows.Forms.ListViewItem).Selected = newValue
                Else
                    Dim peter7 As Integer = 7
                End If
            Else
                Dim peter8 As Integer = 8 'Not selected.
            End If
        Next visualIndex

        'PanelStatus.Text = progTxt
        'PanelProteinsParsed.Text =

        Dim findResultStr As String = _
          matchesFound & " items found in " & _
          consideredCount & " considered."
        PanelStatus.Text = findResultStr
        Application.DoEvents()

        If matchesFound = 0 Then
            Dim msgStr As String = _
              "Search string not found in " & consideredCount & _
              " considered proteins!"
            MsgBox(msgStr, MsgBoxStyle.Exclamation, AppConstants.LONG_APP)
        End If
    End Sub 'SetFindParams


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

        'Dim lineOffset As Integer = 5 'To display some proteins before the
        ''  one we are going to make visible.

        Dim someRow As ListViewItem = lstProtHits.TopItem
        Dim visibleFirstVisualIndex As Integer = someRow.Index

        'If visibleFirstVisualIndex = 0 AndAlso mOldVisibleFirstVisualIndex = 0 Then
        '    mSelectedToScrollToNext = 1 'One based.
        'End If

        'Dim startIndex As Integer = visibleFirstVisualIndex + lineOffset + 1
        Dim startIndex As Integer = visibleFirstVisualIndex + 1
        '  1: ....

        Dim lastVisualIndex As Integer = lstProtHits.Items.Count - 1

        Dim visualIndex As Integer
        For visualIndex = startIndex To lastVisualIndex Step 1

            Dim pos As Point = someRow.Position

            Dim itemIsSelected As Boolean = _
              DirectCast(lstProtHits.Items(visualIndex), _
                System.Windows.Forms.ListViewItem).Selected

            If itemIsSelected Then
                DirectCast(lstProtHits.Items(visualIndex), _
                  System.Windows.Forms.ListViewItem).EnsureVisible()

                lstProtHits.EnsureVisible(visualIndex)

                Dim newIndex As Integer = lstProtHits.TopItem.Index

                'Continue until actual scrolling takes place.
                If newIndex <> visibleFirstVisualIndex Then
                    Exit For
                End If

                'Is is possible to scroll to a ***particular***
                'location???? - lineOffset
            End If
        Next

    End Sub 'mnuScrollToNextSelected_Click


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

        Dim reportStr As String = mMascotResultParser.getCorrelationReport()

        'Changed PM_CORRREPORT_NODATA_IN_MB3 2008-09-18. No information when 
        '  protein list is loaded from MB3, only just after parsing.
        If reportStr.Length > 10 Then

            'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
            Dim exportTargetSettings As exportTargetSettingsStruct = _
              Me.getGlobalTargetSettings()

            PILInputOutput.pushToTarget(reportStr, _
              exportTargetSettings, _
              appPath())
        Else
            Dim MBinfo As AppConstants.savedMBfilesInfoStruct = _
              AppConstants.currentConstantsForSavingMB()

            Dim msgStr As String = _
              "Could not export correlation information. " & _
              "This information is not available from a loaded " & _
              "parse (" & MBinfo.fileExtensionWithDot & "). " & _
              "Use the menu command on a protein list that has just been parsed."
            MsgBox(msgStr)
        End If
    End Sub 'mnuExportCorrelationReport_Click


    'Changed PM_REPORTS 2006-08-15
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuExportParseReport_Click( _
      ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles mnuExportParseReport.Click

        Dim reportStr As String = mParseReport.getTabularReport()

        'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
        Dim exportTargetSettings As exportTargetSettingsStruct = _
          Me.getGlobalTargetSettings()


        'Changed PM_AVOID_EXCEL 2008-08-21. Use last setting from the export proteins and peptides...
        ''Changed PM_BROKENEXPORT 2008-05-28
        ''Excel for now.
        'Dim ex As exportTargetSettingsStruct = _
        '  exportTargetSettingsStruct.defaultExportTargetSettings()
        'ex.target = targetEnum.enumExportToExcel
        'PILInputOutput.pushToTarget(reportStr, ex)
        PILInputOutput.pushToTarget( _
          reportStr, _
          exportTargetSettings, _
          appPath())

    End Sub 'mnuExportParseReport_Click


    'Changed PM_RETCORR_ANYTIME 2006-10-26
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub startRetentionTimeCorrelation(ByVal aSelectedProteins As Integer)

        Dim form As New frmRetentionCorrSettings( _
          mRetCorrParameters, Me, aSelectedProteins)
        form.Show()
    End Sub 'startRetentionTimeCorrelation


    'Changed PM_RETCORR_ANYTIME 2006-10-26
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub setRetCorrParameters( _
      ByVal aRetCorrParameters As retCorrParametersStructure)

        mRetCorrParameters = aRetCorrParameters

        Dim correlator As retentionTimeCorrelator = _
          New retentionTimeCorrelator( _
            mRetCorrParameters.retentionTimeType)

        Dim quantitationModesObject As QuantitationModes_moreGeneral = _
          mApplication.getQuantModes()
        Dim noQuantMode As Boolean = _
          quantitationModesObject.isNoQuantitationMode( _
            mOptions.quantModeCode)

        Dim visualSelection2 As List(Of visibleIndexStruct) = _
          quantApplication.copySelectedIndices3(lstProtHits)

        Dim lastVisualIndex As Integer = visualSelection2.Count - 1
        Dim i As Integer
        For i = 0 To lastVisualIndex
            Dim visualIndex As Integer = visualSelection2(i).visualIdx2

            Dim dataStructureIndex3 As Integer = _
              Me.getProteinIndexFromVisualIndex(visualIndex)

            'mParsedProts(dataStructureIndex3) = _
            '  mCurrentFrmProtValidation.getCurrentProtein_quant() 'Write-back.

            Dim proteinHit As ProteinHitStructure = _
              mParsedProts2(dataStructureIndex3)

            'Changed PM_MARKER_VALIDATION_AS_PEPTFILTER 2007-09-05. Uses the old
            '  field peptDefaultValidationScoreThr2. What should it be?
            correlator.updateWithPeptidesFromOneProtein( _
              proteinHit, dataStructureIndex3, _
              mOptions.peptDefaultValidationScoreThr2, _
              noQuantMode)
        Next

        'Changed PM_RIGHT_AFTER_PARSE_RETENTIONTIME 2007-01-08. Necessary if
        '  done right after parse (previously only worked for a loaded parse).
        Me.createMultipleRawFilesHandlingObject(mWiffFile.sampleNumberInRawFile)

        'For now.
        Dim doNotInsertNewPeptides As Boolean = False
        Dim insertPeptidesInLCTimeRange As Boolean = False 'False: meaning
        '  for all retention times. The two values below are ignored.
        Dim startLCtimeForInsertion_Secs As Double = 0.0
        Dim endLCtimeForInsertion_Secs As Double = 1.0E+20

        'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-24
        'Dim peptideFilter As peptideFilterSpecificationStructure = _
        '  mOptions.peptideFilterSpecification
        Dim peptideFilter As peptideFilterStructure = _
          mOptions.peptideFilters(peptideFilterEnum.enumParsing2)

        quantApplication.postProteinParsing( _
          correlator, _
          mRawFiles2, _
          doNotInsertNewPeptides, _
          mParsedProts2, _
          mMultipleRawFilesHandling2, _
          insertPeptidesInLCTimeRange, _
          startLCtimeForInsertion_Secs, _
          endLCtimeForInsertion_Secs, _
          peptideFilter, _
          mApplication _
          )

        If True Then
            Dim corrStr As String = correlator.getCorrelationReport()

            'It may fail on some computers. Call the save to file
            'version in the exception handler?.
            Try
                'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
                Dim exportTargetSettings As exportTargetSettingsStruct = _
                  Me.getGlobalTargetSettings()

                'Changed PM_AVOID_EXCEL 2008-08-21. Use last setting from the export proteins and peptides...
                ''Changed PM_BROKENEXPORT 2008-05-28
                ''Excel for now.
                'Dim ex As exportTargetSettingsStruct = _
                '  exportTargetSettingsStruct.defaultExportTargetSettings()
                'ex.target = targetEnum.enumExportToExcel
                'PILInputOutput.pushToTarget(corrStr, ex)
                PILInputOutput.pushToTarget(corrStr, _
                  exportTargetSettings, _
                  appPath())

            Catch exceptionObject As Exception
                displayStandardExceptionInfo( _
                  exceptionObject, _
                  "Could export the retention time correlation.")
                Exit Sub
            End Try
        End If 'Block.
    End Sub 'setRetCorrParameters


    'Changed PM_RETCORR_ANYTIME 2006-10-24
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuRetentionTimeCorrelation_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuRetentionTimeCorrelation.Click

        Dim selectedProteins As Integer = lstProtHits.SelectedIndices.Count
        If selectedProteins > 0 Then
            Me.startRetentionTimeCorrelation(selectedProteins)
        End If
    End Sub 'mnuRetentionTimeCorrelation_Click


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

        If lstProtHits.SelectedIndices.Count > 0 Then
            Dim visualSelection2 As List(Of visibleIndexStruct) = _
              quantApplication.copySelectedIndices3(lstProtHits)

            Dim lastVisualIndex As Integer = visualSelection2.Count - 1
            Dim i As Integer
            For i = 0 To lastVisualIndex
                Dim visualIndex As Integer = visualSelection2(i).visualIdx2
                Dim dataStructureIndex3 As Integer = _
                  Me.getProteinIndexFromVisualIndex(visualIndex)

                Dim proteinHit As ProteinHitStructure = _
                  mParsedProts2(dataStructureIndex3)

                proteinHit.peptides.zapPeptides_queryRange( _
                  -2000000000, 0)

                mParsedProts2(dataStructureIndex3) = proteinHit 'Write-back.
            Next
        End If

        'Display statistics here? Number zapped peptides xx selected proteins.
    End Sub 'mnuRemoveInsertedPeptides_Click


    'Changed PM_COMMANDLINE 2006-11-16
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub getDataIndicesFromProteinNumbers( _
      ByVal aStartProteinNumber As Integer, _
      ByVal anEndProteinNumber As Integer, _
      ByRef anOutStartDataIndex As Integer, _
      ByRef anOutEndDataIndex As Integer, _
      ByRef anOutEmptyRange As Boolean _
      )
        Dim lastIndex As Integer = mParsedProts2.Count() - 1

        anOutStartDataIndex = 0
        anOutEndDataIndex = lastIndex

        'Changed PM_CMD_NO_FIRST_PROTEIN 2006-11-22
        Dim firstIndexFound As Boolean = False

        If aStartProteinNumber >= 0 Then 'We take negative to mean
            '  empty...

            Dim j As Integer
            For j = 0 To lastIndex
                Dim proteinNumber As Integer = mParsedProts2(j).hitNumber

                'Changed PM_CMD_NO_FIRST_PROTEIN 2006-11-22
                If Not firstIndexFound Then
                    If proteinNumber >= aStartProteinNumber Then
                        anOutStartDataIndex = j

                        'Changed PM_CMD_NO_FIRST_PROTEIN 2006-11-22
                        firstIndexFound = True
                    End If
                End If

                If proteinNumber <= anEndProteinNumber Then
                    anOutEndDataIndex = j
                Else
                    Exit For 'No need to continue
                End If
            Next j
        Else
            Dim peter3 As Integer = 3 'Empty! 
        End If
        anOutEmptyRange = Not firstIndexFound
    End Sub 'getDataIndicesFromProteinNumbers()


    'Changed PM_REFACTOR 2006-11-28
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function defaultSaveName() _
      As String

        'Changed PM_DEFAULT_SAVENAME 2004-10-27
        Dim quantModeStr As String = _
          quantApplication.quantModeString( _
            mOptions.quantModeCode, mApplication)

        'Changed PM_DANGEROUS 2006-11-15
        'Better now (?). Previously it could be a 
        'misleading suggested save file name if it was 
        'saved after some ***other*** Mascot result 
        'file/raw file was parsed...
        '
        'Dim MascotResultFileName As String = _
        '  mMascotResultParser.getMascotResultFileName()
        Dim MascotResultFileName As String = mWiffFile.MascotFilePath

        Dim defaultFileName As String = _
          Path.GetFileNameWithoutExtension(MascotResultFileName) & _
          ",QUANTMODE_" & quantModeStr

        Return defaultFileName
    End Function 'defaultSaveName()


    'Changed PM_REFACTOR 2006-11-28
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function dialogSave( _
      ByRef anOutFileName As String, _
      ByVal aProteins As Integer, _
      ByVal aIsAllProteins As Boolean, _
      ByVal aMBfileVersion As Integer) _
      As Boolean

        Dim toReturn As Boolean = False

        If mParsedProts2 Is Nothing Then
            MsgBox("No proteins to save")
        End If

        'Changed PM_SAVE_EXTENSION_BIX 2006-03-21
        'Changed PM_BINSAVE_FORMAT 2005-08-08
        'SaveFileDialog1.Filter = "Binary file (*.bi9)|*.bi9"
        '  bs7
        '  bs9: as from 2006-11-05
        '  mb1: as from 2006-11-13
        '  mb3: as from 2006-12-30
        '

        SaveFileDialog1.FileName = Me.defaultSaveName()

        'Changed PM_PROPER_MB3_SAVEDIALOG 2008-11-24
        ''Changed PM_REFACTOR 2008-11-12
        'Dim MBinfo As AppConstants.savedMBfilesInfoStruct = _
        '  AppConstants.currentConstantsForSavingMB()
        Dim MBinfo As AppConstants.savedMBfilesInfoStruct = _
          AppConstants.constantsForSavingMB(aMBfileVersion)

        'Dim dFilter As String = "Binary file (*.mb3)|*.mb3"
        Dim dFilter As String = MBinfo.fullDialogFilterSingular

        SaveFileDialog1.Filter = dFilter

        'Changed PM_MB3_EXTENSION 2007-07-09
        SaveFileDialog1.DefaultExt = "html" 'Note: only works if ValidateNames is True!!!!
        SaveFileDialog1.AddExtension = True


        '  E.g. "Saving 4 selected proteins."
        Dim titleSB As StringBuilder = New StringBuilder(40)
        titleSB.Append("Saving ")
        titleSB.Append(aProteins)
        If Not aIsAllProteins Then
            titleSB.Append(" selected")
        End If
        titleSB.Append(" proteins.")

        SaveFileDialog1.Title = titleSB.ToString()
        If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            anOutFileName = SaveFileDialog1.FileName
            toReturn = True
        End If

        Return toReturn
    End Function 'dialogSave()


    'Moved it down here...
    'Changed PM_REFACTOR 2006-11-28
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub saveAdoc( _
      ByRef anInDocToSave2 As MSQuantDocumentStructure, _
      ByRef anInBinFileName As String, _
      ByVal aProteins As Integer, _
      ByVal aSaveFileVersion As Integer)

        'aSaveFileVersion: e.g. 300 for MB3, 400 for MB4.

        'If first parameter is Object instead then this function could be 
        'a general wrapper, in a utility class - PILInputOutput?.

        mApplication.startStopWatch()

        Dim saveFile As FileStream = Nothing 'Keep compiler happy.

        Try
            'Changed PM_SAVE_RECALIBRATION 2005-01-27
            'Dim fileName As String = SaveFileDialog1.FileName
            'saveFile = File.OpenWrite(fileName)
            'BFormatter.Serialize(saveFile, mParsedProts)
            'saveFile.Close()
            '
            ''Changed PM_REFACTOR 2004-09-07
            'Dim fileName2 As String = fileName & ".bM2"
            'Dim saveFile2 As FileStream = File.OpenWrite(fileName2)
            'BFormatter.Serialize(saveFile2, mRawFiles)
            'saveFile2.Close()
            saveFile = File.OpenWrite(anInBinFileName)

            Dim BFormatter As New BinaryFormatter

            'Changed PM_MB4_VERSIONING 2008-11-12
            anInDocToSave2.fileVersion = aSaveFileVersion 'A way to transfer
            '  information to the GetObjectData() function. But is there a more
            '  direct way? Bypass Serialize() altogether?

            'try/catch???
            BFormatter.Serialize(saveFile, anInDocToSave2) 'Will 
            '  call GetObjectData() on object anInDocToSave.

            saveFile.Close()

            'BFormatter.Serialize(saveFile, mOptions)
            'BFormatter.Serialize(saveFile, mWiffFileStr)
            'BFormatter.Serialize(saveFile, mMascotWebOutputFileName)

        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)

            saveFile.Close()
            MsgBox("Could not save to file")
            PanelStatus.Text = "Could not save to file"
        End Try

        Dim memDiff_MB As Double
        Dim parseTimeSecs As Double = mApplication.stopStopWatch(memDiff_MB)

        Dim msgStr As String = _
          "Saved " & aProteins & " protein hits to file. Time: " & _
          parseTimeSecs.ToString("0.00") & " seconds."
        PanelStatus.Text = msgStr
    End Sub 'saveAdoc()


    'Changed PM_REFACTOR 2006-11-28
    '****************************************************************************
    '*    Is used when the application has been called                          *
    '*    with command line parameters (user dialog is avoided)...              *
    '*                                                                          *
    '*    But why this name???                                                  *
    '*                                                                          *
    '*                                                                          *
    '****************************************************************************
    Private Function defaultSaveFields2() _
      As MSQuantDocumentStructure

        'Changed PM_SAVE_RECALIBRATION 2005-01-27
        Dim docToSave As MSQuantDocumentStructure

        docToSave.experimentSettings2 = mExperimentSettings

        'Changed PM_SAVE_ALLRECALIB_MB4 2008-11-21
        docToSave.recalibrator = mRecalibrator

        docToSave.parsedProts3 = mParsedProts2
        docToSave.rawFiles2 = mRawFiles2

        'Only for MB3 format. Needed as we want to be able to 
        'save in the old format (unless we would get the 
        'constants on demand instead of storing them here).
        If True Then
            Dim tag As Integer = SDUPrecalibrator.ALL_TAGCODE
            Dim slope As Double
            Dim offset As Double
            mRecalibrator.getLinearCalibrationConstants(slope, offset, tag)
            docToSave.recalibSlope2 = slope
            docToSave.recalibOffset2 = offset
        End If

        'Changed PM_NOSELECTIO_NEEDED_FOR_OPENING_BIN 2006-11-15
        docToSave.mascotFileStr = mWiffFile.MascotFilePath
        docToSave.rawFileStr = mWiffFile.rawFilePath

        Return docToSave
    End Function 'defaultSaveFields2()


    'Changed PM_COMMANDLINE 2006-11-15
    '****************************************************************************
    '*    Saving directly to file, no user dialog. Is used when the             *
    '*    application has been called with command line parameters...           *
    '****************************************************************************
    Public Sub saveParseToBinFile( _
      ByRef anInBinFileName As String, _
      ByVal aSaveFileVersion As Integer)

        Dim docToSave As MSQuantDocumentStructure = Me.defaultSaveFields2()

        Me.saveAdoc( _
          docToSave, _
          anInBinFileName, _
          docToSave.parsedProts3.Count(), _
          aSaveFileVersion)
    End Sub 'saveParseToBinFile()


    'Changed PM_REFACTOR 2008-11-12
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub fullSave(ByVal aSaveFileVersion As Integer)

        Dim saveFileName As String = Nothing

        'All proteins!
        If Me.dialogSave( _
          saveFileName, mParsedProts2.Count(), True, aSaveFileVersion) Then

            Me.saveParseToBinFile( _
              saveFileName, aSaveFileVersion)
        End If
    End Sub 'fullSave()


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

        fullSave(AppConstants.CURRENT_SAVEDFILEVERSION)
    End Sub 'mnuSaveProteinHitsAs_Click()


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

        fullSave(AppConstants.SAVEDFILEVERSION_MB3)
    End Sub 'mnuSaveProteinsInMB3_Click()


    'Changed PM_SPLIT_AND_MERGE_PROTEINS 2006-11-28
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSaveSelectedProteinHits_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuSaveSelectedProteinHits.Click

        'Something with selection. Number of proteins, copy to new list, etc.

        Dim visualSelection4 As List(Of visibleIndexStruct) = _
          quantApplication.copySelectedIndices3(lstProtHits)

        If visualSelection4.Count > 0 Then

            Dim saveFileName As String = Nothing
            If Me.dialogSave( _
              saveFileName, _
              visualSelection4.Count(), _
              False, _
              AppConstants.CURRENT_SAVEDFILEVERSION) Then

                Dim tempProtList As List(Of ProteinHitStructure) = _
                  New List(Of ProteinHitStructure) 'Derive from mParsedProts2.

                Dim docToSave As MSQuantDocumentStructure = _
                  Me.defaultSaveFields2()

                Dim lastVisualIndex3 As Integer = visualSelection4.Count - 1
                Dim i As Integer
                For i = 0 To lastVisualIndex3
                    Dim visualIndex3 As Integer = visualSelection4(i).visualIdx2
                    Dim dataStructureIndex3 As Integer = _
                      Me.getProteinIndexFromVisualIndex(visualIndex3)
                    tempProtList.Add(mParsedProts2(dataStructureIndex3))
                Next

                docToSave.parsedProts3 = tempProtList

                'Now it is OK to use count:
                Me.saveAdoc( _
                  docToSave, saveFileName, docToSave.parsedProts3.Count(), _
                  AppConstants.CURRENT_SAVEDFILEVERSION)
            End If 'User did not cancel save dialog.

            'Changed PM_DIMMED_EMPTYSELECTION_SAVESPECIAL 2008-01-22. Can
            'no longer happen...
            'Else
            '    MsgBox( _
            '      "Could not complete action. No protein or proteins is/are selected. Select one or more proteins first.")
        End If 'Non-empty protein selection.
    End Sub 'mnuSaveSelectedProteinHits_Click()


    'Changed PM_REFACTOR 2006-11-28
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Shared Function dialogLoad( _
      ByRef anInOpenFileDialog As System.Windows.Forms.OpenFileDialog, _
      ByRef anOutLoadFileName As String, _
      ByVal aMBfileVersion As Integer) _
      As Boolean

        Dim toReturn As Boolean = False

        'Changed PM_REFACTOR 2006-11-15. Now ask the user for the bin file as 
        'the first thing.

        'Changed PM_REFACTOR 2008-11-12
        Dim MBinfo As AppConstants.savedMBfilesInfoStruct = _
          AppConstants.constantsForSavingMB(aMBfileVersion)
        'Dim dFilter As String = "Binary files (*.mb3)|*.mb3"
        Dim dFilter As String = MBinfo.fullDialogFilterPlural

        anInOpenFileDialog.Filter = dFilter

        anInOpenFileDialog.Title = "Open protein hit data"
        If anInOpenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then

            anOutLoadFileName = anInOpenFileDialog.FileName
            toReturn = True
        Else
            Dim peter2 As Integer = 2 'User cancelled.
        End If

        Return toReturn
    End Function 'dialogLoad()


    'Changed PM_SPLIT_AND_MERGE_PROTEINS 2006-11-28
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuInsertProteins_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuInsertProteins.Click

        Dim savedFileVersion As Integer = AppConstants.CURRENT_SAVEDFILEVERSION

        Dim loadFileName As String = Nothing
        If frmProteinList.dialogLoad( _
             OpenFileDialog1, loadFileName, savedFileVersion) Then

            Dim someMascotResultForm As frmProteinList = Nothing

            Dim msg As String = Nothing
            Dim loadedDoc2 As MSQuantDocumentStructure
            loadedDoc2.parsedProts3 = Nothing 'Keep compiler happy.
            loadedDoc2.rawFiles2 = Nothing 'Keep compiler happy.
            loadedDoc2.mascotFileStr = Nothing 'Keep compiler happy.
            loadedDoc2.rawFileStr = Nothing 'Keep compiler happy.

            loadedDoc2.experimentSettings2 = Nothing 'Keep compiler happy.

            Dim loadInfoStr As String = Nothing
            Dim succeeded2 As Boolean = _
              quantApplication.deserialiseDocumentDataStructures4( _
                loadFileName, msg, loadedDoc2, _
                mApplication, loadInfoStr, _
                savedFileVersion)
            'Later: use loadInfoStr.

            If succeeded2 Then
                Dim listToAdd As List(Of ProteinHitStructure) = _
                  loadedDoc2.parsedProts3

                'Assume it is ordered by protein hit number
                Dim oldListLastIndex As Integer = mParsedProts2.Count() - 1
                Dim newHitNumberBase As Integer = _
                  mParsedProts2(oldListLastIndex).hitNumber + 1

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

                    Dim proteinToAdd As ProteinHitStructure = listToAdd(j)
                    Dim newHitNumber As Integer = newHitNumberBase + j
                    proteinToAdd.hitNumber = newHitNumber

                    mParsedProts2.Add(proteinToAdd)
                Next j

                'Note: the peptide filter does not matter as it is not
                '      used when the third parameter is False.
                Dim dummyPeptideFilter As peptideFilterStructure = _
                  peptideFilterStructure.noPepFilter()

                Me.setParsedProteinList( _
                  mParsedProts2, _
                  False, _
                  dummyPeptideFilter, _
                  mRawFiles2)
            End If
        End If
    End Sub 'mnuInsertProteins_Click


    'Changed PM_AUTODOCUMENTATION 2007-04-17
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuReport_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuReport.Click

        Dim doIt As Boolean = True

        Dim selectedProteinsCount As Integer = _
          lstProtHits.SelectedIndices.Count()
        If selectedProteinsCount = 0 Then
            doIt = False
        End If

        Dim someFolder As String = Nothing
        If doIt Then
            quantApplication.userSelectFolder( _
              "Select folder for report files for " & _
              selectedProteinsCount & " selected proteins.", _
              someFolder)
            If someFolder = Nothing Then
                doIt = False 'User cancelled
            End If
        End If

        If doIt Then
            Dim tickCount1 As Integer = Environment.TickCount
            Dim baseFileNumber As Integer = tickCount1
            Dim fileNumber As Integer = baseFileNumber

            Dim baseDir As String = someFolder
            Me.initReport(baseDir)

            Dim firstTime As Boolean = True
            Dim visualSelection4 As List(Of visibleIndexStruct) = _
              quantApplication.copySelectedIndices3(lstProtHits)

            Dim lastVisualIndex3 As Integer = visualSelection4.Count - 1
            Dim i As Integer
            For i = 0 To lastVisualIndex3
                Dim lastProtein As Boolean = i = lastVisualIndex3

                Dim visualIndex3 As Integer = visualSelection4(i).visualIdx2

                Dim dataStructureIndex As Integer = _
                  Me.getProteinIndexFromVisualIndex(visualIndex3)

                Dim OKtoUse As Boolean = _
                  Me.auto_openPrValFrm2( _
                    dataStructureIndex, firstTime, 0)

                'We don't expect empty protein (no peptides) when it is
                'from the visual protein list.
                Trace.Assert(OKtoUse = True, "PIL ASSERT. Empty protein!")

                Dim toStop As Boolean = _
                  mCurrentFrmProtValidation.doDumpPeptideInfoAsGraphics( _
                    baseDir, fileNumber, lastProtein, mReportInfo)
            Next

            '*.PNG files created, one for each 
            'Post process:
            '  create DocBook XML file, 

            Me.endReport()
        End If 'Any protein selected.
    End Sub 'mnuReport_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub initReport(ByRef baseDir As String)

        Dim hms As String = PILInputOutput.timeAsHMS()
        Dim docBookMainFile As String = _
          baseDir & Path.DirectorySeparatorChar & _
          AppConstants.LONG_APP & "Report," & hms & ".xml"

        Dim AppFolderPath As String = appPath()

        Dim AppFolderPathAsURL As String = AppFolderPath.Replace("\", "/")
        AppFolderPathAsURL = AppFolderPathAsURL.Replace(" ", "%20")

        'Dim DTDpath As String = _
        '  "file:///Z:/zNEW/TRANSPORT/ToTARU/2005-08-10/to%20burn,2004-08-15,DocBook/Installing%20and%20using/Windows/DTDs/docbook-xml-4.2/docbookx.dtd"
        Dim DTDpath As String = _
          "file:///" & AppFolderPathAsURL & "/" & _
          "docBook" & "/" & "docbookx.dtd"
        Dim someXMLwriter As XmlTextWriter = _
          newStandardXMLout( _
            docBookMainFile, _
            "book", _
            DTDpath, _
            quantApplication.versionString_withDate())

        Dim currentISOdate As String = iso8601FullTime()

        If True Then 'Start of DocBook XML document.
            'Changed PM_XMLCOMMENTS_LINEBREAK 2008-02-08
            Dim ssb As StringBuilder = New StringBuilder(100)

            SDUP_emptyCommentLine(someXMLwriter)

            SDUPcomment(someXMLwriter, _
              "Changed: 2007-04-18 PM  Generation of this file, first version.", _
              ssb)
            SDUPcomment(someXMLwriter, _
              "Changed: 2007-05-03 PM  New standard comment header.", ssb)
            SDUPcomment(someXMLwriter, _
              "Changed: 2007-xx-xx PM", ssb)
            SDUP_emptyCommentLine(someXMLwriter)
            SDUP_emptyCommentLine(someXMLwriter)

            'Later:
            '  Installation of DocBook on Windows
            '  according to
            '   <http://supportweb.cs.bham.ac.uk/documentation/tutorials/docsystem/build/tutorials/docbooksys/docbooksys.pdf>.
            '  
            '  Orig DOCTYPE/SYSTEM ID: "-//OASIS//DTD DocBook V4.2//EN",
            '  changed to use the same as file 'catalog',
            '    "-//OASIS//DTD DocBook XML V4.2//EN"
            '  
            '  Version 1:
            '  
            '    <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
            '      "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
            '  
            '  Note: direct reference works, but how do we get the
            '        catalog method to work?
            '  
            '  DocBook quick reference:
            '    lists, <itemizedlist>/<listitem>/<para>, <orderedlist>/<listitem>/<para>.
            '    HTML link, <ulink url="http://xyz">abc</ulink>
            '    figure, <figure>
            '              <title>
            '              <mediaobject>
            '                <imageobject>
            '                  <imagedata>
            '                <textobject>
            '                <caption>
            '                  <para>
            '    Literals:
            '     < : <
            '     > : >
            '     & : &

            'What about this? Needed?
            '    <!DOCTYPE book SYSTEM
            '      "file:///C:/DocBook/Installing%20and%20using/Windows/DTDs/docbook-xml-4.2/docbookx.dtd">

            someXMLwriter.WriteStartElement("book")

            someXMLwriter.WriteStartElement("bookinfo")

            someXMLwriter.WriteElementString( _
              "title", Nothing, _
              AppConstants.LONG_APP & _
              " report for XYZ proteins and XYZ peptides.")

            someXMLwriter.WriteStartElement("author")

            someXMLwriter.WriteElementString( _
              "firstname", Nothing, _
              "")

            someXMLwriter.WriteElementString( _
              "surname", Nothing, _
              AppConstants.LONG_APP & ", vx.x.x, 2007-xx-xx")

            someXMLwriter.WriteStartElement("affiliation")

            someXMLwriter.WriteStartElement("address")

            someXMLwriter.WriteElementString( _
              "email", Nothing, _
              AppConstants.LONG_APP & "@xyz")
            someXMLwriter.WriteEndElement() 'For address.

            someXMLwriter.WriteEndElement() 'For affiliation.

            someXMLwriter.WriteEndElement() 'For author.

            someXMLwriter.WriteStartElement("copyright")

            someXMLwriter.WriteElementString( _
              "year", Nothing, _
              "2007")

            'How is attribute specified???:
            '  <holder role="mailto:pmortensen@bmb.sdu.dk">Peter Mortensen</holder>
            someXMLwriter.WriteElementString( _
              "holder", Nothing, _
              AppConstants.LONG_APP & "/ Peter Mortensen")

            someXMLwriter.WriteEndElement() 'For copyright.

            someXMLwriter.WriteElementString( _
              "pubdate", Nothing, _
              currentISOdate)

            someXMLwriter.WriteElementString( _
              "releaseinfo", Nothing, _
              "$Id: " & AppConstants.LONG_APP & " report, v 1.0 " & _
              currentISOdate & AppConstants.LONG_APP & " Exp $")

            someXMLwriter.WriteStartElement("abstract")

            someXMLwriter.WriteElementString( _
              "para", Nothing, _
              "xyz")

            someXMLwriter.WriteElementString( _
              "para", Nothing, _
              "abc")

            someXMLwriter.WriteEndElement() 'For abstract.

            someXMLwriter.WriteEndElement() 'For bookinfo.
        End If

        'Later:
        If True Then 'Information about the sample, e.g 
            '  Mascot result file path, etc.
        End If

        'For now: only one part - fragment spectra. There could be
        'others, e.g. detailed quantitation results.
        someXMLwriter.WriteStartElement("part")

        someXMLwriter.WriteElementString( _
          "title", Nothing, _
          "Part: MS2 spectra dump")

        mReportInfo.XMLwriter = someXMLwriter
        mReportInfo.XMLfileName = docBookMainFile
        mReportInfo.massFormatStr = "0.00000"
    End Sub 'initReport


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

        'For shorter notation.
        Dim writer As System.Xml.XmlTextWriter = mReportInfo.XMLwriter

        writer.WriteEndElement() 'For part.
        writer.WriteEndElement() 'For "book".

        writer.Flush()
        writer.Close()

        'Later: generate and execute BAT file that
        '       runs DocBook and postprocess to PDF.
    End Sub 'initReport


    'Changed PM_RECALIB_VISUAL 2007-09-02
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuRecalibVisual_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuRecalibVisual.Click

        'For now we just refuse if there is no selection, but the real solution 
        'should be to disable menu item when there is no selection.

        Dim protein_visualIndices3 As List(Of visibleIndexStruct) = _
          quantApplication.copySelectedIndices3(lstProtHits)

        Dim protein_datastructureIndices As List(Of Integer) = _
          Me.selectedIndices2DatastructureIndices2(protein_visualIndices3)

        'Why not test protein_visualIndices2 instead????

        If protein_datastructureIndices.Count > 0 Then
            Dim someFilter As peptideFilterStructure = _
              peptideFilterStructure.noPepFilter()

            'Changed PM_SILAC_AWARE_PEPTIDEFILTERDIALOG 2008-10-05
            Dim SILACmods As Dictionary(Of Integer, Integer) = _
              Me.constructSILACmods()

            'Note: if one is already open then we lose connection to
            '      it. But that is OK (?) - what about the call-back
            '      events.
            mCalibVisualForm = _
              New frmRecalibrationVisualisation( _
                Me, _
                protein_datastructureIndices, mParsedProts2, someFilter, _
                mApplication, _
                mWiffFile.MascotFilePath, _
                mRawFiles2, _
                mRecalibrator, _
                SILACmods, _
                mParseIDnumber)

            mCalibVisualForm.Show()
        End If
    End Sub 'mnuRecalibVisual_Click


    'Changed PM_RECALIB_VISUAL_SAVE 2007-09-04
    '****************************************************************************
    '*    Purpose: record new peptide filter for recalibration.                 *
    '****************************************************************************
    Private Sub mCalibVisualForm_calibVisualDismissed( _
      ByVal aSender As Object, ByVal anEvent As pepFilterEventArgs) _
      Handles mCalibVisualForm.calibVisualDismissed

        'Is this function really needed. Is it called immediately
        'when the peptide filter dialog (inside the recalib
        'visual dialog) is dismissed?
        Dim filter As peptideFilterStructure = anEvent.getFilter()

        mParentForm.setApeptideFilter( _
          filter, peptideFilterEnum.enumRecalibVisual)
    End Sub 'mCalibVisualForm_calibVisualDismissed


    'Changed PM_RECALIB_AFTERPARSE 2007-11-06
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuRecalibration_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuRecalibration.Click

        If lstProtHits.SelectedIndices.Count > 0 Then
            Dim visualSelection4 As List(Of visibleIndexStruct) = _
              quantApplication.copySelectedIndices3(lstProtHits)

            Dim selected As Integer = visualSelection4.Count()
            Dim msg As String = _
              "Recalibration will be done using the filter from " & _
              "the Options dialog and be based on " & _
              selected & " selected proteins."
            MsgBox(msg)

            Dim recalibPeptideFilter As peptideFilterStructure = _
              mOptions.peptideFilters(peptideFilterEnum.enumRecalibParse)

            'Changed PM_WRONG_PROTEINS 2008-09-25
            Dim datastructureIndices As List(Of Integer) = _
              Me.selectedIndices2DatastructureIndices2(visualSelection4)

            'Changed PM_WRONG_PROTEINS 2008-09-25. First parameter
            '  was visualSelection4!
            Me.recalibrateAndAdjustMassesAndValidation2( _
              datastructureIndices, _
              mParsedProts2, _
              recalibPeptideFilter, _
              False)

            Me.visualiseRecalibration(mRawFiles2)
        End If 'Not empty selection.
    End Sub 'mnuRecalibration_Click


    'Changed PM_EXPORT_RAWFILEID 2007-11-19
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function generateRawFilesReport( _
      ByRef anInCalibration As SDUPrecalibrator) _
      As String

        Dim resSB As StringBuilder = New StringBuilder(300)

        Dim uncalib_lowMCR As Double = 400.0 'For now: fixed, not true
        '  value for the data set.

        Dim uncalib_highMCR As Double = 1300.0 'For now: fixed, not
        '  true value for the data set.

        If True Then 'Header
            resSB.Append("Raw files report.")
            resSB.Append(ControlChars.NewLine)
            resSB.Append(ControlChars.NewLine)

            quantApplication.addCalibrationInformationForAll( _
              anInCalibration, resSB)

            resSB.Append("Lowest MCR for all [Th] (not true value):")
            resSB.Append(vbTab)
            resSB.Append(uncalib_lowMCR)
            resSB.Append(ControlChars.NewLine)

            resSB.Append("Highest MCR for all [Th] (not true value):")
            resSB.Append(vbTab)
            resSB.Append(uncalib_highMCR)
            resSB.Append(ControlChars.NewLine)

            resSB.Append(ControlChars.NewLine)
        End If

        If True Then 'Header line
            resSB.Append("Raw file")
            resSB.Append(vbTab)

            resSB.Append("ID")
            resSB.Append(vbTab)

            resSB.Append("Recalib, slope")
            resSB.Append(vbTab)

            resSB.Append("Recalib, offset")
            resSB.Append(vbTab)

            resSB.Append("Considered for recalib")
            resSB.Append(vbTab)

            resSB.Append("Used for recalib")
            resSB.Append(vbTab)

            'Changed PM_PSP_S 2008-05-07
            'resSB.Append("Preselected peptides")
            resSB.Append("Preselected peptides (PSPs)")
            resSB.Append(vbTab)

            resSB.Append("Low after recalib [Th]")
            resSB.Append(vbTab)

            resSB.Append("Low diff after recalib [Th]")
            resSB.Append(vbTab)

            resSB.Append("Low diff after recalib [ppm]")
            resSB.Append(vbTab)

            resSB.Append("High after recalib [Th]")
            resSB.Append(vbTab)

            resSB.Append("High diff after recalib [Th]")
            resSB.Append(vbTab)

            resSB.Append("High diff after recalib [ppm]")
            resSB.Append(vbTab)

            resSB.Append("Full path")
            resSB.Append(vbTab)

            resSB.Append(ControlChars.NewLine)
        End If

        Dim slope As Double
        Dim offset As Double

        Dim lastIndex As Integer = mRawFiles2.Length() - 1
        Dim j As Integer
        For j = 0 To lastIndex
            Dim someRawFile As fileSpecStructure = mRawFiles2(j)

            Dim fname As String = someRawFile.path

            Dim fnameNoPath As String = Path.GetFileName(fname)
            Dim ID As Integer = someRawFile.tag2

            anInCalibration.getLinearCalibrationConstants( _
              slope, offset, ID)

            'Refactor these two blocks?:

            Dim charge1 As Integer = 1 'Arbitrary. We will only use MCR values.
            Dim calibMCR1b As Double = _
              anInCalibration.uncalib2calib(uncalib_lowMCR, ID)

            'Changed PM_REFACTOR 2008-05-20
            'Dim theoMass1 As Double = _
            '  (uncalib_lowMCR - MSconstants.PROTON_MASS) * charge1   'Adaption.
            Dim theoMass1 As Double = _
              PILmassCalc.chargeTransform(uncalib_lowMCR, charge1, 0)

            Dim valLow As massSpectrometryBase.massErrorStructure = _
              PILmassCalc.massErrors(theoMass1, uncalib_lowMCR, calibMCR1b, charge1)

            Dim charge2 As Integer = 1 'Arbitrary. We will only use MCR values.
            Dim calibMCR2b As Double = anInCalibration.uncalib2calib(uncalib_highMCR, ID)

            'Changed PM_REFACTOR 2008-05-20
            'Dim theoMass2 As Double = _
            '  (uncalib_highMCR - MSconstants.PROTON_MASS) * charge2  'Adaption.
            Dim theoMass2 As Double = _
              PILmassCalc.chargeTransform(uncalib_highMCR, charge2, 0)

            Dim valHigh As massErrorStructure = _
              PILmassCalc.massErrors(theoMass2, uncalib_highMCR, calibMCR2b, charge2)

            resSB.Append(fnameNoPath)
            resSB.Append(vbTab)

            resSB.Append(ID)
            resSB.Append(vbTab)

            resSB.Append(slope.ToString("0.000000000"))
            resSB.Append(vbTab)

            resSB.Append(offset.ToString("0.000000000"))
            resSB.Append(vbTab)

            'Peptide counts.
            resSB.Append("LATER")
            resSB.Append(vbTab)
            resSB.Append("LATER")
            resSB.Append(vbTab)
            resSB.Append("LATER")
            resSB.Append(vbTab)

            resSB.Append(calibMCR1b.ToString("0.000000000"))
            resSB.Append(vbTab)
            resSB.Append(valLow.calibMCRError.ToString("0.000000000"))
            resSB.Append(vbTab)
            resSB.Append(valLow.calibMCRRelativeError.ToString("0.000000000"))
            resSB.Append(vbTab)

            resSB.Append(calibMCR2b.ToString("0.000000000"))
            resSB.Append(vbTab)
            resSB.Append(valHigh.calibMCRError.ToString("0.000000000"))
            resSB.Append(vbTab)
            resSB.Append(valHigh.calibMCRRelativeError.ToString("0.000000000"))
            resSB.Append(vbTab)

            resSB.Append(fname)
            resSB.Append(vbTab)

            resSB.Append(ControlChars.NewLine)
        Next j

        Dim toReturn As String = resSB.ToString()
        Return toReturn
    End Function 'generateRawFilesReport


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

        Dim reportStr As String = Me.generateRawFilesReport(mRecalibrator)

        'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
        Dim exportTargetSettings As exportTargetSettingsStruct = _
          Me.getGlobalTargetSettings()

        'Changed PM_AVOID_EXCEL 2008-08-21. Use last setting from the export proteins and peptides...
        ''Changed PM_BROKENEXPORT 2008-05-28
        ''Excel for now.
        'Dim ex As exportTargetSettingsStruct = _
        '  exportTargetSettingsStruct.defaultExportTargetSettings()
        'ex.target = targetEnum.enumExportToExcel
        'PILInputOutput.pushToTarget(reportStr, ex)
        PILInputOutput.pushToTarget( _
          reportStr, _
          exportTargetSettings, _
          appPath())
    End Sub 'mnuExportRawFilesReport_Click


    'Changed PM_RECALIB_VISUAL_CLICK_TO_PEPTIDEINFO 2008-03-12
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub openParticularPeptide( _
      ByVal aProteinHitNumber As Integer, _
      ByVal aQueryNumber As Integer)

        Dim datastructureIndex As Integer = _
          Me.proteinIndexFromHitNumber(aProteinHitNumber)
        Dim toReturn As Boolean = _
          openProtValForm3(True, datastructureIndex, aQueryNumber)
    End Sub 'openParticularPeptide


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function extractNextCSVstringField( _
      ByRef anInSomeLine As String, ByVal aStartIndex As Integer, _
      ByRef anOutIndex As Integer, ByRef anOutQuotedField As Boolean) _
      As Boolean
        'anOutIndex will point after the content. Either on a "," or one
        'past the last character.
        '
        'anOutQuotedField is intended for client side checking...

        'Note: there is no return string as we want to limit the number 
        '      of temporary strings. The client may only want to extract
        '      a single string.

        Dim toReturn As Boolean = True
        anOutQuotedField = False

        Dim lineLen As Integer = anInSomeLine.Length()
        Dim firstCh As String = anInSomeLine.Substring(aStartIndex, 1)
        If firstCh = "," Then

            'Empty field. We can compute next index without string search.
            anOutIndex = aStartIndex + 1 'Point to beginning of new field.
        Else
            Dim endIndex As Integer = -1
            If firstCh = """" Then
                anOutQuotedField = True

                'Quoted field. Note: we will ignore any "," until the
                'ending quote.

                Dim lastIndex As Integer = -1

                Dim startExtractIndex As Integer = aStartIndex + 1

                'Look for next quote.
                Dim lastField As Boolean = False
                Dim qIdx As Integer = _
                  anInSomeLine.IndexOf("""", startExtractIndex)

                If qIdx >= 0 Then
                    endIndex = qIdx + 1 'Point to "," or past end of line.

                    'Perhaps later: additional check for quoted quote - embedded 
                    'quotes  are represented a double quote with string
                    'fields in CSV files. With the current implementation
                    'we will fail miserably.
                Else
                    Trace.Assert(False, _
                      "PIL ASSERT. This should never happen..  For line: " & _
                      anInSomeLine & ".")
                End If
            Else
                'Non-quoted field (e.g. numeric). We do not parse such fields.

                'Look-ahead for ",".
                endIndex = _
                  anInSomeLine.IndexOf(",", aStartIndex)
                If endIndex < 0 Then
                    endIndex = lineLen
                End If
            End If

            Trace.Assert(endIndex >= 0, "PIL ASSERT. <message>.")
            anOutIndex = endIndex + 1 'Point to beginning of new field
        End If

        If anOutIndex = lineLen Then
            toReturn = False
        End If
    End Function 'extractNextCSVfield


    'Changed PM_RETRIEVE_PROTEIN_SEQUENCES 2008-04-07
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function extractCSVstringField( _
      ByRef anInSomeLine As String, _
      ByVal aField_base1 As Integer, _
      ByVal aMustBeQuoted As Boolean, _
      ByRef anOutFieldContent As String) _
      As Boolean

        'aMustBeQuoted: for error detection only.

        'Notes:
        '  1. CSV format <http://edoceo.com/utilitas/csv-file-format>,
        '     "Embedded double-quotes - Embedded double-quote characters
        '     must be doubled, and the field must be delimited with
        '     double-quotes."
        '
        '  2. See also <http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm>.

        Dim toReturn As Boolean = False
        Dim done As Boolean = False
        anOutFieldContent = Nothing

        Dim inString As Boolean = False 'A parse state.

        ' 'To get started.
        ' If anInSomeLine.Length() > 0 Then
        '     Dim firstCh As String = anInSomeLine.Substring(0, 1)
        '     inString = firstCh = """"
        ' 
        '     If inString Then
        '         Dim peter2 As Integer = 2
        '     End If
        ' End If

        Dim newIdx As Integer
        Dim curIdx As Integer = 0
        Dim fieldNumber As Integer = 1
        While Not done

            Dim quotedField As Boolean
            Dim lastField As Boolean = _
              extractNextCSVstringField( _
                anInSomeLine, curIdx, newIdx, quotedField)

            If aField_base1 = fieldNumber Then

                Dim lenOffset As Integer = 0
                Dim indexOffset As Integer = 0
                If quotedField Then
                    lenOffset = 2
                    indexOffset = 1
                    'Note: -2 for the
                    '  enclosing quotes. -1 for the separator (",").
                Else
                    Dim peter2 As Integer = 2 'No quotes - e.g. protein sequence.
                End If

                Dim len As Integer = newIdx - curIdx - lenOffset - 1

                If len > 0 Then
                    Trace.Assert(Not aMustBeQuoted Or quotedField = True, _
                      "PIL ASSERT. Field number " & aField_base1 & _
                      " is not a string field as expected. Current line: " & _
                      Environment.NewLine & anInSomeLine)

                    '"+1" for the start quote.
                    anOutFieldContent = _
                      anInSomeLine.Substring(curIdx + indexOffset, len)

                    toReturn = True
                Else
                    Dim peter2 As Integer = 2 'Empty field, e.g. protein
                    '  accesion number for peptide lines.
                End If

                done = True
            End If

            curIdx = newIdx
            fieldNumber += 1

            If lastField Then
                done = True
            End If

            ' If inString Then
            '     Dim idx3 As Integer = anInSomeLine.IndexOf("""", curIdx)
            ' 
            '     If idx3 >= 0 Then
            ' 
            '     End If
            ' Else
            '     Dim idx1 As Integer = anInSomeLine.IndexOf(",", curIdx)
            ' 
            '     If idx1 >= 0 Then
            '         If aField_base1 = fieldNumber Then
            ' 
            '             Dim len As Integer = idx1 - curIdx - 2 '"-2" for the
            '             '  enclosing quotes.
            '             If len > 0 Then
            '                 '"+1" for the start quote.
            '                 anOutFieldContent = _
            '                   anInSomeLine.Substring(curIdx + 1, len)
            ' 
            '                 toReturn = True
            '             Else
            '                 Dim peter2 As Integer = 2 'Empty field, e.g. protein
            '                 '  accesion number for peptide lines.
            '             End If
            ' 
            '             done = True
            '         End If
            ' 
            '         fieldNumber += 1
            '         curIdx = idx1 + 1 'Jump over ",".
            '     Else
            '         done = True
            '     End If
            ' End If
        End While

        Return toReturn
    End Function 'extractCSVstringField()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub parseExport2file( _
      ByRef aSaveFileNameFullPath As String, _
      ByRef anInProteinLookupHash As Dictionary(Of String, Integer), _
      ByRef anInOutProteinList As List(Of ProteinHitStructure), _
      ByVal aPeptideFilter As peptideFilterStructure _
      )

        Dim fi As FileInfo = New FileInfo(aSaveFileNameFullPath)
        Dim inputFileLen As Long = fi.Length()

        Try
            Dim inputFileStream As FileStream = _
              New FileStream( _
                aSaveFileNameFullPath, FileMode.Open, FileAccess.Read)

            Dim inputStreamReader As StreamReader = _
              New StreamReader(inputFileStream, _
                System.Text.Encoding.ASCII)

            Dim proteinsInInput As Integer = 0

            Dim proteinsAssignedSequence As Integer = 0
            Dim emptySequences As Integer = 0

            Dim lineCounter As Integer = 0

            While Not inputStreamReader.EndOfStream

                Dim someLine As String = inputStreamReader.ReadLine()
                lineCounter += 1

                If someLine.Length > 0 Then 'Ignore empty lines

                    'Protein/peptide lines start with the protein
                    'hit number. Other lines, like table header, do not.
                    Dim firstCh As String = someLine.Substring(0, 1)
                    If firstCh >= "0" AndAlso firstCh <= "9" Then

                        'Second field is protein accession number for proteins
                        'and is empty for peptide lines.
                        Dim readProteinAcc As String = Nothing
                        If Me.extractCSVstringField( _
                                someLine, 2, True, readProteinAcc) Then

                            If anInProteinLookupHash.ContainsKey(readProteinAcc) Then
                                Dim proteinSequence As String = Nothing
                                If Me.extractCSVstringField( _
                                  someLine, 10, False, proteinSequence) Then

                                    'Crude test to see if we actually got
                                    'the protein sequence.

                                    Dim dataIndex As Integer = _
                                      anInProteinLookupHash(readProteinAcc)
                                    Dim someProtein As ProteinHitStructure = _
                                      anInOutProteinList(dataIndex)

                                    'Changed PM_RETRIEVE_PROTEIN_SEQUENCES_FASTER 2008-04-22
                                    Dim pepts As massSpectrometryBase.PILpeptides = _
                                      someProtein.peptides
                                    'We are not sure if we can set the filter and
                                    'then use the count function (without affecting
                                    'the normal base peptide filter).
                                    'Instead iterate through the peptides with the 
                                    'retrieve filter to find the count.
                                    Dim pepIter As peptideListIterator = _
                                      New peptideListIterator( _
                                        someProtein.peptides, aPeptideFilter)
                                    Dim pept As PeptideHitStructure = _
                                      PeptideHitStructure.blankPeptide() 'Keep compiler happy.
                                    Dim count As Integer = 0
                                    While Not pepIter.nextPeptide(pept)
                                        count += 1
                                    End While

                                    If count > 0 Then
                                        'Reality check on our hash...
                                        Dim parsedAcc As String = _
                                          someProtein.accNum
                                        Trace.Assert(readProteinAcc = parsedAcc, _
                                          "PIL ASSERT. Internal error. " & _
                                          "Parsed protein accession number, " & _
                                          parsedAcc & _
                                          ", is not the same as the one " & _
                                          "from the CSV file, " & _
                                          readProteinAcc & ".")

                                        Dim protMass As Double = _
                                          someProtein.monoIsotopicMass
                                        Dim minSequenceLen As Integer = _
                                          CInt(protMass / 204) 'Tryptophan

                                        Dim readSeqLen As Integer = _
                                          proteinSequence.Length()
                                        Trace.Assert(readSeqLen > minSequenceLen, _
                                          "PIL ASSERT. " & _
                                          "Bad protein sequence (protein length would be " & _
                                          minSequenceLen & " if all AAs were tryptophan) from CSV file """ & _
                                          aSaveFileNameFullPath & _
                                          """ , line " & lineCounter & _
                                          ". Accession number: " & readProteinAcc & _
                                          ". Protein mass (mono or average???) in " & _
                                          AppConstants.LONG_APP & ", " & _
                                          ". Protein sequence length: " & readSeqLen & _
                                          ". from Mascot result file: " & protMass.ToString("0.00000") & _
                                          ". Protein sequence from CSV file (within "">>><<<""): >>>" & _
                                          proteinSequence & "<<<.")

                                        'MsgBox( _
                                        '  "Found protein sequence for " & _
                                        '  readProteinAcc & ": " & Environment.NewLine & _
                                        '  proteinSequence)

                                        proteinsAssignedSequence += 1
                                        someProtein.sequence = proteinSequence

                                        'Write back
                                        anInOutProteinList(dataIndex) = someProtein
                                    Else
                                        'No peptide is within our protein sequence
                                        'retrieve filter: don't compute and set 
                                        'protein sequence coverage.
                                        Dim peter2 As Integer = 2
                                    End If
                                Else
                                    'MsgBox( _
                                    '  "Unexpected empty protein sequence field in file " & _
                                    '  aSaveFileNameFullPath)
                                    emptySequences += 1
                                End If
                            Else
                                Dim peter3 As Integer = 3  'Accession number not found.
                            End If
                        End If 'Protein line
                    End If 'Protein or peptide line.
                End If 'Not empty line.
            End While 'Through lines in the download CSV file with protein information.

            'Output some statistics.
            Dim totalProteins As Integer = anInOutProteinList.Count()
            Dim selectedProteins As Integer = anInProteinLookupHash.Count()
            Dim percentAssigned As Double = _
              (100.0 * proteinsAssignedSequence) / selectedProteins

            Dim msgStr As String = _
              "Out of " & selectedProteins & " selected proteins " & _
              proteinsAssignedSequence & _
              " got assigned a (non-empty) amino acid sequence (" & _
              percentAssigned.ToString("0.0") & _
              " %). " & emptySequences & _
              " of the protein sequences returned from the Mascot server were empty. " & _
              "The total number of proteins is " & totalProteins & "."
            MsgBox(msgStr)

        Catch exceptionObject As Exception
            displayStandardExceptionInfo( _
              exceptionObject, _
              "Could not open file " & aSaveFileNameFullPath)
            Exit Sub
        End Try
    End Sub 'parseExport2file


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function createLookupHashForProteinSubset( _
      ByRef aProteinsSubset_visualIndices3 As List(Of visibleIndexStruct), _
      ByRef anInParsedProts As List(Of ProteinHitStructure), _
      ByRef anOutMinimumMaxScore As Double _
      ) _
      As Dictionary(Of String, Integer)

        Dim proteinLookupHash As Dictionary(Of String, Integer) = _
          New Dictionary(Of String, Integer)

        Dim minimumMaxScore As Double = 1000000000000.0 'Of highest scoring peptide in
        '  the proteins: which one has the lowest score.

        Dim useAllProteins As Boolean = _
          aProteinsSubset_visualIndices3 Is Nothing
        Dim len As Integer
        If useAllProteins Then
            len = anInParsedProts.Count()
        Else
            len = aProteinsSubset_visualIndices3.Count()
        End If

        Dim visualIndex3 As Integer
        Dim proteinIndex2 As Integer

        Dim lastIndex As Integer = len - 1
        Dim i As Integer
        For i = 0 To lastIndex
            If useAllProteins Then
                proteinIndex2 = i
            Else
                'Changed PM_REFACTOR 2008-09-25. Now in a struct...
                visualIndex3 = aProteinsSubset_visualIndices3(i).visualIdx2

                proteinIndex2 = _
                  Me.getProteinIndexFromVisualIndex(visualIndex3)
            End If

            Dim prot2 As ProteinHitStructure = anInParsedProts(proteinIndex2)


            'Find highest scoring peptide for this protein, using base view.
            If True Then
                Dim maxPepScore As Double = -10.0
                Dim pepIter As peptideListIterator = _
                  New peptideListIterator( _
                    prot2.peptides)
                Dim pept As PeptideHitStructure = _
                  PeptideHitStructure.blankPeptide() 'Keep compiler happy.
                While Not pepIter.nextPeptide(pept)

                    'Changed PM_MASCOTSCORE_ASDOUBLE 2008-11-25. No
                    'longer implicit conversion from integer to
                    'double...
                    Dim score As Double = pept.MascotScore2

                    If score > maxPepScore Then
                        maxPepScore = score
                    End If
                End While

                If maxPepScore > 0.0 Then 'Check, just in case.
                    If maxPepScore < minimumMaxScore Then
                        minimumMaxScore = maxPepScore
                    End If
                Else
                    'No peptides. This should never happen...
                    Trace.Assert(False, _
                      "PIL ASSERT. No peptides for protein " & prot2.accNum & _
                      ". This should never happen!!!")
                End If
            End If

            proteinLookupHash.Add(prot2.accNum, proteinIndex2)
        Next 'Through proteins (user selected or all).

        'Changed PM_RETRIEVE_PROTEIN_SEQUENCES_FASTER 2008-04-22
        'Side output
        anOutMinimumMaxScore = minimumMaxScore

        Return proteinLookupHash
    End Function 'createLookupHashForProteinSubset()


    'Changed PM_RETRIEVE_PROTEIN_SEQUENCES 2008-04-07
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuRetrieveProteinSequences_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuRetrieveProteinSequences.Click

        If lstProtHits.SelectedIndices.Count > 0 Then

            'Dim search As String = "20070716%2FF037366.dat"

            Dim searcLogURL As String = _
              "http://mascot4.bmb.sdu.dk/mascot/cgi/master_results.pl?file=../data/20070716/F037366.dat"

            Dim params As retrieveProteinStructure
            params.searchLogURL = searcLogURL

            'Changed PM_RETRIEVE_PROTEIN_SEQUENCES_FASTER 2008-04-22
            Dim retrievePeptideFilter As peptideFilterStructure = _
              mOptions.peptideFilters( _
                peptideFilterEnum.enumRetrieveProteinSequences)
            params.peptideFilter2 = retrievePeptideFilter

            'Changed PM_SILAC_AWARE_PEPTIDEFILTERDIALOG 2008-10-05
            Dim SILACmods As Dictionary(Of Integer, Integer) = _
              Me.constructSILACmods()

            mRetrieveProteinsParametersForm = _
              New frmRetrieveProteinsParameters( _
                params, mApplication, mRawFiles2, _
                SILACmods)
            mRetrieveProteinsParametersForm.Show()
        End If 'Not empty selection.
    End Sub 'mnuRetrieveProteinSequences_Click()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '*    Call-back from dialog.                                                *
    '****************************************************************************
    Private Sub mRetrieveProteinsParametersForm_pepFilterDismissed( _
      ByVal aSender As Object, _
      ByVal anEvent As proteinParametersEventArgs) _
      Handles mRetrieveProteinsParametersForm.proteinParametersDialogDismissed

        Dim params As retrieveProteinStructure = anEvent.getParams()
        Dim searchLogURL As String = params.searchLogURL
        'Sample:
        '  http://mascot4.bmb.sdu.dk/mascot/cgi/master_results.pl?file=../data/20070716/F037366.dat
        Dim peptideFilter As peptideFilterStructure = params.peptideFilter2
        Dim key As peptideFilterEnum = _
          peptideFilterEnum.enumRetrieveProteinSequences

        'Persist new peptide filter settings.
        If True Then 'Saving copies here.
            'Perhaps later: remember the URL for protein retrieval,
            '               field searchLogURL. 
            '  mOptions.xyz = searchLogURL

            mOptions.peptideFilters(key) = peptideFilter
            mParentForm.setApeptideFilter(peptideFilter, key)
        End If 'Persisting peptide filter.


        Dim search2 As String = "<none>"

        'Dim sURL2 As String = "http://mascot4.bmb.sdu.dk"
        Dim sURL2 As String = "<no server>"

        'Dim cgiPrefix As String = "/mascot/cgi/"
        Dim cgiPrefix As String = "<no cgi prefix>"

        If True Then 'Extract server and Perl prefix
            Dim idx3 As Integer = searchLogURL.IndexOf("//", 0)

            Dim idx4 As Integer = searchLogURL.IndexOf("/", idx3 + 2)
            Dim len2 As Integer = idx4 - 0

            sURL2 = searchLogURL.Substring(0, len2)

            'idx4 now points at "/". This is what we need.
            Dim idx5 As Integer = searchLogURL.IndexOf("?", idx4)

            'No backwards string search??
            Dim idx6 As Integer = idx5
            Dim end2 As Boolean = False
            While searchLogURL.Substring(idx6, 1) <> "/"
                idx6 -= 1
            End While

            Dim len3 As Integer = idx6 - idx4 + 1 '1 to include the trailing "/".
            cgiPrefix = searchLogURL.Substring(idx4, len3)
        End If

        If True Then 'Extract date/dat file ID
            Dim idx1 As Integer = searchLogURL.IndexOf("file=../data/")
            If idx1 < 0 Then
                MsgBox( _
                  "Search log URL does not appear to have the right form. URL: " & _
                  searchLogURL)
            Else
                idx1 += 13 'Jump over search string...
                Dim idx2 As Integer = searchLogURL.IndexOf(".dat", idx1)
                idx2 += 4 'Jump over ".dat"...

                Dim len As Integer = idx2 - idx1
                Dim dateAndDatfile As String = searchLogURL.Substring(idx1, len)

                search2 = dateAndDatfile.Replace("/", "%2F")
            End If
        End If

        Dim visualSelection4 As List(Of visibleIndexStruct) = _
          quantApplication.copySelectedIndices3(lstProtHits)

        'First we create a hash of references to the user selected
        'proteins. Then we ***only*** need to store the things from
        'the retrieved proteins that we need.
        Dim minimumMaxScore As Double
        Dim proteinLookupHash As Dictionary(Of String, Integer) = _
          Me.createLookupHashForProteinSubset( _
            visualSelection4, mParsedProts2, minimumMaxScore)

        'Get protein sequences. Note that by using export_dat_2.pl we
        'get all the sequences in one call/HTTP transfer.
        If True Then
            ''Dim search As String = "20080403%2FF049002.dat"
            'Dim search As String = "20070716%2FF037366.dat"

            Dim exportPartialURL As String = cgiPrefix & "export_dat_2.pl?"

            'Changed PM_RETRIEVE_PROTEIN_SEQUENCES_FASTER 2008-04-22
            'Use peptide threshold value from a peptide filter, near "_ignoreionsscorebelow="
            '  Are fractional Mascot score OK?
            'Dim minPeptideScore As Double = 10.0

            Dim margin As Double = 0.5 'We are not sure whether the threshold
            '  is inclusive or not...
            Dim minPeptideScore As Double = minimumMaxScore - margin 'This 
            '  can very much speed-up retrieving the protein information
            '  from the Mascot server as there will be much fewer proteins
            '  to retrieve.
            '
            '  Value is minimum score such that all proteins in the selection
            '  have at least one peptide with this score or higher.

            'User can raise it even higher (this will then exclude some proteins
            'from getting a sequence).
            If peptideFilter.scoreMin > minPeptideScore Then
                minPeptideScore = peptideFilter.scoreMin
            End If

            Dim otherParams As String = _
              "&do_export=1&prot_hit_num=1&prot_acc=1&pep_query=1" & _
              "&pep_rank=1&pep_isbold=1&pep_exp_mz=1&" & _
              "_showallfromerrortolerant=0&_onlyerrortolerant=0" & _
              "&_noerrortolerant=0&_show_decoy_report=0" & _
              "&export_format=CSV&_sigthreshold=0.05" & _
              "&REPORT=9999&_server_mudpit_switch=0.000000001" & _
              "&_ignoreionsscorebelow=" & minPeptideScore.ToString("0.00") & _
              "&_showsubsets=0" & _
              "&protein_master=1&prot_score=1&prot_desc=1" & _
              "&prot_mass=1&prot_matches=1&prot_cover=1" & _
              "&prot_len=1&prot_pi=1&prot_seq=1" & _
              "&peptide_master=1&pep_exp_mr=1&pep_score=1"

            Dim fileParam As String = "file=..%2Fdata%2F" & search2

            'Dim URLforRetrieve As String = _
            '  "http://mascot4.bmb.sdu.dk/mascot/cgi/export_dat_2.pl?file=..%2Fdata%2F20080403%2FF049002.dat&REPTYPE=export&_sigthreshold=0.05&REPORT=AUTO&_noerrortolerant=0&_server_mudpit_switch=0.000000001&_ignoreionsscorebelow=15&_showsubsets=0&_showpopups=TRUE&_sortunassigned=scoredown&_requireboldred=0"
            'Dim URLforRetrieve As String = _
            '  "http://mascot4.bmb.sdu.dk/mascot/cgi/export_dat_2.pl?file=..%2Fdata%2F20080403%2FF049002.dat&do_export=1&prot_hit_num=1&prot_acc=1&pep_query=1&pep_rank=1&pep_isbold=1&pep_exp_mz=1&_showallfromerrortolerant=0&_onlyerrortolerant=0&_noerrortolerant=0&_show_decoy_report=0&export_format=CSV&_sigthreshold=0.05&REPORT=AUTO&_server_mudpit_switch=0.000000001&_ignoreionsscorebelow=180&_showsubsets=0&protein_master=1&prot_score=1&prot_desc=1&prot_mass=1&prot_matches=1&prot_cover=1&prot_len=1&prot_pi=1&prot_seq=1"
            'Dim URLforRetrieve As String = _
            '  "http://mascot4.bmb.sdu.dk/mascot/cgi/export_dat_2.pl?file=..%2Fdata%2F20080403%2FF049002.dat&do_export=1&prot_hit_num=1&prot_acc=1&pep_query=1&pep_rank=1&pep_isbold=1&pep_exp_mz=1&_showallfromerrortolerant=0&_onlyerrortolerant=0&_noerrortolerant=0&_show_decoy_report=0&export_format=CSV&_sigthreshold=0.05&REPORT=9999&_server_mudpit_switch=0.000000001&_ignoreionsscorebelow=10&_showsubsets=0&protein_master=1&prot_score=1&prot_desc=1&prot_mass=1&prot_matches=1&prot_cover=1&prot_len=1&prot_pi=1&prot_seq=1&peptide_master=1&pep_exp_mr=1&pep_score=1"
            'Dim URLforRetrieve As String = _
            '  "http://mascot4.bmb.sdu.dk/mascot/cgi/export_dat_2.pl?file=..%2Fdata%2F20080403%2FF049002.dat&do_export=1&prot_hit_num=1&prot_acc=1&pep_query=1&pep_rank=1&pep_isbold=1&pep_exp_mz=1&_showallfromerrortolerant=0&_onlyerrortolerant=0&_noerrortolerant=0&_show_decoy_report=0&export_format=CSV&_sigthreshold=0.05&REPORT=9999&_server_mudpit_switch=0.000000001&_ignoreionsscorebelow=10&_showsubsets=0&protein_master=1&prot_score=1&prot_desc=1&prot_mass=1&prot_matches=1&prot_cover=1&prot_len=1&prot_pi=1&prot_seq=1&peptide_master=1&pep_exp_mr=1&pep_score=1"

            'U:\temp2\QSTAR sample, F037366.html
            'http://mascot4.bmb.sdu.dk/mascot/cgi/master_results.pl?file=../data/20070716/F037366.dat

            Dim URLforRetrieve As String = _
              sURL2 & exportPartialURL & fileParam & otherParams

            Dim AppFolderPath As String = appPath()

            Dim mascotResultFileFullPath As String = mWiffFile.MascotFilePath
            Dim parseID As String = _
              Path.GetFileNameWithoutExtension(mascotResultFileFullPath)
            Dim fileNamePrefix As String = "_downloaded_protein_information_"
            Dim saveFileName2 As String = _
              fileNamePrefix & parseID & ".csv"

            Dim fullPathSaveFileName2 As String = _
              AppFolderPath & Path.DirectorySeparatorChar & saveFileName2

            'Note: if there is no path then the file is saved on the desktop...

            'We cache the protein information - if it has already been
            'downloaded then we don't download it, but use the saved
            'file instead.

            If Not File.Exists(fullPathSaveFileName2) Then
                Dim wc As System.Net.WebClient = New System.Net.WebClient
                Try
                    'Note 1: is a UNIX text file, not a Windows/DOS text file...
                    'Note 2: the public Matrix Science site does not support
                    '        returning the protein sequence...
                    'Note 3: timeout can not be controlled for DownloadFile().
                    '
                    'wc.DownloadFile(URLforRetrieve, fullPathSaveFileName2)

                    Dim timeOutSecs As Double = 10 * 60.0
                    timeOutSecs = 50 * 60 '50 minutes.
                    SDUPinternetUtilities.SDUP_DownloadFile( _
                      URLforRetrieve, fullPathSaveFileName2, timeOutSecs)

                Catch exceptionObject As Exception
                    displayStandardExceptionInfo( _
                      exceptionObject, _
                      "Could not download " & Environment.NewLine & _
                      Environment.NewLine & _
                      "<" & URLforRetrieve & "> " & Environment.NewLine & _
                      Environment.NewLine & _
                      "to file " & _
                      fullPathSaveFileName2 & ". " & Environment.NewLine & _
                      Environment.NewLine)

                    'For testing.
                    'Dim tFile As String = "_temp_14h54m38s"
                    Dim tFile As String = "_temp_13h9m30s"

                    Dim testFile As String = _
                      AppFolderPath & Path.DirectorySeparatorChar & _
                      tFile

                    If File.Exists(testFile) Then
                        fullPathSaveFileName2 = testFile
                    Else
                        Exit Sub
                    End If
                End Try
            End If 'If no cached file.

            Me.parseExport2file( _
              fullPathSaveFileName2, _
              proteinLookupHash, _
              mParsedProts2, _
              peptideFilter)
        End If 'Block.
    End Sub 'mRetrieveProteinsParametersForm_pepFilterDismissed()


    'Changed PM_SEQUENCE_COVERAGE 2008-04-15
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub computeAndSetSequenceCoverage()

        Dim visualSelection4 As List(Of visibleIndexStruct) = _
          quantApplication.copySelectedIndices3(lstProtHits)

        Dim lastVisualIndex3 As Integer = visualSelection4.Count - 1

        'Changed PM_SEQUENCE_COVERAGE 2008-12-16
        Dim sequenceTooShortCount As Integer = 0
        Dim noPositionInformationCount As Integer = 0
        Dim proteinsWithSequence As Integer = 0

        Dim i As Integer
        For i = 0 To lastVisualIndex3

            'Changed PM_REFACTOR 2008-09-25. Now in a struct...
            Dim visualIndex3 As Integer = visualSelection4(i).visualIdx2

            Dim dataStructureIndex3 As Integer = _
              Me.getProteinIndexFromVisualIndex(visualIndex3)

            Dim someProt As ProteinHitStructure = _
              mParsedProts2(dataStructureIndex3)

            Dim seqLen As Integer = 0
            If Not someProt.sequence Is Nothing Then
                seqLen = someProt.sequence.Length()
            End If

            If seqLen > 0 Then
                proteinsWithSequence += 1

                Dim hitMap As List(Of Integer) = _
                  New List(Of Integer)(seqLen)

                Dim k As Integer
                For k = 1 To seqLen
                    hitMap.Add(0)
                Next k

                Dim dirty As Boolean = False

                'Changed PM_SEQUENCE_COVERAGE 2008-12-16
                Dim sequenceTooShort As Boolean = False

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

                Dim pepIter As peptideListIterator = _
                  New peptideListIterator(someProt.peptides)
                While Not pepIter.nextPeptide(pept)
                    If pept.verified Then
                        dirty = True

                        Dim startPosition As Integer = _
                          pept.startPositionInProtein
                        Dim endPosition As Integer = _
                          pept.endPositionInProtein

                        If startPosition >= 1 Then
                            Dim j As Integer
                            For j = startPosition To endPosition
                                Dim zeroBased As Integer = j - 1

                                If zeroBased < seqLen Then
                                    hitMap(zeroBased) += 1
                                Else
                                    'Changed PM_SEQUENCE_COVERAGE 2008-12-16
                                    'This means the sequence (e.g. directly
                                    'from the Mascot server) is probably
                                    '***incorrect***. Less likely is that 
                                    'a newer version of the entry in the 
                                    'sequence database has changed.
                                    '
                                    sequenceTooShort = True
                                    sequenceTooShortCount += 1
                                    Exit For 'We can stop as the rest will be 
                                    '  past. We also need for
                                    '  sequenceTooShortCount to be correct.
                                End If
                            Next j
                        Else
                            noPositionInformationCount += 1
                        End If

                    End If
                End While 'Through peptides.

                If dirty Then
                    Dim aminoAcidsHit As Integer = 0
                    Dim lastIndex As Integer = hitMap.Count() - 1
                    Dim j As Integer
                    For j = 0 To lastIndex
                        If hitMap(j) > 0 Then
                            aminoAcidsHit += 1
                        End If
                    Next j

                    Dim sequenceCoverage As Double = _
                      (100.0 * aminoAcidsHit) / seqLen
                    someProt.sequenceCoverage = sequenceCoverage

                    Me.updateProtein(dataStructureIndex3, someProt)

                    mParsedProts2(dataStructureIndex3) = someProt 'Write-back...
                End If
            End If 'Protein sequence
        Next i 'Through proteins

        'Changed PM_SEQUENCE_COVERAGE 2008-12-16
        If sequenceTooShortCount > 0 Then
            Dim msgStr As String = _
              "Warning: " & sequenceTooShortCount & _
              " proteins had a shorter sequence than "
            MsgBox(msgStr)
        End If

        If noPositionInformationCount > 0 Then
            Dim msgStr As String = _
              "Warning: " & noPositionInformationCount & _
              " peptides did not have any protein position information (in " & _
              proteinsWithSequence & " proteins with a sequence). " & _
              "This can happen if, at the time of the Mascot search, " & _
              "the Mascot server installation was not modified to " & _
              "return protein position information."
            MsgBox(msgStr)
        End If

    End Sub 'computeSequenceCoverage


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

        Dim peter2 As Integer = 2 'Do nothing...
    End Sub 'frmProteinList_Load


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

        'Changed PM_SEQUENCE_COVERAGE 2008-04-15
        If lstProtHits.SelectedIndices.Count > 0 Then 'This check
            '  should not be necessary... ASSERT instead?

            computeAndSetSequenceCoverage()
        End If
    End Sub 'mnuComputeAndSetSequenceCoverage_Click


    '****************************************************************************
    '*    <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 Provalidation window, again routed
        'from the Quantitation window, to persist export dialog settings.
        '
        'Just route on, to Protein List window.
        mParentForm.setProteinAndPeptidesFilter2( _
          aInProteinAndPeptidesFilter2, _
          aPeptideFilter)
    End Sub 'setProteinAndPeptidesFilter


    'Changed PM_CONVENIENCE 2008-05-30
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuOpenResultFileFolder_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuOpenResultFileFolder.Click

        Dim MascotResultFileName As String = mWiffFile.MascotFilePath
        showFileInWindowsExplorer( _
          MascotResultFileName, "Opening the Mascot Result File.")
    End Sub 'mnuOpenResultFileFolder_Click


    'Changed PM_CONVENIENCE 2008-05-30
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuOpenRawFileFolder_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuOpenRawFileFolder.Click

        Dim rawFileName As String = mWiffFile.rawFilePath
        showFileInWindowsExplorer( _
          rawFileName, "Opening the raw file.")
    End Sub 'mnuOpenRawFileFolder_Click


    'Not needed anyway...
    ' 'Changed PM_AVOID_EXCEL 2008-08-21
    ' '****************************************************************************
    ' '*    <placeholder for header>                                              *
    ' '****************************************************************************
    ' Private Function getLastestExportTarget( _
    '   ByRef anOutTargetSettings As exportTargetSettingsStruct) _
    '   As Boolean
    ' 
    '     Dim toReturn As Boolean = False 'Default, it fails...
    ' 
    '     If mLastProtPeptExportTargetSettings.userAppPath <> "XYZ" Then
    '         toReturn = True
    '         anOutTargetSettings = mLastProtPeptExportTargetSettings
    '     Else
    '         MsgBox("")
    '     End If
    '     Return toReturn
    ' End Function 'getLastestExportTarget()


    'Changed PM_REFACTOR 2008-09-29
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function dataStructureIndexesForSelected( _
      ByRef aInListView As ListViewCEBIExtended4) _
      As List(Of Integer)

        'What happens if the selection is empty??

        Dim protein_visualIndices3 As List(Of visibleIndexStruct) = _
          quantApplication.copySelectedIndices3(lstProtHits)

        Dim protein_datastructureIndices As List(Of Integer) = _
          Me.selectedIndices2DatastructureIndices2(protein_visualIndices3)

        Return protein_datastructureIndices
    End Function 'dataStructureIndexesForSelected()


    'Changed PM_PCP_PLOT 2008-10-01. Move to a more appropriately place.
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Shared Function deriveRawFileID2dimensionIndex( _
      ByVal aRawFileMapping As Dictionary(Of Integer, rawFileStruct4), _
      ByRef anInNpointHashValue2dimensionIndex As _
        Dictionary(Of Integer, Integer)) _
 _
      As Dictionary(Of Integer, Integer)


        Dim lenForPreallocate As Integer = 10 'The real number
        '  is the number of different ***values*** in hash
        '  anInNpointHashValue2dimensionNumber.

        Dim rawFileID2dimensionNumber As Dictionary(Of Integer, Integer) = _
          New Dictionary(Of Integer, Integer)(lenForPreallocate)

        Dim hashEnumerator2 As Dictionary( _
          Of Integer, rawFileStruct4).Enumerator = _
            aRawFileMapping.GetEnumerator()

        While hashEnumerator2.MoveNext()
            Dim NpointHashValue As Integer = hashEnumerator2.Current.Key
            Dim curValue As rawFileStruct4 = hashEnumerator2.Current.Value

            Dim fileID As Integer = curValue.rawFileID7

            If fileID >= 0 Then

                Dim dimensionIndex As Integer
                If anInNpointHashValue2dimensionIndex.TryGetValue( _
                  NpointHashValue, dimensionIndex) Then

                    rawFileID2dimensionNumber.Add(fileID, dimensionIndex)
                Else
                    'Unexpected failure. Reason: .

                    Dim msgStr As String = _
                      "No value found for key " & NpointHashValue & _
                      ". File ID is " & fileID & ", " & curValue.rawFile & _
                      ". " & _
                      "This happens when the size of a dimension (e.g. sucrose fraction) has been reduced and the file mapping has not been changed accordingly. "
                    MsgBox(msgStr)

                    Exit While 'Limit the number of dialog boxes...
                End If
            Else
                Dim peter2 As Integer = 2 'File mapping not defined.
            End If

        End While 'Hash iteration.

        Return rawFileID2dimensionNumber
    End Function 'deriveRawFileID2dimensionIndex


    'Changed PM_SILAC_AWARE_PEPTIDEFILTERDIALOG 2008-10-05
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function constructSILACmods() _
      As Dictionary(Of Integer, Integer)

        'Note: we can't cache the list of SILAC modifications as it
        '      should change if the user choses another quantitation
        '      mode.
        Dim quantitationModesObject As QuantitationModes_moreGeneral = _
          mApplication.getQuantModes()
        Dim SILACmods As Dictionary(Of Integer, Integer) = _
          quantitationModesObject.modificationIDsForQuantitationMode( _
            mOptions.quantModeCode)

        Return SILACmods
    End Function 'constructSILACmods()


    'Changed PM_PCP_PLOT_OPENPROTEIN 2008-10-14
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub openProtein( _
      ByVal aProteinHitNumber As Integer, _
      ByVal aDimensionNumber As Integer)

        openParticularPeptide(aProteinHitNumber, 0)
        'mCurrentFrmProtValidation.doUnattentedQuantitation(False)
        mCurrentFrmProtValidation.quantLabeledProtein(False)
    End Sub 'openProtein()


    'Changed PM_GENERALISED_EXPORT 2005-03-08
    'Is called when the dialog ends..........
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub setProteinAndPeptidesFilter_export3( _
      ByVal aInProteinAndPeptidesFilter2 As proteinAndPeptidesFilterStructure2, _
      ByVal aPeptideFilter As peptideFilterStructure)

        If True Then 'Saving copies here.
            'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-29. Store it in
            'options instead
            'mProteinAndPeptidesFilter2 = aInProteinAndPeptidesFilter2
            mOptions.proteinAndPeptidesFilter = aInProteinAndPeptidesFilter2

            'Updated here, but it should also be updated in another class from
            'where it is loaded/saved.
            mOptions.peptideFilters(peptideFilterEnum.enumExport2) = _
              aPeptideFilter
        End If

        'Use our mark that we sat when we initiated the export dialog: should
        'the result be exported to Excel or saved to a file.
        Select Case aInProteinAndPeptidesFilter2.tag
            Case tagEnum.enumTag1

                'Changed PM_COMMANDLINE_EXPORT 2008-08-22
                'Moved visual selection part from exportProteinsAndPeptides_Common3()
                'to here.
                '
                'Note: this takes a very long time, dominating time to export.
                '      E.g. 17 secs for 1267 proteins. See notes in
                '      copySelectedIndices3() for more details. Update: it
                '      has been speeded up now!!
                '
                Dim protein_visualIndices2 As List(Of visibleIndexStruct) = _
                  quantApplication.copySelectedIndices3(lstProtHits)

                Dim datastructureIndices As List(Of Integer) = _
                  Me.selectedIndices2DatastructureIndices2(protein_visualIndices2)

                'Changed PM_WRONG_PROTEINS 2008-09-25. Second parameter to
                '  exportProteinsAndPeptides_Common3() was 
                '  protein_visualIndices2 !! - visual indexes were passed 
                '  as datastructure indexes.

                'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
                Dim exportTargetSettings As exportTargetSettingsStruct = _
                  aInProteinAndPeptidesFilter2.exportTargetSettings4
                quantApplication.checkExportSettings(exportTargetSettings)
                '  This will present the target dialog to the user if
                '  the setting has not been persisted yet.

                PILInputOutput.pushToTarget( _
                  Me.exportProteinsAndPeptides_Common3( _
                    aInProteinAndPeptidesFilter2, datastructureIndices), _
                  exportTargetSettings, _
                  appPath())

            Case tagEnum.enumTag2

                'Changed PM_AVOID_EXCEL 2008-08-22. Saving to file is now
                '  handled elsewhere.
                ' 'Changed PM_SAVEDIALOG_TITLE 2005-12-01
                ' SaveFileDialog1.Title = "Saving protein and peptide information"
                ' 
                ' 'Use return value for some text reporting to GUI?
                ' Dim wasSaved As Boolean = _
                '   pushToUserSelectedFile2( _
                '     Me.exportProteinsAndPeptides_Common2( _
                '     aInProteinAndPeptidesFilter2), _
                '     "Saved some peptides to file")
                Trace.Assert(False, _
                  "PIL ASSERT. This should never happen...")

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

        'Perhaps the new settings from the export dialog should not be
        'persisted if the user cancelled the save dialog?.

        'Pass on to the global and most recent version of options...
        '
        'Note that we only pass on what has been changed here and not the
        '  entire options (that we have a copy of and that may not be up-to-date;
        '  the user may have changed some settings after we got the copy).
        mParentForm.setProteinAndPeptidesFilter2( _
          aInProteinAndPeptidesFilter2, _
          aPeptideFilter)
    End Sub 'setProteinAndPeptidesFilter_export3()


    'Changed PM_SPECTRAEXPORT_GENERALISED 2008-05-05
    'From export/save protein/peptide/spectra-dialog.
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '*    Call-back from peptide filter form.                                   *
    '****************************************************************************
    Private Sub mExportProteinsAndPeptidesFiltersForm_dialogDismissed( _
      ByVal aSender As Object, _
      ByVal anEvent As exportFilterEventArgs) _
      Handles mExportProteinsAndPeptidesFiltersForm.exportFilterDismissed

        Dim newValues As exportFilterValuesStructure = anEvent.getFilter()

        Me.setProteinAndPeptidesFilter_export3( _
          newValues.proteinAndPeptidesFilter, newValues.peptideFilter)
    End Sub 'mExportProteinsAndPeptidesFiltersForm_dialogDismissed()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub startExportOrSavePeptidesAndProteins2(ByVal aType As tagEnum)

        'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-29
        'mProteinAndPeptidesFilter2.tag = aType
        Dim protPepFilter As proteinAndPeptidesFilterStructure2 = _
          mOptions.proteinAndPeptidesFilter
        protPepFilter.tag = aType

        quantApplication.checkExportSettings(protPepFilter.exportTargetSettings4)
        '  This will present the target dialog to the user if
        '  the setting has not been persisted yet.

        Dim extraText As String = _
          "For " & lstProtHits.SelectedIndices.Count & " selected proteins."

        'Changed PM_SILAC_AWARE_PEPTIDEFILTERDIALOG 2008-10-05
        Dim quantitationModesObject As QuantitationModes_moreGeneral = _
          mApplication.getQuantModes()
        Dim SILACmods As Dictionary(Of Integer, Integer) = _
          quantitationModesObject.modificationIDsForQuantitationMode( _
            mOptions.quantModeCode)

        'Changed PM_DISPLAY_NUMBER_SELECTED 2006-12-30. New parameter,
        'number of selected proteins - to be displayed in the dialog.
        mExportProteinsAndPeptidesFiltersForm = New frmExportFilters( _
          protPepFilter, _
          extraText, _
          mApplication, _
          mOptions.peptideFilters(peptideFilterEnum.enumExport2), _
          mRawFiles2, _
          SILACmods)

        'Note: mExportFiltersForm_dialogDismissed() handles the event from
        '      the dialog, in turn calling setProteinAndPeptidesFilter_export2().
        '      
        mExportProteinsAndPeptidesFiltersForm.Show()
    End Sub 'startExportOrSavePeptidesAndProteins2()


    'Changed PM_EXPORTS_ON_SELECTION 2005-03-01
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSaveProteinsAndPeptides_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuSaveProteinsAndPeptides.Click

        'Now disabled. We should eliminate the complicated stuff with enumTag1
        'and enumTag2 (that remembered the distinction between export/save after
        'the dialog had finished.)

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

        Me.startExportOrSavePeptidesAndProteins2(tagEnum.enumTag2) 'User 
        ' selects a file after the export dialog has been OK'ed.
        ' Call-back/event handler is mExportFiltersForm_dialogDismissed().
    End Sub 'mnuSaveProteinsAndPeptides_Click


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

        Me.startExportOrSavePeptidesAndProteins2(tagEnum.enumTag1) 'Use export.

        'The actual export will take place when the user is done
        'with the ***export*** dialog.
        ' Call-back/event handler is mExportFiltersForm_dialogDismissed().
    End Sub 'mnuExportProteinsAndPeptides_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mergeTags( _
      ByRef anInOutToAddTo As List(Of taggingStruct), _
      ByRef anInOutMergeFrom As List(Of taggingStruct) _
      )
        'Note: two nested loops. But both of the lists are usually
        '      very short. Using a hash would waste more memory.

        If Not anInOutMergeFrom Is Nothing Then
            If Not anInOutToAddTo Is Nothing Then

                Dim someItem1 As taggingStruct
                For Each someItem1 In anInOutMergeFrom

                    Dim alreadyExists As Boolean = False

                    Dim someItem2 As taggingStruct
                    For Each someItem2 In anInOutToAddTo

                        If someItem1.tag2 = someItem2.tag2 Then
                            alreadyExists = True

                            Exit For
                        End If
                    Next 'Through anInOutToAddTo

                    If Not alreadyExists Then
                        anInOutToAddTo.Add(someItem1)
                    End If
                Next 'Through anInOutMergeFrom
            Else
                'Input is empty. The output is then the merge-from list.
                anInOutToAddTo = anInOutMergeFrom
            End If
        Else
            'Nothing to merge. We do nothing.
            Dim peter2 As Integer = 2
        End If
    End Sub 'mergeTags()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function replaceTags( _
      ByRef anInOldEmbeddedTags As String, _
      ByRef anInNewTags As String, _
      ByRef anInOutScratch As StringBuilder) _
      As String

        anInOutScratch.Length = 0

        'For now: assume the existing tags are at the end.
        Dim tagStartIndex As Integer = anInOldEmbeddedTags.IndexOf("MTAGS: ")
        If tagStartIndex >= 0 Then
            Dim len As Integer = tagStartIndex
            anInOutScratch.Append(anInOldEmbeddedTags.Substring(0, len))
        Else
            'No existing. Just append.
            anInOutScratch.Append(anInOldEmbeddedTags)
        End If
        anInOutScratch.Append(" ")
        anInOutScratch.Append(anInNewTags)

        Return anInOutScratch.ToString
    End Function 'replaceTags()


    'Changed PM_PROTEIN_TAGS 2008-10-29
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub applyTags( _
      ByRef anInTagList As List(Of taggingStruct), _
      ByVal aMerge As Boolean)
        'If aMerge is false then the existing tag is replaced with the new.


        'We do need the visual indexes as we are going to do screen updates.
        'Dim protein_datastructureIndices As List(Of Integer) = _
        '  dataStructureIndexesForSelected(lstProtHits)
        Dim protein_visualIndices3 As List(Of visibleIndexStruct) = _
          quantApplication.copySelectedIndices3(lstProtHits)
        Dim protein_datastructureIndices As List(Of Integer) = _
          Me.selectedIndices2DatastructureIndices2(protein_visualIndices3)

        Dim proteins As Integer = protein_datastructureIndices.Count
        If proteins > 0 Then

            Dim ssb As StringBuilder = New StringBuilder(300)

            lstProtHits.BeginUpdate()

            Dim lastIndex As Integer = protein_datastructureIndices.Count - 1
            Dim i As Integer
            For i = 0 To lastIndex 'Through selected proteins.
                Dim dataIndex As Integer = protein_datastructureIndices(i)
                Dim someProt As ProteinHitStructure = _
                  mParsedProts2(dataIndex)

                'Apply all tags to current protein.

                Dim descr As String = someProt.description3

                Dim tags As List(Of taggingStruct) = Nothing
                If aMerge Then
                    tags = tagging.extractTags(descr)
                Else
                    Dim peter2 As Integer = 2 'Replace existing.
                End If

                mergeTags(tags, anInTagList)
                Dim newTags As String = tagging.outputTags(tags, ssb)

                Dim newDescription As String = _
                  replaceTags(descr, newTags, ssb)

                someProt.description3 = newDescription
                mParsedProts2(dataIndex) = someProt 'Writeback.

                'Update in GUI
                Dim visualIndex As Integer = _
                  protein_visualIndices3(i).visualIdx2
                Dim someProteinRow As ListViewItem = _
                  lstProtHits.Items(visualIndex)
                mColumnMapper.updateListItem( _
                  someProteinRow, proteinColumnEnum.enumProteinDescription2, _
                  newDescription)

                Dim primaryTagStr As String = tagging.primaryTag(tags, mSsb)
                mColumnMapper.updateListItem( _
                  someProteinRow, proteinColumnEnum.enumPrimaryProteinTag2, _
                  primaryTagStr)
            Next 'Through selected proteins.

            lstProtHits.EndUpdate()
        End If 'Non-empty selection.
    End Sub 'applyTags()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mTaggingForm_tagListDismissed( _
      ByVal aSender As Object, _
      ByVal anEvent As tagListEventArgs) _
      Handles mTaggingForm.tagListDismissed

        'Note: we rely on protein selection not being changed while the
        '      tag dialog is open. The consequence would be only applying the 
        '      tags to the changed selection of proteins.

        Dim tagList As List(Of taggingStruct) = anEvent.getTagList()

        Me.applyTags(tagList, True)
    End Sub 'mTaggingForm_tagListDismissed


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

        'Deleting is simply done by passing an empty list and specify replace...
        Me.applyTags(Nothing, False)
    End Sub 'mnuDeleteAllTags_Click


    'Changed PM_REFACTOR 2008-11-05
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub setupProfileDataStructures( _
      ByRef anInOutPlotValues As List(Of proteinPCPstructure), _
      ByRef anOutMinbucketIndex As Integer, _
      ByRef anOutProtein_datastructureIndices As List(Of Integer) _
      )

        'Dim plotValues As List(Of MolecularSharedStructures.proteinPCPstructure) = _
        '  Nothing 'Flag. Defer initialisation till we know the 
        ''  number of dishes.
        anInOutPlotValues = Nothing 'Value if no proteins selected.

        anOutMinbucketIndex = -1 'Just in case.

        anOutProtein_datastructureIndices = _
          dataStructureIndexesForSelected(lstProtHits)

        Dim proteins As Integer = anOutProtein_datastructureIndices.Count
        If proteins > 0 Then
            'mExperimentSettings.JAspace.getVectorSet()
            Dim dimensions As List(Of CEBIdimension) = _
              mExperimentSettings.JAspace.getDimensionDefinitions()
            Dim dlen As Integer = dimensions.Count()

            Dim keyOrder As List(Of Integer) = New List(Of Integer)(dlen)

            If True Then
                'For now: primary is the first dimension, sucrose
                '         fraction for the default content.
                'Later: user specified.
                Dim lastIndex3 As Integer = dlen - 1
                Dim j As Integer
                For j = 0 To lastIndex3
                    keyOrder.Add(j)
                Next j
            End If

            'In return value we can rely on first getting all the
            'points for which the primary dimension's index
            'is 0 (e.g. sucrose fraction 1), then the points
            'for which the primary dimension's index is 1 (e.g.
            'sucrose fraction 2) and so on. 
            '
            'mExperimentSettings.JAspace.getSortedVectorSet()

            'Dim buckets As Integer
            'Dim minbucketIndex As Integer

            Dim maxbucketIndex As Integer

            'From Npoint hash value to dimension number.
            Dim mapHash As Dictionary(Of Integer, Integer) = _
              mExperimentSettings.JAspace.getMapHash( _
                keyOrder, anOutMinbucketIndex, maxbucketIndex)
            Dim buckets As Integer = maxbucketIndex - anOutMinbucketIndex + 1

            Dim rawFileID2dimensionIndex As Dictionary(Of Integer, Integer) = _
              deriveRawFileID2dimensionIndex( _
                mExperimentSettings.rawFileMapping3, mapHash)


            '  Return value: hash to map from a raw file ID (e.g. 813) to
            '                primary dimension (e.g. 3 for sucrose
            '                fraction 4). More than one raw file may
            '                map to the same dimension number - that
            '                is the whole point. E.g. gel slice is not
            '                considered and ***all*** gel slices for a sucrose
            '                fraction go into computing the protein 
            '                ratio value (e.g. averaging the protein ratios).

            'Later: some kind of check that all dimensions are fully
            '       or partly represented by the raw file. E.g.
            '       if 10 gel fractions are specified then at 
            '       least 1 raw file per gel fractions should 
            '       map to that gel slice.

            If True Then 'Block. Go through the selected proteins.

                'When plotting: move the codebelow to the dialog to
                '               intersperse with building
                '               of plot data structures (thus abondoning/not
                '               storing the real values)

                'Later: some (on-the-fly) actions: normalise peptide
                '       ratios. Compute protein ratios.

                Dim bailOut As Boolean = False 'For avoiding too many message
                '  boxes when a raw file is not mapped.

                Dim lastIndex4 As Integer = _
                  anOutProtein_datastructureIndices.Count - 1
                Dim i As Integer
                For i = 0 To lastIndex4 'Through selected proteins
                    Dim dataIndex As Integer = _
                      anOutProtein_datastructureIndices(i)
                    Dim someProt As ProteinHitStructure = _
                      mParsedProts2(dataIndex)

                    'Any quantitation result?
                    If Not someProt.quantResults3 Is Nothing Then

                        'For now: just get some quant results.

                        'Dim dish2 As Integer = 1 'SILAC dish 2...
                        Dim dishes As Integer = someProt.quantResults3.Count

                        If anInOutPlotValues Is Nothing Then 'We have to wait until now - we
                            '  now know the number of dishes.
                            anInOutPlotValues = _
                              MolecularSharedStructures.proteinPCPstructure.initList( _
                                proteins, buckets, dishes)
                        End If

                        Dim lastIndex5 As Integer = dishes - 1
                        Dim dishZ As Integer
                        For dishZ = 0 To lastIndex5

                            Dim oneDish As oneDishResultStructure = _
                              someProt.quantResults3(dishZ)

                            If dataIndex < 0 Then
                                Dim peter2 As Integer = 2
                            End If

                            Dim prPlotVals As MolecularSharedStructures.proteinPCPstructure = _
                              anInOutPlotValues(i)
                            prPlotVals.proteinDataIndex2 = dataIndex

                            'Trace.Assert(Not oneDish.quantRes2 Is Nothing, _
                            '  "PIL ASSERT. oneDish.quantRes2 is Nothing. " & _
                            '  "In setupProfileDataStructures().")


                            'Key is file ID number.

                            Dim hashEnumerator2 As Dictionary( _
                              Of Integer, protSILACresultStructure).Enumerator = Nothing

                            'Changed PM_PCP_PLOT_EMPTYQUANTRESULT_CRASH 2008-11-08.
                            'While hashEnumerator2.MoveNext()
                            'Save one ident level by using hashEnumerator2 as a flag...
                            Dim someQuantResult As Boolean = _
                              Not oneDish.quantRes2 Is Nothing
                            If someQuantResult Then
                                hashEnumerator2 = oneDish.quantRes2.GetEnumerator()
                            Else
                                Dim peter2 As Integer = 2 'No quant result...
                            End If
                            While someQuantResult AndAlso _
                                  hashEnumerator2.MoveNext()

                                Dim curKey As Integer = hashEnumerator2.Current.Key

                                If curKey <> _
                                  MultipleRawFilesHandling.REF_WHOLEPROTEIN Then

                                    Dim curValue As protSILACresultStructure = _
                                       hashEnumerator2.Current.Value

                                    Dim dimIdx2 As Integer

                                    If rawFileID2dimensionIndex.TryGetValue( _
                                      curKey, dimIdx2) Then

                                        dimIdx2 -= anOutMinbucketIndex 'Down to zero based index.

                                        Dim rawFileRatio As Double = _
                                          curValue.averageRatioToBase
                                        Dim N As Integer = -1 'N is not available!!!

                                        'Changed PM_PCP_PLOT_SEVERAL_DISHES 2008-10-16
                                        'someProteinPlotValues.values(dimensionIndex) += _
                                        '  rawFileRatio

                                        'prPlotVals.dimensionValues(dimIdx2).SILACdishes2(dishZ)
                                        Dim dishValues As _
                                          singleSILACvaluesStructure = _
                                            prPlotVals.profiles(dishZ).dimensionValues(dimIdx2)

                                        dishValues.SILACratio2 += rawFileRatio

                                        prPlotVals.profiles(dishZ).dimensionValues(dimIdx2) = _
                                          dishValues 'Write back (for the updated ratio values).

                                        'prPlotVals.Ns(dimIdx2) += N
                                    Else
                                        Dim msgStr As String = _
                                          "Could not find raw file for fild ID " & _
                                          curKey & ". Not defined in the raw file mapping. " & _
                                          "Change it using the raw file mapping dialog " & _
                                          "(main Window/Tools/Raw File Mapping)"
                                        MsgBox(msgStr)

                                        'No longer enough with the extra for loop...
                                        'Exit For 'Exit the outer loop, not just
                                        ''  the inner. In order to reduce the
                                        ''  number of dialog boxes. We don't
                                        ''  want one for every protein.
                                        bailOut = True
                                    End If
                                Else
                                    'The for all of protein value (not for a
                                    'single raw file).
                                    Dim peter4 As Integer = 4
                                End If

                                'Note: we are not checking bailOut. This will
                                '      result in a message box for each unmapped
                                '      raw file. But no more, we are exiting
                                '      right after this loop.
                            End While 'Hash iteration.

                            '  Iterate through prPlotVals.values2 and derive 
                            '    prPlotVals.values2(0).identicalZeros 
                            '    and set prPlotVals.values2(0).SILACdishes2.

                            If True Then 'Block. Setting derived value, identicalZeros.
                                Dim someProteinProfile As proteinProfileStructure = _
                                  prPlotVals.profiles(dishZ)

                                Dim anyZeros As Boolean = False
                                Dim someItem4 As singleSILACvaluesStructure
                                For Each someItem4 In someProteinProfile.dimensionValues
                                    If someItem4.SILACratio2 < 0.000001 Then

                                        someProteinProfile.identicalZeros += 1
                                        anyZeros = True
                                    Else
                                        Dim peter2 As Integer = 2
                                    End If
                                Next 'Through a protein profile.

                                If anyZeros Then
                                    prPlotVals.profiles(dishZ) = someProteinProfile 'Write
                                    '  back.
                                End If
                            End If 'Block. Setting derived value, identicalZeros.

                            anInOutPlotValues(i) = prPlotVals 'Write back.

                            'At least for now: we connect quantitation
                            'results to N-points through the raw file...
                            '
                            'But perhaps it would be more natural to
                            'use N-point (or equivalent hash value) to store by?

                            If bailOut Then
                                Exit For
                            End If
                        Next dishZ 'Through SILAC dishes.

                    End If 'There is a quantitation result.

                    If bailOut Then
                        Exit For
                    End If
                Next 'Through selected proteins.
            End If 'Block. Go through selected proteins.

        End If 'Non-empty protein selection

    End Sub 'setupProfileDataStructures()


    'Changed PM_PCP_PLOT 2008-09-29
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuDisplayProteinProfiles_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuDisplayProteinProfiles.Click

        Dim plotValues As List(Of proteinPCPstructure) = Nothing
        Dim minbucketIndex As Integer
        Dim protein_datastructureIndices As List(Of Integer) = Nothing
        setupProfileDataStructures( _
          plotValues, minbucketIndex, protein_datastructureIndices)

        If Not plotValues Is Nothing Then
            Dim primaryDimensionName As String = "Sucrose fraction" 'For now.
            Dim someForm As frmPCPplot = New frmPCPplot( _
              plotValues, mParsedProts2, primaryDimensionName, _
              Me, minbucketIndex, mConsensus, _
              mParseIDnumber)
            someForm.Show()
        End If 'No proteins selected.
    End Sub 'mnuDisplayProteinProfiles_Click


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSetConsensusProfile_Click( _
      ByVal aSender As System.Object, ByVal e As System.EventArgs) _
      Handles mnuSetConsensusProfile.Click

        Dim plotValues As List(Of proteinPCPstructure) = Nothing
        Dim minbucketIndex As Integer
        Dim protein_datastructureIndices As List(Of Integer) = Nothing
        setupProfileDataStructures( _
          plotValues, minbucketIndex, protein_datastructureIndices)

        If Not plotValues Is Nothing Then
            'Make consensus profile. Use statistics class to compute 
            'max, min, average, N, standard deviation, etc.

            Dim dishes As Integer = _
              ProteinHitStructure.getDishesFromQuantResult(plotValues)

            Dim dims As Integer = _
              plotValues(0).profiles(0).dimensionValues.Count

            Dim consensus As List(Of frmProteinList.consensusDishInfoStruct) = _
              New List(Of frmProteinList.consensusDishInfoStruct)(dishes)

            If True Then 'Initialisation
                Dim dish As Integer
                For dish = 1 To dishes

                    Dim consensusForDish As List(Of statsStructure) = _
                      New List(Of statsStructure)(dims)
                    Dim j As Integer
                    For j = 1 To dims
                        consensusForDish.Add( _
                          New statsStructure(0, False, True))
                    Next j

                    Dim consensusDishInfo As consensusDishInfoStruct
                    consensusDishInfo.profile = consensusForDish

                    'Computed below.
                    consensusDishInfo.invcov = Nothing
                    consensusDishInfo.mean = Nothing

                    consensus.Add(consensusDishInfo)
                Next dish
            End If 'Block. Initialisation.

            Dim PCPinfo As proteinPCPstructure
            For Each PCPinfo In plotValues 'One item for each protein 

                Dim lastIndex As Integer = dishes - 1
                Dim dishZbased As Integer
                For dishZbased = 0 To lastIndex

                    Dim someProfile As proteinProfileStructure = _
                      PCPinfo.profiles(dishZbased)

                    Dim d As Integer = 0
                    Dim someSingleSILACvalue As singleSILACvaluesStructure
                    For Each someSingleSILACvalue In someProfile.dimensionValues

                        'consensus(dishZbased)(d).update( _
                        '  someSingleSILACvalue.SILACratio2, 0.0)
                        Dim pointP As statsStructure = _
                          consensus(dishZbased).profile(d)
                        Dim yValue As Double = _
                          someSingleSILACvalue.SILACratio2

                        'Changed PM_IDENTICALZERO_IN_SCORING 2008-11-30. Ignore
                        '  identical zero points when computing the consensus
                        '  profile. This can be considered a sort of outlier
                        '  elimination.
                        Dim identicalZero As Boolean = _
                          yValue <= 0.000001

                        If Not identicalZero Then

                            'Changed PM_CONSENSUSSCORE_LOGTRANSFORMED 2008-11-30
                            'pointP.update(0.0, yValue)
                            Dim transformedValue As Double = _
                              frmPCPplot.ratioTransform(yValue)
                            pointP.update(0.0, transformedValue)

                            consensus(dishZbased).profile(d) = pointP 'Write back. Needed 
                            '  as it is a value type.
                        Else
                            Dim peter2 As Integer = 2 'For breakpoints.
                        End If

                        d += 1
                    Next 'Through profile
                Next 'Through dishes
            Next 'Through protein (results from).

            mConsensus = consensus

            Dim sb As StringBuilder = New StringBuilder(100)
            If True Then
                sb.Append( _
                  "Standard deviations (in transformed domain): ")

                'Evaluate computed consenus.

                Dim lastIndexC As Integer = mConsensus.Count - 1
                Dim dishZ As Integer = 0
                For dishZ = 0 To lastIndexC

                    Dim consensusDishInfo As _
                      frmProteinList.consensusDishInfoStruct = _
                        mConsensus(dishZ)

                    sb.Append(dishZ + 1)
                    sb.Append("; ")

                    'Changed PM_CONSENSUSSCORE_NEW 2008-12-05
                    Dim i2 As GeneralMatrix = Nothing
                    Dim forCov As Double()() = Nothing 'Defer 
                    '  initialisation until we can preallocate.
                    Dim forMeanVector As Double()() = Nothing
                    Dim n As Integer = -1 'Set below.

                    Dim pIndex As Integer = 0
                    Dim lastProfilePointIndex As Integer = _
                      consensusDishInfo.profile.Count - 1

                    Dim consensusPoint As statsStructure
                    For Each consensusPoint In consensusDishInfo.profile

                        '  Dim pointP As statsStructure
                        Dim xAve As Double
                        Dim yAve As Double
                        consensusPoint.average(xAve, yAve)

                        Dim xStd As Double
                        Dim yStd As Double
                        consensusPoint.stddev(xStd, yStd)

                        'Later: avoid last, trailing, comma.

                        sb.Append(yStd.ToString("0.00"))
                        sb.Append(", ")

                        'Changed PM_CONSENSUSSCORE_NEW 2008-12-05
                        If True Then
                            n = consensusPoint.yValues.Count
                            If forCov Is Nothing Then
                                forCov = New Double(n - 1)() {}
                                For i As Integer = 0 To n - 1
                                    forCov(i) = _
                                      New Double(lastProfilePointIndex) {}
                                Next

                                forMeanVector = New Double(0)() {}
                                forMeanVector(0) = _
                                  New Double(lastProfilePointIndex) {}
                            End If

                            'Fill in one measurement vector, in what will 
                            'become a column in the matrix for computing
                            'the covariance matrix.
                            Dim mean As Double = yAve
                            For i As Integer = 0 To n - 1
                                forCov(i)(pIndex) = _
                                  consensusPoint.yValues(i) - mean
                            Next

                            forMeanVector(0)(pIndex) = mean
                        End If

                        pIndex += 1
                    Next 'Through profileForOneDish

                    'Covariance matrix for current dish.
                    If True Then 'Block. Later: move to a general place.
                        Dim Xm As GeneralMatrix = _
                          New GeneralMatrix(forCov)
                        Dim cov As GeneralMatrix = Xm.Transpose() * Xm

                        Dim scale As Double = 1.0 / n 'The alternative
                        '  is N-1: 1.0 / (n-1).
                        cov.MultiplyEquals(scale)

                        Dim invCov As GeneralMatrix = Nothing
                        If dishZ <> 0 Then
                            invCov = cov.Inverse()
                        Else
                            'We would get a failure (trying to computer 
                            '  the inverse) if all values are equal.
                            invCov = cov 'Let it be defined. It could also be
                            '  something else, like the identity matrix.
                        End If

                        Dim meanVector As GeneralMatrix = _
                          New GeneralMatrix(forMeanVector)

                        'Remember together with consensus, for later use
                        'in scoring.
                        consensusDishInfo.invcov = invCov
                        consensusDishInfo.mean = meanVector

                        mConsensus(dishZ) = consensusDishInfo 'Write back.
                    End If 'Block.

                    sb.Append(ControlChars.NewLine)
                Next dishZ 'Through mConsensus

                sb.Append(".")
            End If

            Dim stdStr As String = sb.ToString
            MsgBox( _
              "A consensus profile has been computed for each " & _
              "quantity (e.g. for each SILAC dish ratio) and set based on " & _
              plotValues.Count & " selected proteins. " & _
              ControlChars.NewLine & ControlChars.NewLine & _
              stdStr)
        End If 'Some proteins selected.

    End Sub 'mnuSetConsensusProfile_Click()


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

        Dim plotValues As List(Of proteinPCPstructure) = Nothing
        Dim minbucketIndex As Integer
        Dim protein_datastructureIndices As List(Of Integer) = Nothing
        setupProfileDataStructures( _
          plotValues, minbucketIndex, protein_datastructureIndices)

        Dim anySelectedProteins As Boolean = Not plotValues Is Nothing
        Dim consensusProfileExists As Boolean = Not mConsensus Is Nothing

        If anySelectedProteins AndAlso Not consensusProfileExists Then
            Dim proteins As Integer = plotValues.Count
            Dim msgStr As String = _
              AppConstants.LONG_APP & _
              " can not compute consensus scores for the " & _
              proteins & "selected proteins. " & _
              "The consensus profile has not been set/computed. " & _
              "Select proteins that are member of the consensus set " & _
              "and use the menu command to set the consensus profile."
            MsgBox(msgStr)
        End If

        If anySelectedProteins And consensusProfileExists Then
            Dim dishes As Integer = _
              ProteinHitStructure.getDishesFromQuantResult(plotValues)

            Dim listIndex2 As Integer = 0

            Dim PCPinfo As proteinPCPstructure
            For Each PCPinfo In plotValues 'One item for each protein 

                Dim dataIndex As Integer = _
                  protein_datastructureIndices(listIndex2)
                Dim someProt As ProteinHitStructure = _
                  mParsedProts2(dataIndex)

                'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                'someProt.consensusScore2 = New List(Of Double)(dishes)
                someProt.consensusScore3 = _
                  New List(Of consensusScoreStruct)(dishes)

                Dim lastIndex As Integer = dishes - 1
                Dim dishZbased As Integer
                For dishZbased = 0 To lastIndex

                    Dim valuesForScore As statsStructure = _
                      New statsStructure(0, False, False)

                    Dim someProfile As proteinProfileStructure = _
                      PCPinfo.profiles(dishZbased)

                    Dim d As Integer = 0 'Needed! Better name ?: dimension.

                    'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                    Dim nonZeroPoints2 As Integer = 0
                    Dim withinConsensus As Integer = 0
                    Dim zeroPoints As Integer = 0

                    'Prepare building vector to be used in new
                    'consensus score.
                    Dim pLastIndex As Integer = _
                      someProfile.dimensionValues.Count - 1
                    Dim forMeasurementVector As Double()() = _
                      New Double(0)() {} 'This will be the profile for
                    '  the current protein (and current dish), but in the
                    '  form required by the matrix class...
                    forMeasurementVector(0) = New Double(pLastIndex) {}

                    Dim someSingleSILACvalue As singleSILACvaluesStructure
                    For Each someSingleSILACvalue In someProfile.dimensionValues

                        Dim yValue2 As Double = _
                          someSingleSILACvalue.SILACratio2

                        'Changed PM_THRESHOLD_IDENTICALZERO 2008-11-30. As
                        '  in setupProfileDataStructures().
                        ''Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                        'Dim identicalZero As Boolean = yValue <= 0.0001
                        Dim identicalZero As Boolean = _
                          yValue2 <= 0.000001

                        Dim transformedValue As Double = 0.0 'Accept and 
                        '  don't punish missing points...

                        'Changed PM_IDENTICALZERO_IN_SCORING 2008-11-30
                        'We don't punish a few identical zero points in a 
                        'profile.
                        If Not identicalZero Then
                            Dim consensusValues As statsStructure = _
                              mConsensus(dishZbased).profile(d)
                            Dim dummy As Double
                            Dim consensus As Double
                            consensusValues.average(dummy, consensus)

                            'Changed PM_CONSENSUSSCORE_LOGTRANSFORMED 2008-11-30
                            'Dim err As Double = consensus - yValue
                            'We now score in the transformed domain.
                            '
                            Dim transformedConsensusValue As Double = consensus
                            transformedValue = _
                              frmPCPplot.ratioTransform(yValue2)
                            Dim err As Double = _
                              transformedConsensusValue - transformedValue

                            'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                            If True Then
                                'Use some of the functions we use when
                                'exporting various absolute and relative
                                'errors?

                                Dim relErr As Double = err / consensus

                                'Changed PM_20PERCENT_CONSENSUS 2008-12-03. Was
                                '  10 percent...
                                If relErr < 0.2 Then '20 percent
                                    withinConsensus += 1
                                Else
                                    Dim peter2 As Integer = 2 'Outside
                                    '  consensus...
                                End If
                            End If

                            valuesForScore.update(0.0, err)

                            nonZeroPoints2 += 1
                        Else
                            zeroPoints += 1 'Identical zero!
                        End If

                        'Changed PM_CONSENSUSSCORE_NEW 2008-12-05
                        forMeasurementVector(0)(d) = transformedValue

                        d += 1
                    Next 'Through a profile for some dish.

                    Dim consensusScore As Double = 0.0
                    Dim squareErrors2 As Double = valuesForScore.sumOfSqY

                    If squareErrors2 > 0.0000001 Then 'This guard should
                        '  still be OK.

                        'Changed PM_CONSENSUSSCORE_NEW 2008-12-05
                        ''Changed PM_CONSENSUSSCORE_LINEAR 2008-12-01
                        ''consensusScore = 1.0 / valuesForScore.sumOfSqY
                        'Dim RMS As Double = Math.Sqrt(valuesForScore.sumOfSqY)
                        'consensusScore = 1.0 / RMS

                        Dim measurementVector As GeneralMatrix = _
                          New GeneralMatrix(forMeasurementVector)

                        Dim consensusDishInfo As _
                          frmProteinList.consensusDishInfoStruct = _
                            mConsensus(dishZbased)

                        Dim diff As GeneralMatrix = _
                          measurementVector.Subtract(consensusDishInfo.mean)

                        Dim diffTr As GeneralMatrix = diff.Transpose()

                        Dim tmp As GeneralMatrix = _
                          consensusDishInfo.invcov.Multiply(diffTr)

                        Dim cScore As GeneralMatrix = diff.Multiply(tmp)

                        Dim sqScore As Double = cScore.GetElement(0, 0)
                        consensusScore = Math.Sqrt(sqScore)
                    End If

                    'Changed PM_IDENTICALZERO_IN_SCORING 2008-11-30.
                    'Don't punish identical zeros - unless too manư.
                    If zeroPoints > nonZeroPoints2 Then
                        consensusScore = 0.0
                    End If

                    'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                    Dim cons As consensusScoreStruct
                    cons.consensusScore = consensusScore
                    cons.nonZeroPoints = nonZeroPoints2
                    cons.pointsWithInConsensus = withinConsensus 'Later

                    'Changed PM_EXTENDED_CONSENSUSSCORE 2008-11-28
                    'someProt.consensusScore2.Add(consensusScore)
                    someProt.consensusScore3.Add(cons)
                Next 'Through dishes.

                updateProtein(dataIndex, someProt)

                listIndex2 += 1
            Next 'Through proteins, PCP profiles for.
        End If


        ' Dim proteins As Integer = protein_datastructureIndices.Count
        ' If proteins > 0 Then
        '     Dim lastIndex4 As Integer = _
        '       protein_datastructureIndices.Count - 1
        '     Dim i As Integer
        '     For i = 0 To lastIndex4 'Through selected proteins
        '         Dim dataIndex As Integer = protein_datastructureIndices(i)
        '         Dim someProt As ProteinHitStructure = _
        '           mParsedProts2(dataIndex)
        ' 
        '     Next
        ' 
        ' End If
    End Sub 'mnuScoreConsensus_Click


    'Changed PM_COLUMNSORT_BY_KEYBOARD 2008-11-07
    '****************************************************************************
    '*    Common menu command handler for the sub items                         *
    '*    of View (that are setup dynamically).                                 *
    '****************************************************************************
    Private Sub arrangeProteinsMenuSubItemsOnClick( _
      ByVal aSender As Object, ByVal anEvent As EventArgs)

        'Will we be called before actual menu command
        'selection? E.g. during setup of the this window? Answer: apparently not.

        Dim someMenuItem As MenuItem = DirectCast(aSender, MenuItem)

        Dim columnSortID As Integer = CInt(someMenuItem.Tag)

        mListViewColumnSorter.prepareSortAndSort(columnSortID, lstProtHits)

        'Needed?
        'If Not mStartingUp Then
        'Else
        '    Dim peter2 As Integer = 2
        'End If
    End Sub 'arrangeProteinsMenuSubItemsOnClick()


    'Changed PM_PROTEIN_TAGS 2008-10-29
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuAddTag_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuAddTag.Click

        mTaggingForm = New frmTagging(mCurrentTags)
        mTaggingForm.Show()

        'Note: mTaggingForm_tagListDismissed() handles the event when the
        '      user OKs the dialog.
    End Sub 'mnuAddTag_Click


    'Changed PM_SAVE_RAWFILE_MAPPING_MB4 2008-11-18
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuDimensions_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuDimensions.Click

        mDimensionsDialog = New frmDimensions(mExperimentSettings.JAspace)
        mDimensionsDialog.Show()
    End Sub 'mnuDimensions_Click()


    'Changed PM_SAVE_RAWFILE_MAPPING_MB4 2008-11-18
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuRawFileMapping_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuRawFileMapping.Click

        'Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
        Dim exportTargetSettings As exportTargetSettingsStruct = _
          Me.getGlobalTargetSettings()

        mRawFileMappingDialog = _
          New frmRawFileMapping( _
            mExperimentSettings.JAspace.getVectorSet(), _
            mExperimentSettings.rawFileMapping3, _
            exportTargetSettings)
        mRawFileMappingDialog.Show()
    End Sub 'mnuRawFileMapping_Click()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '*    Call-back from dimensions form.                                       *
    '****************************************************************************
    Private Sub mDimensionsDialog_dialogDismissed( _
      ByVal aSender As Object, _
      ByVal anEvent As dimensionsEventArgs) _
      Handles mDimensionsDialog.dimensionsDismissed

        Dim newDimensions As List(Of CEBIdimension) = anEvent.getDimensions()

        'Changed PM_SHARED_DIMENSIONSETTINGS_BUG 2008-11-20
        'Dim JAspace2 As CEBIspaces = mExperimentSettings.JAspace
        Dim JAspace2 As CEBIspaces = New CEBIspaces() 'Replace existing (so
        '  we will not share it with the object we got passed in
        '  the constructor).

        JAspace2.setDimensionDefinitions(newDimensions)
        mExperimentSettings.JAspace = JAspace2 'Needed? Yes!
    End Sub 'mDimensionsDialog_dialogDismissed()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '*    Call-back from raw files mapping form.                                *
    '****************************************************************************
    Private Sub mRawFileMappingDialog_dialogDismissed( _
      ByVal aSender As Object, _
      ByVal anEvent As rawFileMappingEventArgs) _
      Handles mRawFileMappingDialog.rawFileMappingDismissed

        mExperimentSettings.rawFileMapping3 = anEvent.getMapping()
    End Sub 'mRawFileMappingDialog_dialogDismissed()


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    'Changed PM_QUANTIFY_FROMFILE 2003-03-13
    Private Sub doQuantExternal()

        OpenFileDialog1.Title = "Open list of peptides"
        OpenFileDialog1.Filter = "Text files (*.txt)|*.txt"
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

            'Use the first of the parsed proteins as a pseudo protein to
            'contain the peptides from the file.
            Dim pseudoProtein As ProteinHitStructure = _
              ProteinHitStructure.blankProtein() 'Keep compiler happy.

            pseudoProtein.description3 = "pseudo protein. Do not use at home."
            pseudoProtein.accNum = "gi|999999999999"
            pseudoProtein.monoIsotopicMass = 33333.333

            'Changed PM_REFACTOR_HOTSPOT 2006-03-16
            'pseudoProtein.pepts = New ArrayList(100)  this was not the right way...
            pseudoProtein.peptides = New PILpeptides(100) '100: capacity, not maximum...

            Dim fname As String = OpenFileDialog1.FileName
            'Dim theFile As FileStream = CType(OpenFileDialog1.OpenFile, System.IO.FileStream)
            Dim stream As FileStream = _
              New FileStream(fname, FileMode.Open, FileAccess.Read)
            Dim reader As StreamReader = New StreamReader(stream)

            Dim peptideCount As Integer = 0
            Dim stopNow As Boolean = False
            While Not stopNow
                Dim lineStr As String = reader.ReadLine()
                If lineStr Is Nothing Then
                    stopNow = True
                Else
                    Dim lineItems As String() = Split(lineStr, vbTab)
                    Dim numItems As Integer = lineItems.Length
                    If lineItems(0) = "PF" Then 'What about leading or
                        '  trailing spaces?
                        If numItems >= 7 Then 'We require at least
                            '  the fields up to and including charge.
                            peptideCount += 1

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

                            pept.queryNumber = peptideCount

                            'Changed PM_REFACTOR 2006-10-12. Not needed.
                            'pept.averageOf_IWT_Ratios = 4.444444
                            'pept.averageOf_HIWT_Ratios = 77.777777

                            pept.checkboxChecked = True
                            pept.MascotColour = _
                              mascotColourEnum.enumBoldRed

                            'Changed PM_EXTERNAL_QUANT_TROUBLE 2006-08-10
                            'Not 99, this will make it look like an inserted
                            'peptide and an assert will result in 
                            'pept.MascotScore = PILpeptides.FIXED_SCORE_FOR_INSERTED_PEPTIDES
                            pept.MascotScore2 = _
                              2.0 * PILpeptides.FIXED_SCORE_FOR_INSERTED_PEPTIDES2

                            ''Changed PM_MS3INTEGRATION 2004-06-15
                            'Changed PM_MASCOTSCORE_ASDOUBLE 2008-11-25. No
                            'longer implicit conversion from integer to
                            'double...
                            pept.MascotScorePlusMS3Score = pept.MascotScore2

                            pept.useForQuantitation = True
                            pept.verified = True

                            Dim seq As String = lineItems(1)
                            Dim mass As Double = CDbl(lineItems(2))
                            Dim retTstart As Double = CDbl(lineItems(4))
                            Dim retTend As Double = CDbl(lineItems(5))
                            Dim charge As Integer = CInt(lineItems(6))

                            'Not yet!
                            '  'Changed PM_PROTEIN_ACC_IN_IMPORT 2003-03-18
                            '  Dim proteinAcc As String = lineItems(7)
                            '  pseudoProtein.accNum = proteinAcc 'Overwrites for
                            '  '  every peptide. If needed use some code to avoid
                            '  '  the re-assignments.

                            Dim retCenterComputed As Double = _
                              (retTend + retTstart) / 2

                            pept.AASequence = seq
                            pept.measuredMCR = mass

                            'Changed PM_REFACTOR 2008-05-20
                            ''Changed PM_EXTERNAL_CALIB_MASSTRANSFORMATION_BUG 2006-03-21
                            ' ''Note: formula incorrect...
                            ''pept.MascotCalculatedMass = charge * pept.measuredMCR
                            ' ''  Could be set to mass based on sequence.
                            'pept.MascotCalculatedMass = _
                            '  charge * _
                            '  (pept.measuredMCR - MSconstants.PROTON_MASS)
                            pept.MascotCalculatedMass = _
                              PILmassCalc.chargeTransform( _
                                pept.measuredMCR, charge, 0)

                            If False Then
                                'Old: average specifies the MS/MS and the retention
                                '     time window is -30 secs and +90 secs.

                                pept.retentionTimeStartMinutes = _
                                  retCenterComputed / 60.0
                            Else
                                pept.retentionTimeStartMinutes = retTstart / 60.0
                                pept.retentionTimeEndMinutes = -retTend / 60.0
                                '  Negative value is a flag for actually using
                                '  both fields for the rentiotion time window,
                                '  retentionTimeStartMinutes and
                                '  retentionTimeEndMinutes.
                            End If

                            'Changed PM_IMPORT_TROUBLE 2003-03-26
                            Dim retMiddleMinutes As Double = _
                              0.5 * Math.Abs(pept.retentionTimeEndMinutes + _
                              pept.retentionTimeStartMinutes)
                            'Hopefully the middle point will be close to the actual LC peak.
                            pept.MSMSretentionTimeMinutes = retMiddleMinutes

                            pept.charge = charge

                            'Changed PM_EXTERNAL_QUANT_BROKEN 2003-12-02
                            pept.rawFileID = _
                              MultipleRawFilesHandling.getDefaultRawFileID()

                            'Changed PM_EXTERNAL_QUANT_TROUBLE 2006-08-10
                            pept.experimentNumber = 1 'Some value higher than 0,
                            '  otherwise we get an ASSERT later.
                            '  We have not identified a peptide from an MS-MS
                            '  spectrum, but we must set it anyway.
                            '  Should we adjust the passed retention time to hit
                            '  the nearest fragment spectrum??

                            'Changed PM_REFACTOR_HOTSPOT 2006-03-16
                            'pseudoProtein.pepts.Add(thePeptHitStru)
                            pseudoProtein.peptides.addPeptide(pept)
                        Else
                            'Emit some warning that a PF line is being ignored?
                        End If
                    Else
                        'Not a peptide line. Ignore it.
                    End If
                End If
            End While
            ParserStatus.Text = _
              "Read " & peptideCount & " peptides from file " & fname & "."

            Dim someProteinIndex2 As Integer = 0

            Dim oldProteinHitNumber As Integer = _
              mParsedProts2(someProteinIndex2).hitNumber
            pseudoProtein.hitNumber = oldProteinHitNumber

            mParsedProts2(someProteinIndex2) = pseudoProtein 'Put in
            '  pseudo protein. Replaces existing...

            Dim visualIndex As Integer = someProteinIndex2 'Same, as there
            '  is only one protein...

            'Changed PM_REFACTOR 2006-11-15
            'openProtValForm(visualIndex, True)
            Dim OKtoUse As Boolean = _
              openProtValForm3(True, someProteinIndex2, 0)

            'Changed PM_CMD_EMPTY_PROTEINS 2006-11-22
            'We don't expect empty protein (no peptides). But later it
            'should be handled as error handling and not an ASSERT.
            Trace.Assert(OKtoUse = True, "PIL ASSERT. Empty protein!")


            mCurrentFrmProtValidation.doUnattentedQuantitation(True)
            mParsedProts2(someProteinIndex2) = _
              mCurrentFrmProtValidation.getCurrentProtein_quant() 'write-back
        End If
    End Sub 'doQuantExternal


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    'Changed PM_QUANTIFY_FROMFILE 2003-03-13
    Private Sub mnuQuantExternal_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuQuantExternal.Click

        Try
            doQuantExternal()
        Catch exceptionObject As Exception
            displayStandardExceptionInfo( _
              exceptionObject, _
              "Could not quantify using the selected file. The file may have the correct format.")
            Exit Sub
        End Try
    End Sub 'mnuQuantExternal_Click


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


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

    End Sub 'mnuSelectExternal_Click()


    'Changed PM_SELECT_FROM_EXTERNAL 2008-12-09
    'Completely general. Could be somewhere else. Have we already
    'implemented something like this somewhere else?
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function nextLine( _
      ByRef anInStrBlob As String, _
      ByVal anInIndex As Integer, _
      ByRef anOutEndIndex As Integer) _
      As Boolean

        Dim toReturn As Boolean = False

        Dim len As Integer = anInStrBlob.Length

        If anInIndex >= len Then
            toReturn = True 'Corresponding to EOF
        Else
            Dim fIdx As Integer = _
              anInStrBlob.IndexOf(ControlChars.NewLine, anInIndex)
            If fIdx >= 0 Then

                anOutEndIndex = fIdx
            Else
                'Last item, not terminated by end of line.

                anOutEndIndex = len
            End If
        End If

        Return toReturn
    End Function 'nextLine()


    'Changed PM_REFACTOR 2008-12-12
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub selectProteinsFromAccList( _
      ByRef anInTextList As String, ByVal aExactMatch As Boolean)

        Dim accList As String = anInTextList 'Adaptation for now.

        Dim len As Integer = accList.Length
        Dim estimatedOutLen As Integer = len \ 13

        Dim selectList As List(Of String) = _
          New List(Of String)(estimatedOutLen)

        Dim startIndex As Integer = 0
        Dim endIndex As Integer = -999
        While Not nextLine(accList, startIndex, endIndex)

            'We could do it inline, but for now we build
            'a list - transform the input.

            Dim lineLength As Integer = endIndex - startIndex
            Dim curLine As String = _
              accList.Substring(startIndex, lineLength)
            selectList.Add(curLine)

            startIndex = endIndex + 2 '1: Jump over line end. This 
            '  assumes DOS line-end, not UNIX or MacIntosh.
        End While 'Through lines (usually protein accession numbers.)

        Dim inputLen As Integer = selectList.Count

        'For now: nxm comparisons.

        lstProtHits.BeginUpdate()

        'We need to iterate through the visual GUI as the elements
        'can be in any order as sorted by various coloums.

        Dim matchCount As Integer = 0

        Dim lastIndex As Integer = lstProtHits.Items.Count - 1
        Dim j As Integer
        For j = 0 To lastIndex

            Dim someGUIline As ListViewItem = lstProtHits.Items(j)
            '  Protein hit number.

            Dim proteinHitStr As String = someGUIline.Text

            Dim physicalIndex As Integer = _
              mColumnMapper.item2ColumnIndex( _
                proteinColumnEnum.enumProteinAccessionNumber)

            Dim accNum As String = someGUIline.SubItems(physicalIndex).Text

            Dim someLine As String
            For Each someLine In selectList

                'Partial matching in all protein's accession numbers.
                If accNum.IndexOf(someLine) >= 0 Then
                    'Match! Partial or exact.

                    Dim sameLength As Boolean = _
                      accNum.Length = someLine.Length

                    Dim match As Boolean = True

                    'Changed PM_REFACTOR 2008-12-12
                    'Dim useExactMatch As Boolean = True
                    'If useExactMatch Then
                    If aExactMatch Then
                        If Not sameLength Then
                            match = False
                        Else
                            Dim peter2 As Integer = 2
                        End If
                    End If

                    If match Then
                        someGUIline.Selected = True
                        matchCount += 1
                        Exit For
                    End If
                Else
                    Dim peter3 As Integer = 3
                End If
            Next 'Through selectList
        Next j 'Through visual protein lines.

        Dim inputStr As String = "(of " & inputLen & " in the input)."
        Dim msgStr As String = Nothing
        If matchCount > 0 Then
            msgStr = _
              matchCount & _
              " protein accession numbers matched and have been selected " & _
              inputStr
        Else
            msgStr = "No protein accession numbers matched ! " & inputStr
        End If
        MsgBox(msgStr)

        lstProtHits.EndUpdate()

        'Dim someProtein As ProteinHitStructure
        'For Each someProtein In mParsedProts2
        'Next 'Through mParsedProts2

    End Sub 'selectProteinsFromAccList()


    'Changed PM_SELECT_FROM_EXTERNAL 2008-12-09
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSelectExternal_Clipboard_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuSelectExternal_Clipboard.Click

        selectProteinsFromAccList(Clipboard.GetText(), True)
    End Sub 'mnuSelectExternal_Clipboard_Click()


    'Changed PM_SELECT_FROM_EXTERNAL 2008-12-12
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuSelectExternalPartialMatch_Clipboard_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuSelectExternalPartialMatch_Clipboard.Click

        selectProteinsFromAccList(Clipboard.GetText(), False)
    End Sub 'mnuSelectExternalPartialMatch_Clipboard_Click()


    '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 'frmProteinList


    

    

Generated by script codePublish.pl at 2009-01-05T15:20:59.