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_SUPERCHARGE 2003-11-03
'Imports Mascot_Parser.SDUPutility
Imports SDUPutility
Imports CEBI_generalGUI 'For ListViewColumnSorter
Imports massSpectrometryBase
Imports MolecularSharedStructures

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

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


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

    'Changed PM_REFACTOR 2004-02-04
    Private Enum proteinTbItmColEnum
        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
        enumProteinDescription

        'Changed PM_SEQUENCE_COVERAGE 2008-04-15
        enumSequenceCoverage

        'Changed PM_REFACTOR 2006-10-12
        ' 'Changed PM_PROTEINRATIO_DISPLAY 2004-02-04
        ' enumProteinAverageRatio
        ' enumProteinAverageRatioStDev
        ' 
        ' enumProteinAverageHigherRatio
        ' enumProteinAverageHigherRatioStDev
        ' 
        ' enumIsoRelError
        ' enumHigherRelError
        ' 
        ' 'eProteinAverageHigherRatio

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


        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.

    'Changed PM_REFACTOR 2007-10-24
    'Private mA As Double
    'Private mB As Double
    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

    Private mProteinHitNumberHash As Hashtable

    '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_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 mExportFiltersForm As frmExportFilters


#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 mnuTestMainForm 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 MenuItem9 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem10 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExportCorrelationReport As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSaveCorrelationReport 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 MenuItem12 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem15 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 mnuSaveRecalibReport 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 mnuSaveParseReport As System.Windows.Forms.MenuItem
    Friend WithEvents mnuExportParseReport As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem20 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 mnuTest2 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 MenuItem25 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuSaveRawFilesReport 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 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.MenuItem10 = New System.Windows.Forms.MenuItem
        Me.mnuRetrieveProteinSequences = New System.Windows.Forms.MenuItem
        Me.MenuItem26 = New System.Windows.Forms.MenuItem
        Me.mnuSaveParseReport = New System.Windows.Forms.MenuItem
        Me.mnuExportParseReport = New System.Windows.Forms.MenuItem
        Me.MenuItem12 = New System.Windows.Forms.MenuItem
        Me.mnuSaveRecalibReport = New System.Windows.Forms.MenuItem
        Me.mnuExportRecalibReport = New System.Windows.Forms.MenuItem
        Me.MenuItem15 = New System.Windows.Forms.MenuItem
        Me.mnuSaveCorrelationReport = New System.Windows.Forms.MenuItem
        Me.mnuExportCorrelationReport = New System.Windows.Forms.MenuItem
        Me.MenuItem25 = New System.Windows.Forms.MenuItem
        Me.mnuSaveRawFilesReport = New System.Windows.Forms.MenuItem
        Me.mnuExportRawFilesReport = New System.Windows.Forms.MenuItem
        Me.MenuItem20 = New System.Windows.Forms.MenuItem
        Me.mnuSaveProteinsAndPeptides = New System.Windows.Forms.MenuItem
        Me.mnuExportProteinsAndPeptides = New System.Windows.Forms.MenuItem
        Me.MenuItem2 = 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.mnuEditSelectAll = New System.Windows.Forms.MenuItem
        Me.mnuEditSelectChecked = 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.mnuWiffInfo = New System.Windows.Forms.MenuItem
        Me.mnuSearchStats = New System.Windows.Forms.MenuItem
        Me.mnuShowMascotResult = New System.Windows.Forms.MenuItem
        Me.mnuOptions = New System.Windows.Forms.MenuItem
        Me.mnuQuantOptions = 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.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.MenuItem9 = New System.Windows.Forms.MenuItem
        Me.mnuTestMainForm = New System.Windows.Forms.MenuItem
        Me.mnuTest2 = 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.MenuItem24 = 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.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.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.lstProtHits = New ListViewCEBIExtended4
        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)
        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.mnuAction, Me.mnuAutomation, 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.MenuItem10, Me.mnuRetrieveProteinSequences, Me.MenuItem26, Me.mnuSaveParseReport, Me.mnuExportParseReport, Me.MenuItem12, Me.mnuSaveRecalibReport, Me.mnuExportRecalibReport, Me.MenuItem15, Me.mnuSaveCorrelationReport, Me.mnuExportCorrelationReport, Me.MenuItem25, Me.mnuSaveRawFilesReport, Me.mnuExportRawFilesReport, Me.MenuItem20, Me.mnuSaveProteinsAndPeptides, Me.mnuExportProteinsAndPeptides, Me.MenuItem2, 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..."
        '
        'MenuItem10
        '
        Me.MenuItem10.Index = 4
        Me.MenuItem10.Text = "-"
        '
        'mnuRetrieveProteinSequences
        '
        Me.mnuRetrieveProteinSequences.Enabled = False
        Me.mnuRetrieveProteinSequences.Index = 5
        Me.mnuRetrieveProteinSequences.Text = "Retrieve protein sequences from Mascot server..."
        '
        'MenuItem26
        '
        Me.MenuItem26.Index = 6
        Me.MenuItem26.Text = "-"
        '
        'mnuSaveParseReport
        '
        Me.mnuSaveParseReport.Index = 7
        Me.mnuSaveParseReport.Text = "Parsing Result (save)..."
        '
        'mnuExportParseReport
        '
        Me.mnuExportParseReport.Index = 8
        Me.mnuExportParseReport.Text = "Parsing Result (export)"
        '
        'MenuItem12
        '
        Me.MenuItem12.Index = 9
        Me.MenuItem12.Text = "-"
        '
        'mnuSaveRecalibReport
        '
        Me.mnuSaveRecalibReport.Index = 10
        Me.mnuSaveRecalibReport.Text = "Recalibration Result (save)"
        '
        'mnuExportRecalibReport
        '
        Me.mnuExportRecalibReport.Index = 11
        Me.mnuExportRecalibReport.Text = "Recalibration Result (export)"
        '
        'MenuItem15
        '
        Me.MenuItem15.Index = 12
        Me.MenuItem15.Text = "-"
        '
        'mnuSaveCorrelationReport
        '
        Me.mnuSaveCorrelationReport.Index = 13
        Me.mnuSaveCorrelationReport.Text = "Correlation of Raw Files Result (save)..."
        '
        'mnuExportCorrelationReport
        '
        Me.mnuExportCorrelationReport.Index = 14
        Me.mnuExportCorrelationReport.Text = "Correlation of Raw Files Result (export)"
        '
        'MenuItem25
        '
        Me.MenuItem25.Index = 15
        Me.MenuItem25.Text = "-"
        '
        'mnuSaveRawFilesReport
        '
        Me.mnuSaveRawFilesReport.Index = 16
        Me.mnuSaveRawFilesReport.Text = "Raw Files Information (save)..."
        '
        'mnuExportRawFilesReport
        '
        Me.mnuExportRawFilesReport.Index = 17
        Me.mnuExportRawFilesReport.Text = "Raw Files Information (export)"
        '
        'MenuItem20
        '
        Me.MenuItem20.Index = 18
        Me.MenuItem20.Text = "-"
        '
        'mnuSaveProteinsAndPeptides
        '
        Me.mnuSaveProteinsAndPeptides.Enabled = False
        Me.mnuSaveProteinsAndPeptides.Index = 19
        Me.mnuSaveProteinsAndPeptides.Shortcut = System.Windows.Forms.Shortcut.CtrlF2
        Me.mnuSaveProteinsAndPeptides.Text = "Proteins and Peptides Information (&save)..."
        '
        'mnuExportProteinsAndPeptides
        '
        Me.mnuExportProteinsAndPeptides.Enabled = False
        Me.mnuExportProteinsAndPeptides.Index = 20
        Me.mnuExportProteinsAndPeptides.Shortcut = System.Windows.Forms.Shortcut.F2
        Me.mnuExportProteinsAndPeptides.Text = "Proteins and Peptides Information (&export)..."
        '
        'MenuItem2
        '
        Me.MenuItem2.Index = 21
        Me.MenuItem2.Text = "-"
        Me.MenuItem2.Visible = False
        '
        'mnuClose
        '
        Me.mnuClose.Index = 22
        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.mnuEditSelectAll, Me.mnuEditSelectChecked, 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 = "-"
        '
        'mnuEditSelectAll
        '
        Me.mnuEditSelectAll.Index = 6
        Me.mnuEditSelectAll.Shortcut = System.Windows.Forms.Shortcut.CtrlA
        Me.mnuEditSelectAll.Text = "Select All"
        '
        'mnuEditSelectChecked
        '
        Me.mnuEditSelectChecked.Index = 7
        Me.mnuEditSelectChecked.Shortcut = System.Windows.Forms.Shortcut.CtrlE
        Me.mnuEditSelectChecked.Text = "Select Checked"
        '
        'mnuEditInvertSelection
        '
        Me.mnuEditInvertSelection.Index = 8
        Me.mnuEditInvertSelection.Text = "Invert Selection"
        '
        'MenuItem17
        '
        Me.MenuItem17.Index = 9
        Me.MenuItem17.Text = "-"
        '
        'mnuScrollToNextSelected
        '
        Me.mnuScrollToNextSelected.Index = 10
        Me.mnuScrollToNextSelected.Shortcut = System.Windows.Forms.Shortcut.F3
        Me.mnuScrollToNextSelected.Text = "Scroll to Next Selected"
        '
        'MenuItem16
        '
        Me.MenuItem16.Index = 11
        Me.MenuItem16.Text = "-"
        '
        'mnuFind
        '
        Me.mnuFind.Index = 12
        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.mnuWiffInfo, Me.mnuSearchStats, Me.mnuShowMascotResult, Me.mnuOptions, Me.mnuQuantOptions, Me.mnuSample})
        Me.mnuView.Text = "&View"
        '
        'mnuWiffInfo
        '
        Me.mnuWiffInfo.Enabled = False
        Me.mnuWiffInfo.Index = 0
        Me.mnuWiffInfo.Text = "Wiff file info"
        Me.mnuWiffInfo.Visible = False
        '
        'mnuSearchStats
        '
        Me.mnuSearchStats.Enabled = False
        Me.mnuSearchStats.Index = 1
        Me.mnuSearchStats.Text = "Search stats"
        Me.mnuSearchStats.Visible = False
        '
        'mnuShowMascotResult
        '
        Me.mnuShowMascotResult.Enabled = False
        Me.mnuShowMascotResult.Index = 2
        Me.mnuShowMascotResult.Text = "Show Mascot Search Result"
        '
        'mnuOptions
        '
        Me.mnuOptions.Enabled = False
        Me.mnuOptions.Index = 3
        Me.mnuOptions.Text = "Options..."
        Me.mnuOptions.Visible = False
        '
        'mnuQuantOptions
        '
        Me.mnuQuantOptions.Enabled = False
        Me.mnuQuantOptions.Index = 4
        Me.mnuQuantOptions.Text = "Quant Options..."
        Me.mnuQuantOptions.Visible = False
        '
        'mnuSample
        '
        Me.mnuSample.Index = 5
        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"
        '
        'mnuAction
        '
        Me.mnuAction.Index = 3
        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.MenuItem9, Me.mnuTestMainForm, Me.mnuTest2})
        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"
        '
        'MenuItem9
        '
        Me.MenuItem9.Index = 8
        Me.MenuItem9.Text = "-"
        Me.MenuItem9.Visible = False
        '
        'mnuTestMainForm
        '
        Me.mnuTestMainForm.Index = 9
        Me.mnuTestMainForm.Text = "Test Main Form"
        Me.mnuTestMainForm.Visible = False
        '
        'mnuTest2
        '
        Me.mnuTest2.Index = 10
        Me.mnuTest2.Text = "Test2"
        '
        'mnuAutomation
        '
        Me.mnuAutomation.Index = 4
        Me.mnuAutomation.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuQuantOne, Me.mnuScoreMS3, Me.mnuScorePTM, Me.MenuItem24, Me.mnuComputeAndSetSequenceCoverage, Me.mnuReport, Me.mnuRecalibration, Me.mnuRecalibVisual, Me.MenuItem23, Me.mnuRetentionTimeCorrelation, Me.mnuRemoveInsertedPeptides, Me.MenuItem19, Me.mnuZapQuantSpecResults, Me.mnuRemovePeptides, Me.MenuItem13, Me.mnuQuantChecked, Me.mnuMS3ScoreChecked, Me.MenuItem14, Me.mnuQuantExternal})
        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 MS3"
        '
        'mnuScorePTM
        '
        Me.mnuScorePTM.Enabled = False
        Me.mnuScorePTM.Index = 2
        Me.mnuScorePTM.Shortcut = System.Windows.Forms.Shortcut.CtrlF9
        Me.mnuScorePTM.Text = "Score &PTM - broader"
        '
        'MenuItem24
        '
        Me.MenuItem24.Index = 3
        Me.MenuItem24.Text = "-"
        '
        'mnuComputeAndSetSequenceCoverage
        '
        Me.mnuComputeAndSetSequenceCoverage.Enabled = False
        Me.mnuComputeAndSetSequenceCoverage.Index = 4
        Me.mnuComputeAndSetSequenceCoverage.Text = "Compute and Set Protein Sequence Coverage"
        '
        'mnuReport
        '
        Me.mnuReport.Enabled = False
        Me.mnuReport.Index = 5
        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 = 6
        Me.mnuRecalibration.Text = "&Recalibration and validation"
        '
        'mnuRecalibVisual
        '
        Me.mnuRecalibVisual.Enabled = False
        Me.mnuRecalibVisual.Index = 7
        Me.mnuRecalibVisual.Text = "Recalibration Visualisation..."
        '
        'MenuItem23
        '
        Me.MenuItem23.Index = 8
        Me.MenuItem23.Text = "-"
        '
        'mnuRetentionTimeCorrelation
        '
        Me.mnuRetentionTimeCorrelation.Enabled = False
        Me.mnuRetentionTimeCorrelation.Index = 9
        Me.mnuRetentionTimeCorrelation.Text = "Do Retention Time Correlation"
        '
        'mnuRemoveInsertedPeptides
        '
        Me.mnuRemoveInsertedPeptides.Enabled = False
        Me.mnuRemoveInsertedPeptides.Index = 10
        Me.mnuRemoveInsertedPeptides.Text = "Remove Peptides Inserted by Retention Time Correlation"
        '
        'MenuItem19
        '
        Me.MenuItem19.Index = 11
        Me.MenuItem19.Text = "-"
        '
        'mnuZapQuantSpecResults
        '
        Me.mnuZapQuantSpecResults.Enabled = False
        Me.mnuZapQuantSpecResults.Index = 12
        Me.mnuZapQuantSpecResults.Text = "Zap intermediate quantitation results"
        '
        'mnuRemovePeptides
        '
        Me.mnuRemovePeptides.Enabled = False
        Me.mnuRemovePeptides.Index = 13
        Me.mnuRemovePeptides.Text = "Remove Peptides for &Good"
        '
        'MenuItem13
        '
        Me.MenuItem13.Index = 14
        Me.MenuItem13.Text = "-"
        '
        'mnuQuantChecked
        '
        Me.mnuQuantChecked.Index = 15
        Me.mnuQuantChecked.Shortcut = System.Windows.Forms.Shortcut.CtrlF10
        Me.mnuQuantChecked.Text = "Quantitate &checked"
        Me.mnuQuantChecked.Visible = False
        '
        'mnuMS3ScoreChecked
        '
        Me.mnuMS3ScoreChecked.Index = 16
        Me.mnuMS3ScoreChecked.Text = "MS&3 score checked"
        Me.mnuMS3ScoreChecked.Visible = False
        '
        'MenuItem14
        '
        Me.MenuItem14.Index = 17
        Me.MenuItem14.Text = "-"
        Me.MenuItem14.Visible = False
        '
        'mnuQuantExternal
        '
        Me.mnuQuantExternal.Index = 18
        Me.mnuQuantExternal.Text = "Quantify from external &list"
        '
        'MenuItem4
        '
        Me.MenuItem4.Index = 5
        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, 641)
        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, 624)
        Me.ProgressBar1.Name = "ProgressBar1"
        Me.ProgressBar1.Size = New System.Drawing.Size(1048, 15)
        Me.ProgressBar1.TabIndex = 8
        '
        '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, 624)
        Me.lstProtHits.TabIndex = 11
        Me.lstProtHits.UseCompatibleStateImageBehavior = False
        Me.lstProtHits.View = System.Windows.Forms.View.Details
        '
        '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"
        '
        'frmProteinList
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(1048, 665)
        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 aMasParsOptions As OptionsStruct2)

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

        MyBase.New()

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

        Dim shv As Boolean = True

        '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 MSQapp.vb/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 = aMasParsOptions 'This is needed because we are
        '  going to pass it on to frmProtValidation/frmProteinValidation.vb
        '  in openProtValForm().

        '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.

        mAvoidHandlingProteinCheckedEvent = False

        mProteinHitNumberHash = Nothing 'Lazy instantiation

        '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_TYPESAFE_HASH 2006-11-06
        mColumnSortSpecificationHash = New Dictionary( _
          Of Integer, List(Of sortKeyStructure))

        '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( _
                aMasParsOptions.quantModeCode)
            mDishes = _
              curQuantMode.dishes_StartingFromDish2.Count + 1
        End If
        setProteinListViewColumns(mDishes)

        'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-29. Now set globally,
        '  in defaultOptions(), file MSQapp.vb.
        ' '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

        Dim settings As miscSettingsStructure2Struct = _
          mApplication.getMiscSettings()
        If settings.option1 <> 1 Then
            mnuScorePTM.Visible = shv
        End If

        'Visual sorting.
        If True Then
            'Hit number.
            If True Then
                Dim keyList1 As List(Of sortKeyStructure) = _
                  New List(Of sortKeyStructure)

                'Should be unique. Only the primary key should be needed. Yes!
                keyList1.Add(New sortKeyStructure( _
                  proteinTbItmColEnum.enumProteinHitNumber, _
                  datatypeEnum.enumInteger, _
                  sortingDirectionEnum.enumAscendingSort))
                mColumnSortSpecificationHash.Add( _
                  proteinTbItmColEnum.enumProteinHitNumber, keyList1)
            End If

            'Accession number.
            If True Then
                Dim keyList1 As List(Of sortKeyStructure) = _
                  New List(Of sortKeyStructure)
                keyList1.Add(New sortKeyStructure( _
                  proteinTbItmColEnum.enumProteinAccessionNumber, _
                  datatypeEnum.enumText, _
                  sortingDirectionEnum.enumAscendingSort))

                'Should be unique. Only the primary key should be needed.

                mColumnSortSpecificationHash.Add( _
                  proteinTbItmColEnum.enumProteinAccessionNumber, keyList1)
            End If

            'Number of peptides.
            If True Then
                Dim keyList1 As List(Of sortKeyStructure) = _
                  New List(Of sortKeyStructure)

                keyList1.Add(New sortKeyStructure( _
                  proteinTbItmColEnum.enumNumberOfPeptides, _
                  datatypeEnum.enumInteger, _
                  sortingDirectionEnum.enumDescendingSort))

                keyList1.Add(New sortKeyStructure( _
                  proteinTbItmColEnum.enumProteinScore, _
                  datatypeEnum.enumDecimalNumber, _
                  sortingDirectionEnum.enumDescendingSort))

                keyList1.Add(New sortKeyStructure( _
                  proteinTbItmColEnum.enumProteinHitNumber, _
                  datatypeEnum.enumInteger, _
                  sortingDirectionEnum.enumAscendingSort))

                mColumnSortSpecificationHash.Add( _
                  proteinTbItmColEnum.enumNumberOfPeptides, keyList1)
            End If

            'Protein score.
            If True Then
                Dim keyList1 As List(Of sortKeyStructure) = _
                  New List(Of sortKeyStructure)

                keyList1.Add(New sortKeyStructure( _
                  proteinTbItmColEnum.enumProteinScore, _
                  datatypeEnum.enumDecimalNumber, _
                  sortingDirectionEnum.enumDescendingSort))

                keyList1.Add(New sortKeyStructure( _
                  proteinTbItmColEnum.enumNumberOfPeptides, _
                  datatypeEnum.enumInteger, _
                  sortingDirectionEnum.enumDescendingSort))

                keyList1.Add(New sortKeyStructure( _
                  proteinTbItmColEnum.enumProteinHitNumber, _
                  datatypeEnum.enumInteger, _
                  sortingDirectionEnum.enumAscendingSort))

                mColumnSortSpecificationHash.Add( _
                  proteinTbItmColEnum.enumProteinScore, keyList1)
            End If

            '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.
                For n = 0 To 2
                    Dim lastIndex As Integer = mDishes - 1
                    Dim dish As Integer
                    For dish = 0 To lastIndex
                        Select Case n
                            Case 0 'Ratio
                                keyBase = proteinTbItmColEnum.enumRatioBaseNumber3
                            Case 1 'Std. for ratio
                                keyBase = proteinTbItmColEnum.enumRatioStdDevBaseNumber3

                            Case 2 'Intensity
                                keyBase = proteinTbItmColEnum.enumRatioRelErrBaseNumber3
                            Case Else
                                Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
                        End Select

                        Dim key2 As Integer = keyBase + dish

                        If True Then 'Block, make sure keyList1 goes out of scope.
                            Dim keyList1 As List(Of sortKeyStructure) = _
                              New List(Of sortKeyStructure)

                            'Descending because most values are 0.0 and the interesting
                            'would end up at the end of the list.
                            keyList1.Add(New sortKeyStructure( _
                              key2, _
                              datatypeEnum.enumDecimalNumber, _
                              sortingDirectionEnum.enumDescendingSort))

                            'Secondary keys:
                            keyList1.Add(New sortKeyStructure( _
                              proteinTbItmColEnum.enumProteinHitNumber, _
                              datatypeEnum.enumInteger, _
                              sortingDirectionEnum.enumAscendingSort))
                            'Different secondary keys?

                            mColumnSortSpecificationHash.Add( _
                              key2, keyList1)
                        End If
                    Next 'dish
                Next n
            End If 'Block, quant columns.

            'Protein mass
            If True Then
                Dim keyList1 As List(Of sortKeyStructure) = _
                  New List(Of sortKeyStructure)

                keyList1.Add(New sortKeyStructure( _
                  proteinTbItmColEnum.enumProteinMass, datatypeEnum.enumDecimalNumber, _
                  sortingDirectionEnum.enumAscendingSort))

                keyList1.Add(New sortKeyStructure( _
                  proteinTbItmColEnum.enumProteinHitNumber, datatypeEnum.enumInteger, _
                  sortingDirectionEnum.enumAscendingSort))

                mColumnSortSpecificationHash.Add( _
                  proteinTbItmColEnum.enumProteinMass, keyList1)
            End If
        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_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 = _
          "MSQuant " & 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)

        lstProtHits.Columns.Clear()

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


        mColumnMapper.newColumn("Hit", 43, _
          proteinTbItmColEnum.enumProteinHitNumber, _
          numberAlignment)

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

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

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

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

        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.
            For n = 0 To 2
                Dim lastIndex As Integer = aSILACdishes - 1
                Dim dish As Integer
                For dish = 0 To lastIndex

                    Dim dishOneBased As Integer = dish + 1
                    Select Case n

                        'Perhaps later: dependent width (in pixels).
                        Case 0 'Ratio
                            quantityString = ""
                            quantityString2 = "/1"
                            keyBase = proteinTbItmColEnum.enumRatioBaseNumber3
                        Case 1 'Std. for ratio
                            quantityString = "StDev "
                            quantityString2 = "/1"
                            keyBase = proteinTbItmColEnum.enumRatioStdDevBaseNumber3

                        Case 2 'Intensity
                            quantityString = "Rel Err "
                            quantityString2 = " [%]"
                            keyBase = proteinTbItmColEnum.enumRatioRelErrBaseNumber3
                        Case Else
                            Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
                    End Select
                    Dim key2 As Integer = keyBase + dish
                    Dim header As String = _
                      quantityString & dishOneBased & quantityString2
                    mColumnMapper.newColumn(header, 40, key2, _
                    numberAlignment)
                Next dish
            Next 'Selector
        End If

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

        mColumnMapper.newColumn("Mass [kDa]", 68, _
          proteinTbItmColEnum.enumProteinMass, _
          numberAlignment)
    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 MSQuantCommon.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 anInLoadedDoc As MSQuantDocumentStructure, _
      ByRef anInPanelMessage As String)

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

        saveOffAssoc(aMascotWiffFileAss, aSampleNum)

        'Changed PM_TYPESAFE 2006-10-25
        'Dim loadedProteinsEtc As ArrayList
        Dim loadedProteinsEtc As List(Of ProteinHitStructure)

        Dim someResultStr As String = ""

        ' Changed PM_REFACTOR 2006-11-15
        ' Dim loadedDoc As MSQuantDocumentStructure
        ' loadedDoc.parsedProts2 = Nothing 'Keep compiler happy.
        ' loadedDoc.rawFiles = Nothing 'Keep compiler happy.
        ' 
        ' 'Changed PM_CODEMARKER 2006-10-31
        ' 'asads() 'Avoid this. Serialising multipleRawFiles object will
        ' ''  pull in a lot of other objects to be serialised.
        ' Dim succeeded As Boolean = _
        '   quantApplication.DeserialiseDocumentDataStructures( _
        '     OpenFileDialog1, someResultStr, loadedDoc)

        'Changed PM_SAVE_RECALIBRATION 2005-01-27
        loadedProteinsEtc = anInLoadedDoc.parsedProts3
        mRawFiles2 = anInLoadedDoc.rawFiles

        'Changed PM_FLEXIBLE_RAWFILE_LOC 2007-06-12
        buildRawFilesPathMap(anInLoadedDoc.rawFiles)

        '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).
        If True Then 'Block. Recalibration stuff.

            mRecalibrator = _
              New SDUPrecalibrator( _
                mOptions.recalibDomain, mOptions.recalibLimits)

            'Changed PM_PERFILE_RECALIBRATION 2007-11-16
            'For now. The real solution is to save calibration constants
            'for all raw files and for all. 
            '
            'Amongst other things to save is the recalib domain. Either per file
            '  or one value for all files and all.
            '
            'The loop below will be replaced by a loop through a data
            'structure built up during deserialisation.
            Dim lastIndex As Integer = anInLoadedDoc.rawFiles.Length() - 1
            Dim j As Integer
            For j = 0 To lastIndex
                Dim someRawFile As fileSpecStructure = anInLoadedDoc.rawFiles(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....
                'Changed PM_REFACTOR 2007-10-24
                'mA = anInLoadedDoc.recalibOffset
                'mB = anInLoadedDoc.recalibSlope
                mRecalibrator.setLinearCalibrationConstants( _
                  anInLoadedDoc.recalibSlope, _
                  anInLoadedDoc.recalibOffset, _
                  tagForRecalib) 'Note: 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...
            mRecalibrator.setLinearCalibrationConstants( _
              anInLoadedDoc.recalibSlope, _
              anInLoadedDoc.recalibOffset, _
              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( _
          loadedProteinsEtc, _
          False, _
          dummyPeptideFilter, _
          anInLoadedDoc.rawFiles, _
          mOptions.recalibDomain, _
          mOptions.recalibLimits)

        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, "MSQuant 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
                MsgBox("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. " & _
                  "MSQuant will probably not able to do any correlation between " & _
                  "the raw files.")
            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)

                    MsgBox("MSQuant 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 MSQuant, etc.")
                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, _
          mOptions.recalibDomain, _
          mOptions.recalibLimits)

        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, proteinTbItmColEnum.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 formatStrings() As String = {"0.00", "0.00", "0.0"} 'For ratio,
            '  stddev ratio, intensity and XIC - in that order....

            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.
            For n = 0 To 2 Step 1
                Dim dish As Integer
                For dish = 0 To lastIndex
                    Dim oneDishResult As oneDishResultStructure = _
                      aProt.quantResults3(dish)

                    Dim someItem As _
                      protSILACresultStructure = _
                        MSQuantCommon.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
                        Case 0 'Ratio
                            value = someItem.averageRatioToBase
                            keyBase = proteinTbItmColEnum.enumRatioBaseNumber3
                        Case 1 'Std. for ratio
                            value = someItem.stdDevAverageRatioToBase
                            keyBase = proteinTbItmColEnum.enumRatioStdDevBaseNumber3
                        Case 2 'Rel. err.
                            value = _
                              100.0 * _
                              someItem.stdDevAverageRatioToBase / _
                              someItem.averageRatioToBase
                            keyBase = proteinTbItmColEnum.enumRatioRelErrBaseNumber3
                        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(formatStrings(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, proteinTbItmColEnum.enumNumberOfPeptides, _
          pepCount2.ToString)

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

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

        mColumnMapper.updateListItem( _
          aRow, proteinTbItmColEnum.enumProteinAccessionNumber, _
          aProt.accNum.ToString)

        mColumnMapper.updateListItem( _
          aRow, proteinTbItmColEnum.enumProteinDescription, _
          aProt.description2.ToString)
    End Sub 'updateVisual_ProteinRow


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

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

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

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


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub setParsedProteinList( _
      ByVal aParsedProtList As List(Of ProteinHitStructure), _
      ByVal aDoRecalibrate As Boolean, _
      ByRef anInRecalibPeptideFilter As peptideFilterStructure, _
      ByRef anInRawFiles() As fileSpecStructure, _
      ByVal aRecalibDomain As SDUPrecalibrator.recalibDomainEnum, _
      ByVal aRecalibLimits As SDUPrecalibrator.recalibLimitsStructure)

        'Old:
        '  ByVal aParsedProtList As ArrayList
        '  ByVal aPeptideMaximumRelativeError_PPM As Double, _

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

        Dim recalibType As SDUPrecalibrator.recalibDomainEnum
        'Changed PM_DOMAINS_RECALIBRATION 2007-11-06
        ' 'Changed PM_DOMAINS_RECALIBRATION 2007-11-05
        ' 'For now:
        ' '  Hardcode recalib type to raw file type  
        ' Select Case mOptions.rawFileMode
        '     Case rawFileModeEnum.enumAnalyst
        '         recalibType = _
        '           SDUPrecalibrator.recalibDomainEnum.enumRecalibDomainMass
        ' 
        '     Case rawFileModeEnum.enumFinnegan
        '         recalibType = _
        '           SDUPrecalibrator.recalibDomainEnum.enumRecalibDomainFreq
        ' 
        '     Case rawFileModeEnum.enumMicromass
        '         recalibType = _
        '           SDUPrecalibrator.recalibDomainEnum.enumRecalibDomainMass
        ' 
        '     Case Else
        '         Trace.Assert(False, _
        '           "PIL ASSERT. Select Case never fall-through")
        ' End Select
        recalibType = aRecalibDomain

        If mRecalibrator Is Nothing Then
            mRecalibrator = _
              New SDUPrecalibrator(recalibType, aRecalibLimits) 'Note: if
            '  it is not fed data below then the client sets to the
            '  calibration constants after this function.
        End If

        mParsedProts2 = aParsedProtList
        mProteinHitNumberHash = New Hashtable

        '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).
            Me.recalibrateAndAdjustMassesAndValidation( _
              Nothing, _
              mParsedProts2, _
              anInRecalibPeptideFilter)
        Else
            'Changed PM_REFACTOR 2007-10-24. Default now in SDUPrecalibrator.
        End If

        lstProtHits.Items.Clear()

        '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)

        Dim parsProt As ProteinHitStructure

        Dim lastProteinIndex As Integer = mParsedProts2.Count - 1
        Dim i As Integer
        Dim visualIndex As Integer = 0
        For i = 0 To lastProteinIndex ' parsProt In mParsedProts
            parsProt = mParsedProts2(i)

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

                'Changed PM_PROTEINS_CHECK_SQL_PROBLEM 2003-08-04. Rule now moved
                'to "MascotResultParser.vb"/ParseOneProteinHitTable().
                ' If parsProt.scoreInABC >= mOptions.protDefaultValidation Then
                '     protItem.Checked = True
                ' End If

                'Changed PM_PROTEINCHECK_SQL 2003-08-15

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

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

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

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

                    'Changed PM_REFACTOR 2005-03-01
                    ''Changed PM_REFACTOR 2004-02-04
                    'Dim columns As Integer = mColumnProteinMap.Count
                    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(newItem, parsProt, 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
            mProteinHitNumberHash.Add(parsProt.hitNumber, i)
        Next

        If True Then
            'Changed PM_TYPESAFE_HASH 2006-11-06
            Dim keylist As List(Of sortKeyStructure) = _
              mColumnSortSpecificationHash( _
                proteinTbItmColEnum.enumProteinHitNumber)

            mListViewColumnSorter.prepareSort(keylist)

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

        lstProtHits.Refresh()

        'Changed PM_HIDE_RECALIBVISUALISATION_WINDOW 2008-01-06
        If mOptions.endOfParseAction.openRecalibrationVisualisationWindow Then
            'Changed PM_REFACTOR 2007-11-07
            Me.visualiseRecalibration(anInRawFiles)
        End If

    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)

        mCalibVisualForm = _
          New frmRecalibrationVisualisation( _
            Me, _
            Nothing, mParsedProts2, parsePeptideFilter, _
            mApplication, _
            mWiffFile.MascotFilePath, _
            anInRawFiles, _
            mRecalibrator)
        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
            '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 token As Integer = pepIter.getIterToken()

            Dim peptideCount As Integer = curProt2.peptides.peptideCount(token)
            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)
                Else
                    proteinValForm = mCurrentFrmProtValidation
                    proteinValForm.Init( _
                        curProt2, mWiffFile.rawFilePath, _
                        mWiffFileQuantStr, Me, _
                        mWiffFile, mOptions, _
                        aDataStructureIndex7, mRawFiles2, _
                        mApplication, mRawDataFileHandling, _
                        mRecalibrator, _
                        aDisplayQueryNumber)
                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

        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)

        '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

        Dim recalibStr As String = mRecalibrator.getRecalibMsgStr()
        mParseReport.AddItem2(1000, 0, recalibStr)

        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 aProteinListIndex 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(aProteinListIndex).accNum
        Trace.Assert( _
           origAcc = aProt.accNum, _
            "PIL ASSERT. Protein with accession number " & origAcc & _
            " is about to be overwritten...")

        mParsedProts2(aProteinListIndex) = 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(aProteinListIndex).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


    'Dead code. Delete at any time.
    ''****************************************************************************
    ''*    <placeholder for header>                                              *
    ''****************************************************************************
    'Private Sub mnuOpenProteinHits_Click(ByVal sender As System.Object, ByVal anEvent As System.EventArgs)

    '    Dim someResultStr As String = ""
    '    Dim loadedDoc As MSQuantDocumentStructure
    '    Dim succeeded As Boolean = _
    '      quantApplication.DeserialiseDocumentDataStructures( _
    '        OpenFileDialog1, someResultStr, loadedDoc)

    '    'Changed PM_SAVE_RECALIBRATION 2005-01-27
    '    mParsedProts = loadedDoc.parsedProts
    '    mRawFiles = loadedDoc.rawFiles
    '    mA = loadedDoc.recalibOffset
    '    mB = loadedDoc.recalibSlope

    '    ParserStatus.Text = someResultStr
    'End Sub 'mnuOpenProteinHits_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 = _
              helper.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.MascotScore >= 24 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


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

        Dim frmMain As New frmMainForm
        frmMain.Show()
    End Sub 'mnuTestMainForm_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 visualSelection3 As List(Of Integer) = _
              quantApplication.copySelectedIndices2(lstProtHits.SelectedIndices)

            '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 = visualSelection3.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 = visualSelection3(i)
                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


    '****************************************************************************
    '*    <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 = _
              helper.blankProtein() 'Keep compiler happy.

            pseudoProtein.description2 = "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 = _
                                helper.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.MascotScore = _
                              2 * PILpeptides.FIXED_SCORE_FOR_INSERTED_PEPTIDES

                            'Changed PM_MS3INTEGRATION 2004-06-15
                            pept.MascotScorePlusMS3Score = pept.MascotScore

                            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
            MSQuantCommon2.displayStandardExceptionInfo( _
              exceptionObject, _
              "Could not quantify using the selected file. The file may have the correct format.")
            Exit Sub
        End Try
    End Sub 'mnuQuantExternal_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?", "MSQuant", _
              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 proteinTbItmColEnum = _
          CType(mColumnMapper.columnIndex2itemID(physicalIndex), _
            proteinTbItmColEnum)

        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.
            Dim peter1 As Integer = 1
        End If
    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

        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

            '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.selectAllOrSome( _
          DirectCast(lstProtHits, ListView), False)

        '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


    '****************************************************************************
    '*    <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.selectAllOrSome( _
          DirectCast(lstProtHits, ListView), 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 anInVisualIndices As List(Of Integer)) _
      As List(Of Integer)
        'Old:
        '  ByRef anInVisualIndices As ArrayList
        '  As ArrayList

        Dim toReturn As List(Of Integer) = New List(Of Integer)

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

        Dim visualIndex4 As Integer
        For Each visualIndex4 In anInVisualIndices
            Dim dataStructureIndex4 As Integer = _
              Me.getProteinIndexFromVisualIndex(visualIndex4)
            toReturn.Add(dataStructureIndex4)
        Next

        Return toReturn
    End Function 'selectedIndices2DatastructureIndices2


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function exportProteinsAndPeptides_Common( _
      ByVal aInProteinAndPeptidesFilter2 As proteinAndPeptidesFilterStructure2) _
      As String

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

        Try
            Dim protein_visualIndices As List(Of Integer) = _
              quantApplication.copySelectedIndices2( _
                lstProtHits.SelectedIndices)
            selLen = protein_visualIndices.Count 'For debugging only, debugger
            '  problem with "Generic.".

            Dim datastructureIndices As List(Of Integer) = _
              Me.selectedIndices2DatastructureIndices2(protein_visualIndices)

            If datastructureIndices.Count > 0 Then
                toReturn = quantApplication.xxFormatTextPeptides2( _
                  aInProteinAndPeptidesFilter2, _
                  datastructureIndices, mParsedProts2, _
                  mRecalibrator, mOptions.quantModeCode, mApplication, _
                  mOptions, _
                  Nothing)
            End If

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

        Return toReturn
    End Function 'exportProteinsAndPeptides_Common


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub startExportOrSavePeptidesAndProteins(ByVal aType As tagEnum)

        'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-29
        'mProteinAndPeptidesFilter2.tag = aType
        Dim protPepFilter As proteinAndPeptidesFilterStructure2 = _
          mOptions.exportSettings
        protPepFilter.tag = aType

        Dim extraText As String = _
          "For " & lstProtHits.SelectedIndices.Count & " selected proteins."

        'Changed PM_DISPLAY_NUMBER_SELECTED 2006-12-30. New parameter,
        'number of selected proteins - to be displayed in the dialog.
        mExportFiltersForm = New frmExportFilters( _
          protPepFilter, _
          extraText, _
          mApplication, _
          mOptions.peptideFilters(peptideFilterEnum.enumExport2), _
          mRawFiles2)

        mExportFiltersForm.Show()
    End Sub 'startExportOrSavePeptidesAndProteins


    '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

        Me.startExportOrSavePeptidesAndProteins(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.startExportOrSavePeptidesAndProteins(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


    '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 mnuSaveRecalibReport_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuSaveRecalibReport.Click

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

            'Changed PM_SAVEDIALOG_TITLE 2005-12-01
            SaveFileDialog1.Title = "Saving recalibration report"

            'Use return value for some text reporting to GUI?
            Dim wasSaved As Boolean = _
              pushToUserSelectedFile2( _
                reportStr, "Saved recalibration report to file")

        End If
    End Sub 'mnuSaveRecalibReport_Click


    '****************************************************************************
    '*    <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
            PILInputOutput.pushToExcel(reportStr)
        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 visualSelection3 As List(Of Integer) = _
              quantApplication.copySelectedIndices2(lstProtHits.SelectedIndices)

            '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 = visualSelection3.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 = visualSelection3(i)
                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 visualSelection3 As List(Of Integer) = _
              quantApplication.copySelectedIndices2(lstProtHits.SelectedIndices)

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

                '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_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 visualSelection3 As List(Of Integer) = _
              quantApplication.copySelectedIndices2(lstProtHits.SelectedIndices)

            Dim lastVisualIndex3 As Integer = visualSelection3.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 = visualSelection3(i)
                Dim dataStructureIndex3 As Integer = _
                  Me.getProteinIndexFromVisualIndex(visualIndex3)

                Dim someProt As ProteinHitStructure = _
                  mParsedProts2(dataStructureIndex3)

                Dim dirty As Boolean = False

                Dim pept As PeptideHitStructure = _
                  helper.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 = _
          helper.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.MascotScore = 5
        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 visualSelection3 As List(Of Integer) = _
          quantApplication.copySelectedIndices2(lstProtHits.SelectedIndices)
        Dim lastVisualIndex3 As Integer = visualSelection3.Count - 1

        Dim i As Integer
        For i = 0 To lastVisualIndex3
            Dim visualIndex3 As Integer = visualSelection3(i)
            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 = _
                  helper.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?

                someEmptyPeptide.MascotScorePlusMS3Score = someEmptyPeptide.MascotScore
                someEmptyPeptide.version = 100 'Vers. 1.00.  With this change: redundancy...

                Dim peter2 As Integer = 2
            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 token As Integer = pepIter.getIterToken()

            Dim peptides As Integer = someProt.peptides.peptideCount(token)

            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 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(mProteinHitNumberHash.Count > 0, _
          "PIL ASSERT. mProteinHitNumberHash is empty!.")
        toReturn = CInt(mProteinHitNumberHash(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, _
            proteinTbItmColEnum.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.description2.ToUpper()
                Else
                    descr = parsProt.description2
                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
            MsgBox( _
              "Search string not found in " & consideredCount & _
              " considered proteins!", MsgBoxStyle.Exclamation, "MSQuant")
        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 mnuSaveCorrelationReport_Click( _
      ByVal aSender As System.Object, _
      ByVal anEvent As System.EventArgs) _
      Handles mnuSaveCorrelationReport.Click

        'Changed PM_SAVEDIALOG_TITLE 2005-12-01
        SaveFileDialog1.Title = "Saving correlation report"

        Dim reportStr As String = mMascotResultParser.getCorrelationReport()

        'Use return value for some text reporting to GUI?
        Dim wasSaved As Boolean = _
          pushToUserSelectedFile2(reportStr, "Saved correlation report to file")

    End Sub 'mnuSaveCorrelationReport_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()
        PILInputOutput.pushToExcel(reportStr)
    End Sub 'mnuExportCorrelationReport_Click


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

        Dim reportStr As String = mParseReport.getTabularReport()

        SaveFileDialog1.Title = "Saving parsing report"

        'Use return value for some text reporting to GUI?
        Dim wasSaved As Boolean = _
          pushToUserSelectedFile2(reportStr, "Saved parsing report to file")

    End Sub 'mnuSaveParseReport_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()
        PILInputOutput.pushToExcel(reportStr)
    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 visualSelection As List(Of Integer) = _
          quantApplication.copySelectedIndices2(lstProtHits.SelectedIndices)

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

            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
                PILInputOutput.pushToExcel(corrStr)
            Catch exceptionObject As Exception
                MSQuantCommon2.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 visualSelection As List(Of Integer) = _
              quantApplication.copySelectedIndices2(lstProtHits.SelectedIndices)

            Dim lastVisualIndex As Integer = visualSelection.Count - 1
            Dim i As Integer
            For i = 0 To lastVisualIndex
                Dim visualIndex As Integer = visualSelection(i)
                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) _
      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()
        SaveFileDialog1.Filter = "Binary file (*.mb3)|*.mb3"

        '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 anInDocToSave As MSQuantDocumentStructure, _
      ByRef anInBinFileName As String, _
      ByVal anInProteins As Integer)
        'If first parameter is Object then this function could 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

            'try/catch???

            BFormatter.Serialize(saveFile, 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 " & anInProteins & " protein hits to file. Time: " & _
          parseTimeSecs.ToString("0.00") & " seconds."
        PanelStatus.Text = msgStr
    End Sub 'saveAdoc


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

        'Changed PM_SAVE_RECALIBRATION 2005-01-27
        Dim docToSave As MSQuantDocumentStructure
        docToSave.parsedProts3 = mParsedProts2
        docToSave.rawFiles = mRawFiles2

        'Changed PM_REFACTOR 2007-10-30
        'docToSave.recalibOffset = mA
        'docToSave.recalibSlope = mB
        Dim slope As Double
        Dim offset As Double

        'Changed PM_PERFILE_RECALIBRATION 2007-11-16
        'Note: for now only one set, for all raw files...
        '      In the future we would call the function for each
        '      raw file and for all.
        Dim tag As Integer = SDUPrecalibrator.ALL_TAGCODE

        mRecalibrator.getLinearCalibrationConstants(slope, offset, tag)
        docToSave.recalibSlope = slope
        docToSave.recalibOffset = offset


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

        Return docToSave
    End Function 'defaultSaveFields


    'Moved it down here...
    'Changed PM_COMMANDLINE 2006-11-15
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Sub saveParseToBinFile(ByRef anInBinFileName As String)
        Dim docToSave As MSQuantDocumentStructure = Me.defaultSaveFields()
        Me.saveAdoc(docToSave, anInBinFileName, docToSave.parsedProts3.Count())
    End Sub 'saveParseToBinFile


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

        Dim saveFileName As String = Nothing

        'All proteins!
        If Me.dialogSave(saveFileName, mParsedProts2.Count(), True) Then
            Me.saveParseToBinFile(saveFileName)
        End If
    End Sub 'mnuSaveProteinHitsAs_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 visualSelection3 As List(Of Integer) = _
          quantApplication.copySelectedIndices2(lstProtHits.SelectedIndices)

        If visualSelection3.Count > 0 Then

            Dim saveFileName As String = Nothing
            If Me.dialogSave(saveFileName, visualSelection3.Count(), False) Then

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

                Dim docToSave As MSQuantDocumentStructure = Me.defaultSaveFields()

                Dim lastVisualIndex3 As Integer = visualSelection3.Count - 1
                Dim i As Integer
                For i = 0 To lastVisualIndex3
                    Dim visualIndex3 As Integer = visualSelection3(i)
                    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())
            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) _
      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.
        '
        'aSomeOpenFileDialog.Filter = "Binary files (*.bi9)|*.bi9"
        '  bs7
        '  bs8
        '  bs9
        '  mb1
        '  mb3: as from 2006-12-30
        '
        anInOpenFileDialog.Filter = "Binary files (*.mb3)|*.mb3"
        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 loadFileName As String = Nothing
        If frmProteinList.dialogLoad(OpenFileDialog1, loadFileName) Then

            Dim someMascotResultForm As frmProteinList = Nothing

            Dim msg As String = Nothing
            Dim loadedDoc As MSQuantDocumentStructure
            loadedDoc.parsedProts3 = Nothing 'Keep compiler happy.
            loadedDoc.rawFiles = Nothing 'Keep compiler happy.
            loadedDoc.mascotFileStr = Nothing 'Keep compiler happy.
            loadedDoc.rawFileStr = Nothing 'Keep compiler happy.

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

            If succeeded2 Then
                Dim listToAdd As List(Of ProteinHitStructure) = _
                  loadedDoc.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, _
                  mOptions.recalibDomain, _
                  mOptions.recalibLimits)
            End If
        End If
    End Sub 'mnuInsertProteins_Click


    'Changed PM_FAST_SERIALISATION 2006-12-15
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub mnuTest2_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuTest2.Click

        Debug.WriteLine("Menu command, Test2. Start.")

        'Me.saveParseToBinFile(saveFileName)

        mApplication.startStopWatch()

        Dim docToSave As MSQuantDocumentStructure = Me.defaultSaveFields()
        Me.saveAdoc(docToSave, "xyz", docToSave.parsedProts3.Count())

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

        Debug.WriteLine("Menu command, Test2. End.")
        Debug.WriteLine("")

        Dim msgStr As String = _
          "Saving took " & parseTimeSecs.ToString("0.00") & " secs. " & _
          "Mem diff: " & memDiff_MB.ToString("0.00") & " MB. "
        MsgBox(msgStr)
    End Sub 'mnuTest2_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 MSQfolderPath As String = MSQuantCommon2.appPath()
            'Dim baseDir As String = MSQfolderPath
            Dim baseDir As String = someFolder
            Me.initReport(baseDir)

            Dim firstTime As Boolean = True
            Dim visualSelection3 As List(Of Integer) = _
              quantApplication.copySelectedIndices2(lstProtHits.SelectedIndices)

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

                Dim visualIndex3 As Integer = visualSelection3(i)

                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 = MSQuantCommon2.timeAsHMS()
        Dim docBookMainFile As String = _
          baseDir & Path.DirectorySeparatorChar & _
          "MSQuantReport," & hms & ".xml"

        Dim MSQfolderPath As String = MSQuantCommon2.appPath()

        Dim MSQfolderPathAsURL As String = MSQfolderPath.Replace("\", "/")
        MSQfolderPathAsURL = MSQfolderPathAsURL.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:///" & MSQfolderPathAsURL & "/" & _
          "docBook" & "/" & "docbookx.dtd"
        Dim someXMLwriter As XmlTextWriter = _
          MSQuantCommon2.newStandardXMLout( _
            docBookMainFile, _
            "book", _
            DTDpath, _
            quantApplication.versionString_withDate())

        Dim currentISOdate As String = MSQuantCommon2.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, _
              "MSQuant report for XYZ proteins and XYZ peptides.")

            someXMLwriter.WriteStartElement("author")

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

            someXMLwriter.WriteElementString( _
              "surname", Nothing, _
              "MSQuant, vx.x.x, 2007-xx-xx")

            someXMLwriter.WriteStartElement("affiliation")

            someXMLwriter.WriteStartElement("address")

            someXMLwriter.WriteElementString( _
              "email", Nothing, _
              "MSQuant@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, _
              "MSQuant/ Peter Mortensen")

            someXMLwriter.WriteEndElement() 'For copyright.

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

            someXMLwriter.WriteElementString( _
              "releaseinfo", Nothing, _
              "$Id: MSQuant report, v 1.0 " & currentISOdate & "MSQuant 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_visualIndices As List(Of Integer) = _
          quantApplication.copySelectedIndices2( _
            lstProtHits.SelectedIndices)

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

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

            '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)

            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 visualSelection3 As List(Of Integer) = _
              quantApplication.copySelectedIndices2(lstProtHits.SelectedIndices)

            Dim selected As Integer = visualSelection3.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)

            Me.recalibrateAndAdjustMassesAndValidation( _
              visualSelection3, _
              mParsedProts2, _
              recalibPeptideFilter)

            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 mnuSaveRawFilesReport_Click( _
      ByVal aSender As System.Object, ByVal anEvent As System.EventArgs) _
      Handles mnuSaveRawFilesReport.Click

        MsgBox("Sorry, not implemted yet")
    End Sub 'mnuSaveRawFilesReport_Click


    '****************************************************************************
    '*    <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)
        PILInputOutput.pushToExcel(reportStr)
    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 = _
                                      helper.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 MSQuant, " & _
                                          ". 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.sequence2 = 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
            MSQuantCommon2.displayStandardExceptionInfo( _
              exceptionObject, _
              "Could not open file " & aSaveFileNameFullPath)
            Exit Sub
        End Try
    End Sub 'parseExport2file


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Function createLookupHashForProteinSubset( _
          ByRef aProteinsSubset_visualIndices2 As List(Of Integer), _
          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_visualIndices2 Is Nothing
        Dim len As Integer
        If useAllProteins Then
            len = anInParsedProts.Count()
        Else
            len = aProteinsSubset_visualIndices2.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
                visualIndex3 = aProteinsSubset_visualIndices2(i)
                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 = _
                  helper.blankPeptide() 'Keep compiler happy.
                While Not pepIter.nextPeptide(pept)
                    Dim score As Double = pept.MascotScore

                    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

            mRetrieveProteinsParametersForm = _
              New frmRetrieveProteinsParameters( _
                params, mApplication, mRawFiles2)
            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 visualSelection3 As List(Of Integer) = _
          quantApplication.copySelectedIndices2(lstProtHits.SelectedIndices)

        '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( _
            visualSelection3, mParsedProts2, minimumMaxScore)

        'Dim selected As Integer = visualSelection3.Count()

        '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 MSQfolderPath As String = MSQuantCommon2.appPath()

            'Dim someDate As Date = Now()
            'Dim timeStr As String = _
            '  someDate.Hour & "h" & _
            '  someDate.Minute & "m" & _
            '  someDate.Second & "s" & _
            '  ""
            '
            'Dim saveFileName2 As String = _
            '  "_temp" & "_" & timeStr
            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 = _
              MSQfolderPath & 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
                    MSQuantCommon2.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 = _
                      MSQfolderPath & 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 'mFilterForm_pepFilterDismissed


    'Changed PM_SEQUENCE_COVERAGE 2008-04-15
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub computeAndSetSequenceCoverage()

        Dim visualSelection3 As List(Of Integer) = _
          quantApplication.copySelectedIndices2(lstProtHits.SelectedIndices)

        Dim lastVisualIndex3 As Integer = visualSelection3.Count - 1

        Dim i As Integer
        For i = 0 To lastVisualIndex3

            Dim visualIndex3 As Integer = visualSelection3(i)
            Dim dataStructureIndex3 As Integer = _
              Me.getProteinIndexFromVisualIndex(visualIndex3)

            Dim someProt As ProteinHitStructure = _
              mParsedProts2(dataStructureIndex3)

            Dim seqLen As Integer = 0
            If Not someProt.sequence2 Is Nothing Then
                seqLen = someProt.sequence2.Length()
            End If

            If seqLen > 0 Then
                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

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

                Dim pepIter As peptideListIterator = _
                  New peptideListIterator(someProt.peptides)
                While Not pepIter.nextPeptide(pept)
                    If pept.verified Then
                        dirty = True

                        Dim j As Integer
                        For j = pept.startPositionInProtein To _
                                pept.endPositionInProtein
                            Dim zeroBased As Integer = j - 1

                            hitMap(zeroBased) += 1
                        Next j
                    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
    End Sub 'computeSequenceCoverage


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub frmProteinList_Load( _
      ByVal sender As Object, _
      ByVal e 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


    'Changed PM_GENERALISED_EXPORT 2005-03-08
    'Is called when the dialog ends..........
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Private Sub setProteinAndPeptidesFilter_export2( _
      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.exportSettings = 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
                PILInputOutput.pushToExcel( _
                  Me.exportProteinsAndPeptides_Common( _
                    aInProteinAndPeptidesFilter2))

            Case tagEnum.enumTag2

                '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_Common( _
                    aInProteinAndPeptidesFilter2), _
                    "Saved some peptides to file")
            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_export


    '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 mExportFiltersForm_dialogDismissed( _
      ByVal aSender As Object, _
      ByVal anEvent As exportFilterEventArgs) _
      Handles mExportFiltersForm.exportFilterDismissed

        Dim newValues As exportFilterValuesStructure = anEvent.getFilter()

        Me.setProteinAndPeptidesFilter_export2( _
          newValues.proteinAndPeptidesFilter, newValues.peptideFilter)
    End Sub 'mExportFiltersForm_dialogDismissed


    '****************************************************************************
    '*    <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


End Class 'frmProteinList


    

    

Generated by script codePublish.pl at 2008-09-23T11:59:18.