Source code for MSQuant: MSQapp.vb, MSQuant/msquant/src/main/MSQapp.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: Represents the non-GUI global parts of MSQuant.                 *
'*          Holds Class quantApplication, see below for                     *
'*          documentation.                                                  *
'*                                                                          *
'****************************************************************************

'****************************************************************************
'*                               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:   MPapp.vb                                                  *
'*    TYPE:  VISUAL_BASIC                                                   *
'*                                                                          *
'* CREATED: PM 2003-11-29   Vrs 1.0.                                        *
'* UPDATED: PM 2003-xx-xx                                                   *
'*                                                                          *
'****************************************************************************

Option Strict On
Option Explicit On 

'Imports System.Text.RegularExpressions 'For Regex

Imports System.Runtime.Serialization 'For StreamingContext
Imports System.IO 'For FileStream

Imports System.Text  'For StringBuilder

'Needed?
'Imports System.Reflection '[Assembly]

'Changed PM_QUANTMODES_VERSIONING 2004-02-17
Imports System.Xml 'For XmlNodeList

Imports System.Collections.Generic 'For Dictionary and List.


'Note: this will only work if a reference is added manually
'      in Visual Studio: menu Project/Add Reference/
'      System.Runtime.Serialization.Formatters.soap/Select/OK.
Imports System.Runtime.Serialization.Formatters.soap

'Changed PM_REFACTOR 2004-09-07
Imports System.Runtime.Serialization.Formatters.Binary 'For BinaryFormatter


'Changed PM_SPECTRUMDISPLAY_ZEDGRAPH 2007-09-19
Imports ZedGraph


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

'Changed PM_PERSIST_OPTIONS 2003-04-14
'Imports System.Runtime.Serialization

Imports massSpectrometryBase
Imports massSpectrometryBase.quantitation

Imports MolecularSharedStructures

Imports SDUPutility 'For PILInputOutput.pushToFile


Imports SDUPrecalibrator 'For recalibDomainEnum.


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


Namespace MSQuant 'Name space for things specific to MSQuant.
    'And they must be non-GUI.

    'Changed PM_REFACTOR 2004-06-03
    'Changed PM_QUANT_ORDER 2004-01-18
    Public Structure visibleAndPeptideTableIndexStruct
        Dim visibleIndex As Integer

        'Changed PM_REFACTOR 2006-03-15
        'Dim pepIndex As Integer
        Dim peptToken As Integer

        Dim fileID As Integer
    End Structure 'visibleAndPeptideTableIndexStruct


    'Changed PM_COMMANDLINE 2006-11-15
    Public Structure automationInfoStructure
        Dim binPath As String

        Dim quantProteinsStart As Integer
        Dim quantProteinsEnd As Integer

        Dim PTMscoreProteinsStart As Integer
        Dim PTMscoreProteinsEnd As Integer

        Dim ms3scoreProteinsStart As Integer
        Dim ms3scoreProteinsEnd As Integer

        Dim maxPeptides As Integer
    End Structure 'automationInfoStructure


    'Changed PM_QUANT_ORDER 2004-01-18
    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Class SortByRawFileComparer
        Implements System.Collections.Generic.IComparer( _
          Of visibleAndPeptideTableIndexStruct)

        Function Compare( _
          ByVal aItem1 As visibleAndPeptideTableIndexStruct, _
          ByVal aItem2 As visibleAndPeptideTableIndexStruct) _
          As Integer _
          Implements _
            System.Collections.Generic.IComparer( _
              Of visibleAndPeptideTableIndexStruct).Compare

            Dim toReturn As Integer = 0
            If aItem1.fileID < aItem2.fileID Then
                toReturn = -1
            Else
                If aItem1.fileID > aItem2.fileID Then
                    toReturn = 1
                Else
                    'Same raw, use second key: visual index
                    If aItem1.visibleIndex < aItem2.visibleIndex Then
                        toReturn = -1
                    Else
                        If aItem1.visibleIndex > aItem2.visibleIndex Then
                            toReturn = 1
                        Else
                            'All keys equal....
                            Dim peter8 As Integer = 8
                        End If
                    End If
                End If
            End If
            Return toReturn
        End Function 'Compare
    End Class 'SortByRawFileComparer


    '2003-11-27: Experimental - and not currently used!
    'Class to store options in a way that does not have versioning problems
    'as with normal serialisation, e.g. store of OptionsStruct2.
    'Problem with this class: will drop unknown fields when writing back
    'to disk....
    '
    <Serializable()> _
    Public Class miscOptionsNoVersioningProblems
        Implements ISerializable

        Public nsize As Integer

        'Default constructor, miscOptionsNoVersioningProblems.
        Public Sub New()

        End Sub 'New

        'Deserialization constructor.
        Public Sub New( _
          ByVal info As SerializationInfo, _
          ByVal context As StreamingContext)

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

            'Size = CInt(info.GetValue("size", GetType(Integer)))
            'shape = CType(info.GetValue("shape", GetType(String)), [String])

            ''Allows MyClass2 to deserialize itself
            'someObject = New MyClass2(info, context)
        End Sub 'New


        'Serialization function.
        '****************************************************************************
        '*    For Class miscOptionsNoVersioningProblems                             *
        '****************************************************************************
        Public Sub GetObjectData( _
          ByVal info As SerializationInfo, ByVal context As StreamingContext) _
          Implements ISerializable.GetObjectData

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

            'info.AddValue("size", size2)
            'info.AddValue("shape", shape)

            ''Allows MyClass2 to serialize itself
            'someObject.GetObjectData(info, context)
        End Sub 'GetObjectData

    End Class 'miscOptionsNoVersioningProblems


    '****************************************************************************
    '*    <placeholder for header>                                              *
    '****************************************************************************
    Public Class quantApplication


        Const ERRMSGPREFIX1 As String = _
          "Command line parameter was not accepted."


        'Dim mNsManager As System.Xml.XmlNamespaceManager 'Implicit parameter for
        '  some of the load options functions.

        Private mMiscSettings As miscSettingsStructure2Struct

        Private mMiscSettingsNsManager As System.Xml.XmlNamespaceManager
        Private mMiscSettingsDOM As System.Xml.XmlDocument 'We have to save this
        '  after load time because we want to preserve any elements that
        '  we don't understand. These elements are then also saved when e.g. a
        '  dialog is opened to change the settings and the dialog is closed.
        '
        'Future: use "owner-Document" in some of the functions where a node
        '        is available??
        Private mMiscOptionsFileName_FullPath As String

        'Changed PM_LOAD_OPTIONS_AGAIN 2003-12-12
        Private mOptions As OptionsStruct2
        Private mOptionsNsManager As System.Xml.XmlNamespaceManager
        Private mOptionsDOM As System.Xml.XmlDocument 'We have to save this
        Private mMSQOptionsFileName_FullPath As String

        'Changed PM_REFACTOR 2003-12-17
        Private mCorrSettings As correlationSettingsStructure
        Private mCorrelationSettingsNsManager As System.Xml.XmlNamespaceManager
        Private mCorrelationSettingsDOM As System.Xml.XmlDocument 'We have to save this
        Private mCorrelationSettingsFileName_FullPath As String

        Private mQuantitationModes As QuantitationModes
        Private mQuantitationModesNsManager As System.Xml.XmlNamespaceManager
        Private mQuantitationModesDOM As System.Xml.XmlDocument

        Private mQuantitationDefinitionsFileName As String

        Private mSpectrumClassifier As spectrumClassifier

        'Changed PM_WEAKLY_TYPED_SPECTRUMCLASSIFICATION 2006-02-15
        Private mSpectrumClassificationDefinitions As _
          spectrumClassificationDefinitionsStructure

        'Changed PM_EVENMORE_GENERALISED_QUANTMODES 2005-04-07
        Private mQuantitationModes_new As QuantitationModes_moreGeneral

        'Changed PM_FINNIGAN_QUANTWINDOW_RELATIVE 2005-07-12
        'For now it is sufficient to have only one instance in the program because 
        'only read the settings at program startup. Or in other words it is
        'at the moment not possible to have different settings for different
        'parses (of the same raw data type)
        Private mXICwindow As XICwindow

        'Changed PM_RETCORR_ANYTIME 2006-10-25
        Private mUniqueNumber As Integer

        'Changed PM_COMMANDLINE 2006-11-15
        Private mAutomationInfo As automationInfoStructure

        'Changed PM_COMMANDLINE 2006-11-15
        Private mQuantifiedPeptideCount As Integer

        'Changed PM_PARSESPEED_INTERNAL 2006-11-28
        Private mStopWatch_Ticks1 As Integer
        Private mStopWatch_Mem1 As Long

        Private mStopWatch_LastTimed As Double 'Save it so result
        '  can be read out at a later time.
        Private mStopWatch_LastMemDiff_MB As Double 'Save it so result
        '  can be read out at a later time.


        'Changed PM_GENERALISED_IONSERIES 2008-05-12
        Private mIonSeriesDefinitions As PILgeneralisedIonSeries


        'Changed PM_ION_SERIES_DISPLAYOPTION 2008-05-26
        Private mShowOnlyMatchedIons As Boolean



        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub New()
            mQuantitationModes = New QuantitationModes
            mSpectrumClassifier = Nothing 'Lazy instantiation
            mQuantitationModes_new = New QuantitationModes_moreGeneral
            mXICwindow = New XICwindow

            'Changed PM_RETCORR_ANYTIME 2006-10-25
            mUniqueNumber = -20000

            mAutomationInfo.binPath = "asda"
            mAutomationInfo.maxPeptides = 999999

            'Changed PM_CMD_MS3_AND_PTM 2006-11-27
            'mAutomationInfo.quantProteinsStart = 1
            'mAutomationInfo.quantProteinsEnd = 99999
            mAutomationInfo.quantProteinsStart = -1
            mAutomationInfo.quantProteinsEnd = -1

            mAutomationInfo.PTMscoreProteinsStart = -1
            mAutomationInfo.PTMscoreProteinsEnd = -1

            mAutomationInfo.ms3scoreProteinsStart = -1
            mAutomationInfo.ms3scoreProteinsEnd = -1

            mQuantifiedPeptideCount = 0

            'Changed PM_GENERALISED_IONSERIES 2008-05-12
            mIonSeriesDefinitions = Nothing 'Lazy instantiation.


            'Changed PM_ION_SERIES_DISPLAYOPTION 2008-05-26
            mShowOnlyMatchedIons = True 'Program default.


            If True Then
                'Changed PM_DEBUGTRACE 2006-12-19

                'Needed! Otherwise there will be no output - e.g.
                'using Debug.Writeline().
                Debug.Listeners.Add(New TextWriterTraceListener(Console.Out))

                Debug.AutoFlush = True

                Debug.WriteLine("")
                Debug.WriteLine("MSQuant started!!")
            End If
        End Sub 'New


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Shared Sub ratioAndStdHeaders( _
          ByVal aDishes As Integer, ByRef anInOutBuf As StringBuilder)

            'Changed PM_REFACTOR 2006-10-16
            ''Changed PM_CAP_HEADER 2005-12-13. i -> Iso, w -> Wild, etc. Are some
            ''scripts dependent on this?
            ''Old. Delete at any time.
            ''Dim proteinRatiosHeaders As String = _
            ''  "i/w" & vbTab & _
            ''  "StDev" & vbTab & _
            ''  "h/w" & vbTab & _
            ''  "StDev" & vbTab & _
            ''  ""
            'sbPR.Append("Iso/Wild")
            'sbPR.Append(vbTab)
            'sbPR.Append("StDev")
            'sbPR.Append(vbTab)
            'sbPR.Append("HigherIso/Wild")
            'sbPR.Append(vbTab)
            'sbPR.Append("StDev")
            'sbPR.Append(vbTab)
            Dim lastIndex As Integer = aDishes - 1
            Dim dish As Integer
            For dish = 0 To lastIndex Step 1
                anInOutBuf.Append(" ")
                anInOutBuf.Append(dish + 1)
                anInOutBuf.Append("/1")
                anInOutBuf.Append(vbTab)

                anInOutBuf.Append("StDev")
                anInOutBuf.Append(vbTab)
            Next dish
        End Sub 'ratioAndStdHeaders


        'Changed PM_REFACTOR 2003-10-29
        'Changed PM_REFACTOR 2003-04-16
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        '  This function is coupled to function NakedPeptideTable().
        '  Parameter aProt: const ref.
        '
        Public Shared Sub peptideTableHeaderWithAheader( _
          ByVal anExportHeader As String, ByVal anOpt1 As Integer, _
          ByRef anApp As quantApplication, _
          ByVal aQuantModeCode As Integer, _
          ByRef anInOutSB As System.Text.StringBuilder _
          )
            'Changed PM_REFACTOR 2007-03-22
            'Old: return type: String

            '"wild" -> "wild type" ?

            Dim dishes As Integer = anApp.getDishes(aQuantModeCode)

            'Dim shhv As Boolean = anOpt1 = 1
            Dim shhv As Boolean = True

            'Dim sb As StringBuilder = New StringBuilder(2700)

            If True Then

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


                anInOutSB.Append(anExportHeader)

                'Changed PM_REFACTOR 2008-05-05. Changed to more memory efficient version...
                'Dim sbTAB3 As StringBuilder = New StringBuilder(120)
                If True Then
                    'Changed PM_REFACTOR 2008-05-05. Changed to more memory efficient version...
                    'Dim sbPR As StringBuilder = New StringBuilder(48)

                    'Changed PM_STATISTICS_N 2007-01-11
                    anInOutSB.Append("Reserved - N")
                    anInOutSB.Append(vbTab)

                    'Changed PM_REFACTOR 2007-02-23. Outfactored
                    '  in order to be shared by generation of 
                    '  header for proteins.
                    quantApplication.ratioAndStdHeaders(dishes, anInOutSB)

                    'Dim len1 As Integer = sbPR.Length() 'For debugging only.

                    'Changed PM_REFACTOR 2008-05-05. Changed to more memory efficient version...
                    'sbTAB3.Append(sbPR)
                End If

                'Changed PM_EXPORT_HEADERS 2005-10-21. Where were the column
                '  headers empty??
                anInOutSB.Append("Accession number")
                anInOutSB.Append(vbTab)
                anInOutSB.Append("Mass [Da]")
                anInOutSB.Append(vbTab)
                anInOutSB.Append("Reserved")
                anInOutSB.Append(vbTab)
                anInOutSB.Append("Description")
                anInOutSB.Append(vbTab)
                'Old. Delete at any time.
                'Dim the3TABS As String = _
                '  proteinRatiosHeaders & _
                '  vbTab & vbTab & vbTab & vbTab

                'sb.Append(vbCrLf)
                'sb.Append(vbCrLf)

                'Changed PM_REFACTOR 2008-05-05. Changed to more memory efficient version...
                ''sb.Append(the3TABS)
                'sb.Append(sbTAB3)

                'Dim len2 As Integer = sbTAB3.Length() 'For debugging only.
            End If

            anInOutSB.Append("Sequence")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("MCR (Mass charge ratio) [Th]")
            anInOutSB.Append(vbTab)

            'Changed PM_UNIT_INEXPORT 2006-11-17
            'Note: some scripts match on "Measured".
            'sb.Append("Measured mass [Th]") 
            anInOutSB.Append("Measured mass [Da]")

            anInOutSB.Append(vbTab)
            anInOutSB.Append("Charge")
            anInOutSB.Append(vbTab)

            'Changed PM_CAP_HEADER 2005-12-13
            anInOutSB.Append("Score")
            anInOutSB.Append(vbTab)

            'Changed PM_CAP_HEADER 2005-12-13
            anInOutSB.Append("*** Intensity wild")
            anInOutSB.Append(vbTab)

            'Changed PM_CAP_HEADER 2005-12-13
            anInOutSB.Append("*** XIC wild [Da*secs]")
            anInOutSB.Append(vbTab)

            anInOutSB.Append("*** Ratio (of intensity sums)")
            anInOutSB.Append(vbTab)

            'Changed PM_CAP_HEADER 2005-12-13
            anInOutSB.Append("*** StDev")
            anInOutSB.Append(vbTab)

            anInOutSB.Append("LC centroid [secs]")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("LC peak width [secs]")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("LC, MS/MS event [secs]")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("LC peak detection centroid [secs]")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("LC max time [secs]")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("LC max intensity [sumCounts]")
            anInOutSB.Append(vbTab)

            'Changed PM_CAP_HEADER 2005-12-13
            anInOutSB.Append("Mascot calculated mass [Da]")
            anInOutSB.Append(vbTab)

            'Changed PM_CAP_HEADER 2005-12-13
            anInOutSB.Append("Calibrated measured MCR [Th]")
            anInOutSB.Append(vbTab)

            'Changed PM_CAP_HEADER 2005-12-13
            anInOutSB.Append("Calibrated measured mass [Da]")
            anInOutSB.Append(vbTab)

            'Changed PM_CAP_HEADER 2005-12-13
            anInOutSB.Append("Neutral MS centroid for LC max [Da]")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Bad peak")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Bad peak text")
            anInOutSB.Append(vbTab)

            anInOutSB.Append("Reserved") 'Changed PM_EXPORT_HEADERS 2005-10-21
            anInOutSB.Append(vbTab)

            'Changed PM_CAP_HEADER 2005-12-13
            anInOutSB.Append("*** High ratio") 'Change "High" to something else??
            anInOutSB.Append(vbTab)

            'Changed PM_CAP_HEADER 2005-12-13
            anInOutSB.Append("*** High StDev")
            anInOutSB.Append(vbTab)

            anInOutSB.Append("*** Ratios correlation")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Peptide rank")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Peptide delta score")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Result file")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Modifications")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Mascot protein hit number")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("*** Isotope intensity")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("*** Higher isotope intensity")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Raw file path")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Naked seq")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Max wild for checked")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Peptide mass, no mods [Da]")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Sequence with mods")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Uncalibrated MS centroid MCR [Th]")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Verified")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Calibrated MS centroid mass [Da]")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("*** Isotope XIC [Da*secs]")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("*** Higher isotope XIC [Da*secs]")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Score plus MS3 score")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("MS3 precursor sequence")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("*** Average of ratios")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Start retention time [secs]")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Spectrum number for MS-MS event")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Checked")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Query number")
            anInOutSB.Append(vbTab)

            If shhv Then
                anInOutSB.Append("PTM score")
            Else
                Dim peter88 As Integer = 88
            End If
            'Changed PM_PHOSPHO_SCORING 2005-09-08
            anInOutSB.Append(vbTab)

            'Changed PM_PRECURSOR_INTENSITY 2005-09-08
            anInOutSB.Append("Precursor intensity")
            anInOutSB.Append(vbTab)

            'Changed PM_OBSOLETED 2005-10-17.
            'anInOutSB.Append("Polydimethylsiloxysilane MCR, observed")
            'anInOutSB.Append(vbTab)

            'Changed PM_PHOSPHO_SCORING_EXPORT 2005-10-17
            If shhv Then
                anInOutSB.Append("PTM info")
            Else
                Dim peter87 As Integer = 87
            End If
            anInOutSB.Append(vbTab)

            'Extra column to make it easier to use Excel; PTM info will
            'not overflow to the right.
            anInOutSB.Append("SPACER")
            anInOutSB.Append(vbTab)

            'Changed PM_STANDARDS_COMPLIANCE 2005-10-20
            anInOutSB.Append("Left flanking AA")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("Right flanking AA")
            anInOutSB.Append(vbTab)

            'Changed PM_QS11_TROUBLE 2005-10-21
            anInOutSB.Append("Experiment number (QSTAR only)")
            anInOutSB.Append(vbTab)

            'Changed PM_EXPORT_INTERNAL 2005-10-21
            anInOutSB.Append("Internal index")
            anInOutSB.Append(vbTab)

            'Changed PM_EXPORT_DERIVED_MASS_ERRORS 2005-12-01
            If True Then
                anInOutSB.Append("Uncalibrated MCR error [Th]")
                anInOutSB.Append(vbTab)
                anInOutSB.Append("Uncalibrated MCR relative error [ppm]")
                anInOutSB.Append(vbTab)
                anInOutSB.Append("Absolute uncalibrated MCR relative error [ppm]")
                anInOutSB.Append(vbTab)

                anInOutSB.Append("Calibrated MCR error [Th]")
                anInOutSB.Append(vbTab)
                anInOutSB.Append("Calibrated MCR relative error [ppm]")
                anInOutSB.Append(vbTab)
                anInOutSB.Append("Absolute calibrated MCR relative error [ppm]")
                anInOutSB.Append(vbTab)

                anInOutSB.Append("Uncalibrated mass error [Da]")
                anInOutSB.Append(vbTab)
                anInOutSB.Append("Uncalibrated mass relative error [ppm]")
                anInOutSB.Append(vbTab)
                anInOutSB.Append("Absolute uncalibrated mass relative error [ppm]")
                anInOutSB.Append(vbTab)

                anInOutSB.Append("Calibrated mass error [Da]")
                anInOutSB.Append(vbTab)
                anInOutSB.Append("Calibrated mass relative error [ppm]")
                anInOutSB.Append(vbTab)
                anInOutSB.Append("Absolute calibrated mass relative error [ppm]")
                anInOutSB.Append(vbTab)
            End If

            'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-04
            If True Then
                If shhv Then
                    anInOutSB.Append("Checked PTM info")
                Else
                    Dim peter87 As Integer = 87
                End If
                anInOutSB.Append(vbTab)

                'Extra column to make it easier to use Excel; PTM info will
                'not overflow to the right.
                anInOutSB.Append("SPACER")
                anInOutSB.Append(vbTab)
            End If

            ' anInOutSB.Append("Raw file i/w ")
            ' anInOutSB.Append(vbTab)
            ' 
            ' anInOutSB.Append("Raw file i/w stdev")
            ' anInOutSB.Append(vbTab)
            ' 
            ' anInOutSB.Append("Raw file h/w ")
            ' anInOutSB.Append(vbTab)
            ' 
            ' anInOutSB.Append("Raw file h/w stdev")
            ' anInOutSB.Append(vbTab)
            If True Then

                'Changed PM_STATISTICS_N 2007-01-11
                anInOutSB.Append("Reserved - N")
                anInOutSB.Append(vbTab)

                Dim lastIndex2 As Integer = dishes - 1
                Dim dish2 As Integer
                For dish2 = 0 To lastIndex2 Step 1
                    anInOutSB.Append("Raw file ")
                    anInOutSB.Append(dish2 + 1)
                    anInOutSB.Append("/1")
                    anInOutSB.Append(vbTab)

                    anInOutSB.Append("Raw file ")
                    anInOutSB.Append(dish2 + 1)
                    anInOutSB.Append("/1 stdev")
                    anInOutSB.Append(vbTab)
                Next dish2
            End If

            anInOutSB.Append("Raw file, peptides")
            anInOutSB.Append(vbTab)

            anInOutSB.Append("Start position in protein")
            anInOutSB.Append(vbTab)

            anInOutSB.Append("End position in protein")
            anInOutSB.Append(vbTab)

            anInOutSB.Append("SPACER")
            anInOutSB.Append(vbTab)

            If True Then
                'Changed PM_STATISTICS_N 2007-01-11
                anInOutSB.Append("Reserved - N")
                anInOutSB.Append(vbTab)

                Dim lastIndex3 As Integer = dishes - 1
                Dim dish3 As Integer
                For dish3 = 0 To lastIndex3 Step 1
                    Dim dishOneBased As Integer = dish3 + 1

                    anInOutSB.Append(" ")
                    anInOutSB.Append(dishOneBased)
                    anInOutSB.Append("/1 (average of ratios)")
                    anInOutSB.Append(vbTab)

                    anInOutSB.Append("StDev")
                    anInOutSB.Append(vbTab)

                    anInOutSB.Append(" ")
                    anInOutSB.Append(dishOneBased)

                    'Changed PM_NO_RATIO_OF_INTENSITY_SUMS 2006-11-08
                    'anInOutSB.Append("/1 (of intensity sums)")
                    anInOutSB.Append("/1 (of XICs)")

                    anInOutSB.Append(vbTab)

                    anInOutSB.Append("XIC ")
                    anInOutSB.Append(dishOneBased)
                    anInOutSB.Append(" [Da*secs]")
                    anInOutSB.Append(vbTab)

                    anInOutSB.Append("Intensity ")
                    anInOutSB.Append(dishOneBased)
                    anInOutSB.Append(vbTab)
                Next dish3
            End If

            'Changed PM_EXPORT_USED_IN_PROTEINQUANT 2007-07-30
            anInOutSB.Append("Used in protein quantitation")
            anInOutSB.Append(vbTab)

            'Changed PM_EXPORT_PTMCOMBS 2007-08-03
            anInOutSB.Append("PTM combinations")
            anInOutSB.Append(vbTab)


            'Changed PM_EXPORT_RAWFILEID 2007-11-19
            anInOutSB.Append("Raw file ID")
            anInOutSB.Append(vbTab)

            'Changed PM_SEQUENCE_COVERAGE 2008-04-16
            anInOutSB.Append("Protein sequence coverage")
            anInOutSB.Append(vbTab)

            anInOutSB.Append(vbTab)
            anInOutSB.Append(vbTab)

            anInOutSB.Append(vbCrLf)


            'Dim len3 As Integer = sb.Length() 'For debugging only.

            'Changed PM_REFACTOR 2008-05-05. Changed to more memory efficient version...
            ''Changed PM_REFACTOR 2007-03-22
            ''Return sb.ToString
            'Return sb
        End Sub 'peptideTableHeaderWithAheader()


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Shared Sub addBooleanString( _
          ByVal aBoolValue As Boolean, ByRef anInOutBuf As StringBuilder)

            If aBoolValue Then
                anInOutBuf.Append("TRUE")
            Else
                anInOutBuf.Append("FALSE")
            End If
        End Sub 'addBooleanString


        'Changed PM_REFACTOR 2007-03-22. Convenience functions for
        '  clients that need to output a single peptide.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub addPeptideLine_simple( _
          ByRef anInPept As PeptideHitStructure, _
          ByRef aProt As ProteinHitStructure, _
          ByRef anApp As quantApplication, _
          ByVal aQuantModeCode As Integer, _
          ByRef anInOutSB As System.Text.StringBuilder _
        )

            Dim internalIndex As Integer = -1

            If anInOutSB Is Nothing Then
                anInOutSB = New StringBuilder(2000)
            End If

            Dim dishes As Integer = anApp.getDishes(aQuantModeCode)
            Dim protStr As String = _
              proteinInformation_PrefixForPeptideLine(aProt, dishes)
            Dim scratchSB As StringBuilder = New StringBuilder(500)
            Dim quantitationModesObject As QuantitationModes_moreGeneral = _
              anApp.getQuantModes()

            quantApplication.addPeptideLine( _
              anInPept, _
              aProt, _
              protStr, _
              internalIndex, _
              dishes, _
              anInOutSB, _
              scratchSB, _
              quantitationModesObject, _
              False)
        End Sub 'addPeptideLine_simple


        'Changed PM_REFACTOR 2003-11-21
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub createAndInitRawFileObject( _
          ByVal aRawFileType As rawFileModeEnum, _
          ByRef anInRawFiles() As massSpectrometryBase.fileSpecStructure, _
          ByRef aNewRawFileObject As massSpectrometryBase.rawDataFileHandling, _
          ByVal aSampleNumberInRawFile As Integer, _
          ByRef anInSpectrumClassifier As spectrumClassifier, _
          ByVal aCOMversion As COMversionEnum)

            'Changed PM_JA_FINNEGAN_ASSERT_RESOURCE_LEAK 2003-12-19
            If aNewRawFileObject Is Nothing Then
                Dim peter52 As Integer = 52
            Else
                'Assume it has already opened a file. Make it close it by sending
                'it a message. This is a sort of destructor that we, the
                'client, invoke explicitly.

                aNewRawFileObject.doCleanUp()
            End If

            Select Case aRawFileType
                Case rawFileModeEnum.enumAnalyst
                    aNewRawFileObject = _
                      New massSpectrometryBase.AnalystRawDataFileHandling( _
                        anInSpectrumClassifier, aCOMversion)
                Case rawFileModeEnum.enumFinnegan
                    aNewRawFileObject = _
                      New massSpectrometryBase.betterFinneganRawDataFileHandling( _
                        anInSpectrumClassifier, aCOMversion)
                Case rawFileModeEnum.enumMicromass
                    'Changed PM_MICROMASS_DISABLE 2004-03-17
                    'Changed JWG_MICROMASS_RE-ENABLE 2004-06-01

                    'Changed PM_MICROMASS_AGAIN 2005-10-06
                    'Changed PM_NO_MICROMASS 2005-09-15
                    'Changed PM_MICROMASS_UPDATE 2006-11-29

                    If True Then 'True: then uncomment...
                        aNewRawFileObject = _
                          New massSpectrometryBase.MicromassRawDataFileHandling( _
                            anInSpectrumClassifier, aCOMversion)
                    Else
                        Trace.Assert(False, _
                          "Stop!", _
                          "PIL ASSERT. Internal/development assert for stopping execution......")
                    End If

                Case Else
                    Trace.Assert( _
                      False, _
                      "PIL ASSERT. Select Case never fall-through. Unknown raw data file type!.")
            End Select

            'Changed PM_ASSERT_FOR_MICROMASS 2006-03-14
            '
            'Most likely to happen when the Micromass lines above have been
            'outcommented.
            Trace.Assert(Not aNewRawFileObject Is Nothing, _
              "PIL ASSERT. Object for raw file was not created. " & _
              "Could be a blunder in the Micromass creation part....")

            'Changed PM_IRINA_SAMPLE_NUMBER_TROUBLE 2003-12-02
            aNewRawFileObject.setSampleNumberInRawFile(aSampleNumberInRawFile)

            If True Then
                'Changed PM_SEVERALWIFFS 2003-08-26
                Dim len As Integer = anInRawFiles.Length()
                Trace.Assert(len > 0, "PIL ASSERT. No raw data files!.")
                Dim i As Integer
                For i = 0 To len - 1
                    Dim curFileSpec As massSpectrometryBase.fileSpecStructure = _
                      anInRawFiles(i)
                    aNewRawFileObject.AddRawFileRef(curFileSpec) 'Later: expect
                    '  it to throw an exeption for an empty specification.
                Next
                Dim firstFileSpec As massSpectrometryBase.fileSpecStructure = _
                  anInRawFiles(0)

                'Changed PM_MARKER_MEMORY_ALLOCATION 2004-07-28
                'newCurrentFile() can increase memory used by application by 15 MB!
                aNewRawFileObject.newCurrentFile(firstFileSpec.tag2)
            Else
                'Old
                'Dim fileSpec As massSpectrometryBase.fileSpecStruct
                'fileSpec.path = aWiffFileName
                'fileSpec.tag = 883
                'mRawDataFileHandling.AddRawFileRef(fileSpec) 'Later: expect it to
                ''  throw an exeption for an empty specification.
                'mRawDataFileHandling.newCurrentFile(883) 'For now: only one file
                '  at a time is handled.
            End If
        End Sub 'createAndInitRawFileObject


        'Changed PM_REMOVE_FINNEGAN_DEPENDENCY 2004-03-19
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub addSpectrumControl( _
          ByRef anInOutForm As System.Windows.Forms.Form, _
          ByRef anInFormWindowType As System.Type, _
          ByRef anOutSpectrumControl As Object, _
          ByRef anInSpectrumControlName As String, _
          ByVal aDisplayType As displayModeEnum, _
          ByVal aLocation As System.Drawing.Point, _
          ByVal aSize As System.Drawing.Size, _
          ByVal aCOMversion As COMversionEnum _
          )

            Select Case aDisplayType
                Case displayModeEnum.enumQS

                    'Dim resources2 As System.Resources.ResourceManager = _
                    '  New System.Resources.ResourceManager(anInFormWindowType)
                    '
                    'Changed PM_REFACTOR 2007-07-19
                    ' anOutSpectrumControl = New AxQS20_GraphControlLib.AxGraphControl
                    '
                    ' Dim AnalystControl As AxQS20_GraphControlLib.AxGraphControl = _
                    '   DirectCast(anOutSpectrumControl, _
                    '     AxQS20_GraphControlLib.AxGraphControl)
                    '
                    ' CType(AnalystControl, _
                    '   System.ComponentModel.ISupportInitialize).BeginInit()
                    ' AnalystControl.Enabled = True
                    ' AnalystControl.Location = aLocation
                    ' AnalystControl.Name = aSpectrumControlName
                    ' AnalystControl.OcxState = _
                    '   CType(resources2.GetObject( _
                    '     aSpectrumControlName & ".OcxState"), _
                    '   System.Windows.Forms.AxHost.State)
                    ' AnalystControl.Size = aSize
                    ' AnalystControl.TabIndex = 1

                    'Changed PM_COMVERSIONS 2007-07-24
                    'Dim analystControl As AnalystCOM = _
                    '  New QS20analystCOM() 'QS 2.0 for now.
                    Dim analystControl As AnalystCOM = _
                      DirectCast( _
                        rawDataFileHandling.newCOMobject(aCOMversion), _
                        AnalystCOM)

                    Dim winControl As System.Windows.Forms.Control = _
                      analystControl.axControl_setupControl( _
                        anInFormWindowType, True, aLocation, _
                        anInSpectrumControlName, aSize, 1)

                    anInOutForm.Controls.AddRange( _
                      New System.Windows.Forms.Control() {winControl})
                    CType(winControl, _
                      System.ComponentModel.ISupportInitialize).EndInit()

                    anOutSpectrumControl = analystControl

                Case displayModeEnum.enumXCalibur

                    Dim resources2 As System.Resources.ResourceManager = _
                      New System.Resources.ResourceManager(anInFormWindowType)

                    anOutSpectrumControl = New AxXSpecDisplay
                    Dim FinneganControl As AxXSpecDisplay = _
                      DirectCast(anOutSpectrumControl, AxXSpecDisplay)

                    CType(FinneganControl, _
                      System.ComponentModel.ISupportInitialize).BeginInit()
                    FinneganControl.Enabled = True
                    FinneganControl.Location = aLocation
                    FinneganControl.Name = anInSpectrumControlName

                    'Note: the following error can happen executing the line
                    '  below:
                    '    "unhandled exception of type System.resources.MissingManifestResourceException
                    '     occured in mscorlib.dll ... correctly embedded linked
                    '     assembly baseName"
                    '
                    'Reason: some class or structure is placed ***before*** the class
                    '        for a form. 
                    'Solution: place it either after or inside the form class.
                    FinneganControl.OcxState = _
                      CType(resources2.GetObject(anInSpectrumControlName & ".OcxState"), _
                      System.Windows.Forms.AxHost.State)

                    FinneganControl.Size = aSize
                    FinneganControl.TabIndex = 1
                    'FinneganControl.NoDataText = "No fuel left for Finnegan..."

                    anInOutForm.Controls.AddRange( _
                      New System.Windows.Forms.Control() {FinneganControl})
                    CType(FinneganControl, _
                      System.ComponentModel.ISupportInitialize).EndInit()

                    FinneganControl.NoDataText = "No fuel left for Finnegan..."

                Case displayModeEnum.enumZedGraph

                    ' Dim resources2 As System.Resources.ResourceManager = _
                    '   New System.Resources.ResourceManager(anInFormWindowType)
                    ' 
                    anOutSpectrumControl = New ZedGraphControl
                    Dim zedControl As ZedGraphControl = _
                      DirectCast(anOutSpectrumControl, ZedGraphControl)
                    ' 
                    ' CType(zedControl, _
                    '   System.ComponentModel.ISupportInitialize).BeginInit()
                    zedControl.Enabled = True
                    zedControl.Location = aLocation
                    zedControl.Name = anInSpectrumControlName
                    '
                    ' 'Note: the following error can happen executing the line
                    ' '  below:
                    ' '    "unhandled exception of type System.resources.MissingManifestResourceException
                    ' '     occured in mscorlib.dll ... correctly embedded linked
                    ' '     assembly baseName"
                    ' '
                    ' 'Reason: some class or structure is placed ***before*** the class
                    ' '        for a form. 
                    ' 'Solution: place it either after or inside the form class.
                    ' 
                    ' 'zedControl.OcxState = _
                    ' '  CType(resources2.GetObject(anInSpectrumControlName & ".OcxState"), _
                    ' '  System.Windows.Forms.AxHost.State)
                    ' 
                    zedControl.Size = aSize
                    zedControl.TabIndex = 1
                    ' 'FinneganControl.NoDataText = "No fuel left for Finnegan..."
                    ' 
                    ' anInOutForm.Controls.AddRange( _
                    '   New System.Windows.Forms.Control() {zedControl})
                    ' CType(zedControl, _
                    '   System.ComponentModel.ISupportInitialize).EndInit()

                    anInOutForm.Controls.Add(zedControl)


                    '????
                    zedControl.Tag = "xyz"

                Case Else
                    Trace.Assert(False, "PIL ASSERT. Select Case never fall-through. Unknown raw data file type!.")
            End Select
        End Sub 'addSpectrumControl


        'Changed PM_PHOSPHO_SCORING_USERSEL 2005-12-22. Now actually sets anOutCheckBox!!
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub addCheckBox( _
          ByRef anInOutForm As System.Windows.Forms.Form, _
          ByVal aCheckBoxName As String, _
          ByVal aCheckBoxText As String, _
          ByVal aLocation As System.Drawing.Point, _
          ByVal aStartValue As Boolean, _
          ByVal aTag As String, _
          ByRef anOutCheckBox As System.Windows.Forms.CheckBox _
          )

            'Changed PM_PHOSPHO_SCORING_USERSEL 2005-12-22
            'Dim someCheckBox1 As System.Windows.Forms.CheckBox = _
            '  New System.Windows.Forms.CheckBox
            anOutCheckBox = New System.Windows.Forms.CheckBox

            '  Me.SuspendLayout()

            anOutCheckBox.Location = aLocation
            anOutCheckBox.Name = aCheckBoxName

            'someCheckBox1.Size = New System.Drawing.Size(168, 24)
            anOutCheckBox.Size = New System.Drawing.Size(250, 24)

            'someCheckBox1.TabIndex = 3
            anOutCheckBox.Text = aCheckBoxText
            anOutCheckBox.Tag = aTag
            anOutCheckBox.Checked = aStartValue

            anInOutForm.Controls.Add(anOutCheckBox)
        End Sub 'addCheckBox


        'Changed PM_REFACTOR 2007-09-05
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Function defaultPeptideFilters2() _
          As Dictionary( _
            Of peptideFilterEnum, peptideFilterStructure)

            Dim toReturn As Dictionary( _
              Of peptideFilterEnum, peptideFilterStructure)

            'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-24
            '.peptideModificationFilter2 = New List(Of Integer)
            '
            'Note: this is the hash that contains the set of
            '      peptide filters, not the mod filter!
            '
            toReturn = _
              New Dictionary( _
                Of peptideFilterEnum, _
                peptideFilterStructure)

            'For parsing.
            toReturn(peptideFilterEnum.enumParsing2) = _
              peptideFilterStructure.noPepFilter()

            'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-27
            'For export (but only the peptide filter part).
            'Default: no filter
            toReturn(peptideFilterEnum.enumExport2) = _
              peptideFilterStructure.noPepFilter()

            If True Then
                Dim calibVisualFilter As peptideFilterStructure = _
                  peptideFilterStructure.noPepFilter()

                'Should we have no filter or the filter
                'corresponding to the peptides for calibration?
                toReturn(peptideFilterEnum.enumRecalibVisual) = _
                  calibVisualFilter
            End If

            If True Then
                Dim calibParseFilter As peptideFilterStructure = _
                  peptideFilterStructure.noPepFilter()

                calibParseFilter.scoreMin = 30.0

                'Should we have no filter or the filter
                'corresponding to the peptides for calibration?
                toReturn(peptideFilterEnum.enumRecalibParse) = _
                  calibParseFilter
            End If

            If True Then
                Dim validationParseFilter As peptideFilterStructure = _
                  peptideFilterStructure.noPepFilter()

                validationParseFilter.scoreMin = 25.0

                'Changed PM_MARKER_VALIDATION 2007-09-04

                'Note: default for now for mass accuracy is no 
                '      mass accuracy restriction.

                'Should we have no filter or the filter
                'corresponding to the peptides for calibration?
                toReturn(peptideFilterEnum.enumValidationParse) = _
                  validationParseFilter
            End If

            'Changed PM_RETRIEVE_PROTEIN_SEQUENCES_FASTER 2008-04-22
            If True Then
                Dim retrieveProteinSequenceFilter As peptideFilterStructure = _
                  peptideFilterStructure.noPepFilter()
                retrieveProteinSequenceFilter.scoreMin = 25.0 'Same as validation.
                toReturn(peptideFilterEnum.enumRetrieveProteinSequences) = _
                  retrieveProteinSequenceFilter
            End If

            Return toReturn
        End Function 'defaultPeptideFilter


        'Changed PM_REFACTOR 2003-10-21
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub defaultOptions( _
          ByRef anOptions As OptionsStruct2, _
          ByRef anInQuantitationModes_new As QuantitationModes_moreGeneral, _
          ByRef anInTITLElineDefinitions As TITLElineDefinitions)

            'Old (was not used): 
            '  ByRef anInQuantitationModes As QuantitationModes, _

            anOptions.scoreA = 33 'Still integer...
            anOptions.scoreB = 25 'Still integer...
            anOptions.scoreC = 20 'Still integer...
            anOptions.dontShowIPI = False
            anOptions.dontShowMosquito = False
            anOptions.dontShowProtWithNoPeptInABC = True
            anOptions.inclBoldRedPepts = True
            anOptions.inclLightRedPepts = True
            anOptions.inclRedPeptsIfCheckedOnly = True
            anOptions.inclBoldBlackPeptsIfChecked = False
            anOptions.inclBoldBlackPepts = False
            anOptions.inclPeptsInParens = False
            anOptions.protDefaultValidationScoreThr = 60 'Still integer...

            anOptions.peptDefaultValidationScoreThr2 = 25 'Still integer...

            anOptions.quantModeCode = _
              anInQuantitationModes_new.getFirstQuantitationCode()

            'Changed PM_LTQFT_PROGRAMDEFAULT 2007-08-23. Note: corresponding
            '  to new order in dialog. And associated helper functions.
            ''Changed PM_NOOPTIONS_FILE_ASSERT 2003-10-18
            '.rawFileMode = rawFileModeEnum.enumAnalyst
            anOptions.rawFileMode = rawFileModeEnum.enumFinnegan

            'Changed PM_DOMAINS_RECALIBRATION 2007-11-06
            'Note: corresponding to old recalibration, does not
            '      follow the default above, Finnigan.
            anOptions.recalibDomain = _
              SDUPrecalibrator.recalibDomainEnum.enumRecalibDomainMass

            'Changed PM_VALIDATION_AS_PEPTFILTER 2007-09-05
            ''Changed PM_PRESELECTEDVALIDATED_CONDITIONS 2004-06-21
            '.peptideMaximumRelativeError_PPM = 9999
            '.peptideMinimumDeltaScore = 0.0

            'Changed PM_MSTYPES_FOR_QUANT_OPTION 2004-09-13
            anOptions.MStypes = QuantMSTypesEnum.enumMS_SIM

            'Changed PM_MODIFICATION_FILTER 2004-12-07
            If True Then 'Block to group...
                anOptions.peptideFilters = defaultPeptideFilters2()
            End If

            'Changed PM_TITLELINEPARSING 2007-06-08
            anOptions.TITLEparseDefsCode = _
              anInTITLElineDefinitions.getFirstTITLElineDefCode()

            'Changed PM_REPORTS 2006-08-15
            anOptions.doNotShowDialogAfterParsing = False

            'Changed PM_COMVERSIONS 2007-07-24
            anOptions.COMversion = COMversionEnum.enumAnalystQS20

            'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-29
            anOptions.exportSettings.includePeptides = True
            anOptions.exportSettings.includeProteinInformation2 = False

            'Changed PM_SPECTRAEXPORT_GENERALISED 2008-05-05
            anOptions.exportSettings.includeSpectra = False


            anOptions.exportSettings.tag = tagEnum.enumTag1 'This is a helper field. We
            '  do not really need to set it and it is not persisted.

            anOptions.checkSum = 8893

            'Changed PM_QUANT_ALL 2007-10-12
            anOptions.extra2 = "xyz"

            'Changed PM_HIDE_RECALIBVISUALISATION_WINDOW 2008-01-06
            anOptions.endOfParseAction.openRecalibrationVisualisationWindow = True

            'Changed PM_RECALIB_REALITY_CHECK 2008-03-26
            anOptions.recalibLimits = SDUPrecalibrator.defaultRecalibLimits() 'Let
            '  recalibrator know about defaults. Or is this too application
            '  specific?
        End Sub 'defaultOptions


        'Changed PM_REFACTOR 2007-08-30
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Shared Function extractVendorEnum( _
          ByRef anInFieldName As String, _
          ByRef anInSomeHandle As System.Xml.XmlNode, _
          ByRef anInSomeNsManager As System.Xml.XmlNamespaceManager) _
          As rawFileModeEnum

            Dim toReturn As rawFileModeEnum = rawFileModeEnum.enumAnalyst
            '  Default, e.g. unknown. Can happen if reading a file created
            '  by a newer version of this program.

            Dim enumStr As String = Nothing 'Keep compiler happy.
            MSQuantCommon2.extractStringFromXmlNode( _
              anInSomeHandle, anInSomeNsManager, anInFieldName, enumStr)
            Select Case enumStr
                Case "enumAnalyst"
                    toReturn = rawFileModeEnum.enumAnalyst
                Case "enumFinnegan"
                    toReturn = rawFileModeEnum.enumFinnegan
                Case "enumMicromass"
                    toReturn = rawFileModeEnum.enumMicromass
                Case Else
                    'If it does not exist then we use the default that
                    'was already set.
                    Dim peter2 As Integer = 2
            End Select

            Return toReturn
        End Function 'extractVendorEnum


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub loadOptions(ByVal aFileName2 As String, _
          ByRef anOutOptions As OptionsStruct2)

            'Changed PM_OPTIONSFILES_ONLYINBIN 2004-01-28
            Dim fileNameFullPath As String = _
              MSQuantCommon2.fullPathToFileInApplicationFolder(aFileName2)

            mMSQOptionsFileName_FullPath = fileNameFullPath
            Trace.Assert( _
              MSQuantCommon2.isFullPathFileName(mMSQOptionsFileName_FullPath), _
              "PIL ASSERT. Options file is not a full path name: " & _
              mMSQOptionsFileName_FullPath)

            'Changed PM_TITLELINEPARSING 2007-06-08
            Dim settings As miscSettingsStructure2Struct = _
              Me.getMiscSettings()

            defaultOptions( _
              mOptions, Me.getQuantModes(), settings.TITLElineDefs)
            '  Second parameter deleted (was not used):  
            '    Me.getQuantitationModesObject()

            'Changed PM_LESSSTRICT_READINGOPTIONS 2007-08-22
            'Dim defaultXML As String = _
            '  "<SOAP-ENV:Envelope   " & ControlChars.NewLine & _
            '  "    xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""                " & ControlChars.NewLine & _
            '  "    xmlns:xsd=""http://www.w3.org/2001/XMLSchema""                         " & ControlChars.NewLine & _
            '  "    xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/""           " & ControlChars.NewLine & _
            '  "    xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/""           " & ControlChars.NewLine & _
            '  "    xmlns:clr=""http://schemas.microsoft.com/soap/encoding/clr/1.0""       " & ControlChars.NewLine & _
            '  "    SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">  " & ControlChars.NewLine & _
            '  "  <SOAP-ENV:Body>                                                        " & ControlChars.NewLine & _
            '  "    <a1:MascotParserOptionsStruct2 id=""ref-1""                                 " & ControlChars.NewLine & _
            '  "        xmlns:a1=""http://schemas.microsoft.com/clr/assem/Mascot%20Parser%2C%20Version%3D1.0.1440.24757%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"">  " & ControlChars.NewLine & _
            '  "                                  " & ControlChars.NewLine & _
            '  "    </a1:MascotParserOptionsStruct2>   " & ControlChars.NewLine & _
            '  "  </SOAP-ENV:Body>                " & ControlChars.NewLine & _
            '  "</SOAP-ENV:Envelope>              " & ControlChars.NewLine
            '
            'Dim NSSpec2 As String = _
            '  "http://schemas.microsoft.com/clr/assem/Mascot%20Parser%2C%20Version%3D1.0.1440.24757%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"

            'Changed PM_LESSSTRICT_READINGOPTIONS 2007-08-22
            'Dim fileDidNotExist As Boolean = True
            Dim fileDidNotExist2 As Boolean = _
              Not File.Exists(fileNameFullPath)

            If fileDidNotExist2 Then
                'Moved up here.
                PersistOptionsSettings(aFileName2, mOptions) 'Also called
                '  somewhere else...
            Else
                Try
                    'For MSQuant options.
                    Dim dummyFileDidNotExist As Boolean

                    'Changed PM_LESSSTRICT_READINGOPTIONS 2007-08-22.
                    'Dim struHandle As System.Xml.XmlNode = MSQuantCommon2.optionsFileLoad( _
                    '  fileNameFullPath, "MascotParserOptionsStruct2", 1200, _
                    '  defaultXML, NSSpec, mOptionsDOM, mOptionsNsManager, _
                    '  dummyFileDidNotExist)

                    'From loadOptions().
                    Dim struHandle2 As System.Xml.XmlNode = _
                      MSQuantCommon2.optionsFileLoad( _
                        fileNameFullPath, "/", 1200, _
                        "", _
                        "", _
                        mOptionsDOM, mOptionsNsManager, _
                        dummyFileDidNotExist)

                    Dim optionsHandle As System.Xml.XmlNode = _
                      struHandle2.SelectSingleNode( _
                        "//MascotParserOptionsStruct2", mOptionsNsManager)

                    If True Then 'Single values, not grouped. Except for checksum.

                        'Note: names are without "Score" for backward compatibility
                        '      reasons.
                        MSQuantCommon2.extractIntegerFromXmlNode( _
                          optionsHandle, mOptionsNsManager, "protDefaultValidation", _
                          mOptions.protDefaultValidationScoreThr)

                        'What if a change to the quantitation modes have invalidated a 
                        'a stored code?. Answer: we should check if the code exist
                        'and use a default if not found. To Be Done.
                        MSQuantCommon2.extractIntegerFromXmlNode( _
                          optionsHandle, mOptionsNsManager, "quantModeCode", _
                          mOptions.quantModeCode)

                        'Changed PM_REFACTOR 2007-08-30
                        ' If True Then
                        '     Dim enumStr As String = "enumAnalyst"
                        '     MSQuantCommon2.extractStringFromXmlNode( _
                        '       optionsHandle, mOptionsNsManager, "rawFileMode", enumStr)
                        '     Select Case enumStr
                        '         Case "enumAnalyst"
                        '             mOptions.rawFileMode = rawFileModeEnum.enumAnalyst
                        '         Case "enumFinnegan"
                        '             mOptions.rawFileMode = rawFileModeEnum.enumFinnegan
                        '         Case "enumMicromass"
                        '             mOptions.rawFileMode = rawFileModeEnum.enumMicromass
                        '         Case Else
                        '             'If it does not exist then we use the default that was already set.
                        '             Dim peter2 As Integer = 2
                        '     End Select
                        ' End If 'rawFileMode
                        mOptions.rawFileMode = _
                          extractVendorEnum( _
                            "rawFileMode", optionsHandle, mOptionsNsManager)

                        If True Then 'MStypes
                            'Changed PM_SAVING_OPTIONS 2004-09-14
                            Dim enumStr2 As String = "enumMS_SIM" 'Default for older
                            '  versions of the program that do not have this option.
                            MSQuantCommon2.extractStringFromXmlNode( _
                              optionsHandle, mOptionsNsManager, "MStypes", enumStr2)
                            Select Case enumStr2
                                Case "enumAllMStypes"
                                    mOptions.MStypes = QuantMSTypesEnum.enumAllMStypes
                                Case "enumMS_SIM"
                                    mOptions.MStypes = QuantMSTypesEnum.enumMS_SIM
                                Case "enumMSFullScan"
                                    mOptions.MStypes = QuantMSTypesEnum.enumMSFullScan
                                Case Else
                                    'If it does not exist then we use the default that was already set.
                            End Select
                        End If 'MStypes

                        'Changed PM_TITLELINEPARSING 2007-06-08
                        MSQuantCommon2.extractIntegerFromXmlNode( _
                          optionsHandle, mOptionsNsManager, "TITLEparseDefsCode", _
                          mOptions.TITLEparseDefsCode)

                        MSQuantCommon2.extractBooleanFromXmlNode( _
                          optionsHandle, mOptionsNsManager, "doNotShowDialogAfterParsing", _
                          mOptions.doNotShowDialogAfterParsing)

                        'Changed PM_PERSIST_RECALIBTYPE 2008-02-08
                        If True Then 'Recalibration domain (mass, frequency, etc.)
                            Dim enumStr3 As String = "enumRecalibDomainMass" 'Default 
                            '  for older versions of the program that do not have
                            '  this option.
                            MSQuantCommon2.extractStringFromXmlNode( _
                              optionsHandle, mOptionsNsManager, "recalibDomain", _
                              enumStr3)
                            Select Case enumStr3
                                Case "enumRecalibDomainMass"
                                    mOptions.recalibDomain = _
                                      recalibDomainEnum.enumRecalibDomainMass
                                Case "enumRecalibDomainFreq"
                                    mOptions.recalibDomain = _
                                      recalibDomainEnum.enumRecalibDomainFreq2
                                Case "enumRecalibDomainTOFtime"
                                    mOptions.recalibDomain = _
                                      recalibDomainEnum.enumRecalibDomainTOFtime
                                Case "enumRecalibDomainSqrtFreq"
                                    mOptions.recalibDomain = _
                                      recalibDomainEnum.enumRecalibDomainSqrtFreq
                                Case Else
                                    'If it is not known (e.g. we could be reading a
                                    'file generated by newer version of the
                                    'program) then we use the default.
                                    '
                                    'Note: if we are reading an older version then
                                    '  the default is used (we will not be here then).
                                    Dim peter2 As Integer = 2
                            End Select
                        End If 'Recalibration domain.


                    End If 'Single values, not grouped. Except for checksum.


                    ''This complicated stuff with name space, etc does not (easily)
                    ''work. Instead we bypass checking for "MascotParserOptionsStruct2",
                    ''at least for now. 
                    ''a1:MascotParserOptionsStruct2 vs. MascotParserOptionsStruct2 ??
                    'Dim struc2 As XmlNode = _
                    '  struHandle.SelectSingleNode( _
                    '     "//MascotParserOptionsStruct2", mOptionsNsManager _
                    '    )
                    'Dim struc3 As XmlNode = _
                    '  struHandle.SelectSingleNode( _
                    '     "//a1:MascotParserOptionsStruct2", mOptionsNsManager _
                    '    )
                    '
                    'For reference, new_spectrumClassification.xml, list
                    'of something:
                    '
                    '  Dim specList As XmlNodeList = _
                    '    struHandle.SelectNodes( _
                    '      "//classificationItem", specNsManager)

                    'Dim struc2 As XmlNode = _
                    '  struHandle.SelectSingleNode( _
                    '     "//correlationAndLCpeaksDetectionSettings" _
                    '    )

                    'Changed PM_LESSSTRICT_READINGOPTIONS 2007-08-22.
                    'fileDidNotExist = struHandle.SelectSingleNode( _
                    '  "scoreA", mOptionsNsManager) Is Nothing


                    If True Then 'Preselected peptides (PSPs).
                        'Dim preselectedPep As System.Xml.XmlNode = struHandle.SelectSingleNode( _
                        '  "//preselectedPeptides", mOptionsNsManager)
                        Dim preselectedPep As System.Xml.XmlNode = optionsHandle.SelectSingleNode( _
                          "preselectedPeptides", mOptionsNsManager)

                        MSQuantCommon2.extractBooleanFromXmlNode( _
                          preselectedPep, mOptionsNsManager, "inclBoldRedPepts", _
                          mOptions.inclBoldRedPepts)
                        MSQuantCommon2.extractBooleanFromXmlNode( _
                          preselectedPep, mOptionsNsManager, "inclLightRedPepts", _
                          mOptions.inclLightRedPepts)
                        MSQuantCommon2.extractBooleanFromXmlNode( _
                          preselectedPep, mOptionsNsManager, "inclRedPeptsIfCheckedOnly", _
                          mOptions.inclRedPeptsIfCheckedOnly)
                        MSQuantCommon2.extractBooleanFromXmlNode( _
                          preselectedPep, mOptionsNsManager, "inclBoldBlackPeptsIfChecked", _
                          mOptions.inclBoldBlackPeptsIfChecked)
                        MSQuantCommon2.extractBooleanFromXmlNode( _
                          preselectedPep, mOptionsNsManager, "inclBoldBlackPepts", _
                          mOptions.inclBoldBlackPepts)
                        MSQuantCommon2.extractBooleanFromXmlNode( _
                          preselectedPep, mOptionsNsManager, "inclPeptsInParens", _
                          mOptions.inclPeptsInParens)
                    End If 'Preselected peptides (PSPs).

                    If True Then 'Validation of preselected peptides (PSPs).
                        'Dim valiHandle As System.Xml.XmlNode = struHandle.SelectSingleNode( _
                        '  "//validationOfPreselectedPeptides", mOptionsNsManager)
                        Dim valiHandle As System.Xml.XmlNode = _
                          optionsHandle.SelectSingleNode( _
                            "validationOfPreselectedPeptides", mOptionsNsManager)

                        'Changed PM_VALIDATION_AS_PEPTFILTER 2007-09-05. We no longer
                        'read it. They are now in a peptide filter.
                        ' MSQuantCommon2.extractDoubleFromXmlNode( _
                        '   valiHandle, mOptionsNsManager, "peptideMaximumRelativeError_PPM", _
                        '   mOptions.peptideMaximumRelativeError_PPM)
                        ' 
                        ' MSQuantCommon2.extractIntegerFromXmlNode( _
                        '   valiHandle, mOptionsNsManager, "peptDefaultValidation", _
                        '   mOptions.peptDefaultValidationScoreThr)

                    End If 'Validation of preselected peptides (PSPs).

                    If True Then 'Classification of preselected peptides (PSPs).
                        'Dim classi As System.Xml.XmlNode = struHandle.SelectSingleNode( _
                        '  "//classificationOfPreselectedPeptides", mOptionsNsManager)
                        Dim classi As System.Xml.XmlNode = optionsHandle.SelectSingleNode( _
                          "classificationOfPreselectedPeptides", mOptionsNsManager)

                        MSQuantCommon2.extractIntegerFromXmlNode( _
                          classi, mOptionsNsManager, "scoreA", _
                          mOptions.scoreA)
                        MSQuantCommon2.extractIntegerFromXmlNode( _
                          classi, mOptionsNsManager, "scoreB", _
                          mOptions.scoreB)
                        MSQuantCommon2.extractIntegerFromXmlNode( _
                          classi, mOptionsNsManager, "scoreC", _
                          mOptions.scoreC)
                    End If 'Classification of preselected peptides (PSPs).

                    If True Then 'vendors. E.g. one particular COM component version per
                        '  instrument type.

                        'More structured, but also less flexible.
                        'Dim vendors As System.Xml.XmlNodeList = struHandle.SelectNodes( _
                        '  "//vendors/vendor", mOptionsNsManager)
                        Dim vendors As System.Xml.XmlNodeList = _
                          optionsHandle.SelectNodes( _
                            "vendors/vendor", mOptionsNsManager)

                        Dim someNode As System.Xml.XmlNode
                        For Each someNode In vendors

                            Dim vendorID As rawFileModeEnum = extractVendorEnum( _
                              "ID", someNode, mOptionsNsManager)

                            Dim enumStr3 As String = ""
                            MSQuantCommon2.extractStringFromXmlNode( _
                              someNode, mOptionsNsManager, "COMversion", enumStr3)

                            Dim res As COMversionEnum = COMversionEnum.enumAnalystQS20
                            Select Case enumStr3
                                Case "enumAnalystQS10"
                                    res = COMversionEnum.enumAnalystQS10

                                Case "enumAnalystQS11"
                                    res = COMversionEnum.enumAnalystQS11

                                Case "enumAnalystQS20"
                                    res = COMversionEnum.enumAnalystQS20

                                Case "enumXCalibur143RC"
                                    res = COMversionEnum.enumXCalibur143RC

                                Case "enumXCalibur20"
                                    res = COMversionEnum.enumXCalibur20

                                Case "enumXCalibur20SR1"
                                    res = COMversionEnum.enumXCalibur20SR1

                                Case "enumMassLynx40"
                                    res = COMversionEnum.enumMassLynx40

                                Case "enumMassLynx41"
                                    res = COMversionEnum.enumMassLynx41

                                Case Else
                                    'Use the default...
                                    Dim peter2 As Integer = 2
                            End Select

                            'For now: only Analyst. And only QS2.0 and QS1.1 are supported 
                            '  elsewhere in the program (QS1.0 not supported yet)
                            '  We do not currently have a place to store the others.
                            '  The datastructure would be a list of vendors.
                            If vendorID = rawFileModeEnum.enumAnalyst Then
                                mOptions.COMversion = res
                            End If
                        Next 'Through vendors.
                    End If 'Vendors

                    'Changed PM_DISABLE_OLD_OPTIONS 2007-08-23
                    'MSQuantCommon2.extractBooleanFromXmlNode_deep( _
                    '  struHandle, mOptionsNsManager, "dontShowIPI", _
                    '  mOptions.dontShowIPI)
                    'MSQuantCommon2.extractBooleanFromXmlNode_deep( _
                    '  struHandle, mOptionsNsManager, "dontShowMosquito", _
                    '  mOptions.dontShowMosquito)
                    'MSQuantCommon2.extractBooleanFromXmlNode_deep( _
                    '  struHandle, mOptionsNsManager, "dontShowProtWithNoPeptInABC", _
                    '  mOptions.dontShowProtWithNoPeptInABC)

                    If True Then 'Peptide filters. 
                        Dim peptideFilters As System.Xml.XmlNodeList = _
                          optionsHandle.SelectNodes( _
                            "peptideFilters/peptideFilter", mOptionsNsManager)

                        Dim someFilterNode As System.Xml.XmlNode
                        For Each someFilterNode In peptideFilters

                            Dim enumStr4 As String = ""
                            MSQuantCommon2.extractStringFromXmlNode( _
                              someFilterNode, mOptionsNsManager, "key", enumStr4)

                            Dim key As peptideFilterEnum = peptideFilterEnum.enumParsing2
                            Dim validEnum As Boolean = True
                            Select Case enumStr4
                                Case "enumParsing2"
                                    key = peptideFilterEnum.enumParsing2
                                Case "enumExport2"
                                    key = peptideFilterEnum.enumExport2

                                    'Changed PM_RECALIB_VISUAL_SAVE 2007-09-04
                                Case "enumRecalibVisual"
                                    key = peptideFilterEnum.enumRecalibVisual
                                Case "enumRecalibParse"
                                    key = peptideFilterEnum.enumRecalibParse
                                Case "enumValidationParse"
                                    key = peptideFilterEnum.enumValidationParse

                                    'Changed PM_RETRIEVE_PROTEIN_SEQUENCES_FASTER 2008-04-22
                                Case "enumRetrieveProteinSequences"
                                    key = peptideFilterEnum.enumRetrieveProteinSequences

                                Case Else
                                    validEnum = False
                            End Select

                            'This will set all fields to defaults. If we 
                            'are reading an options file created by an older version
                            'then news fields will get default values.
                            Dim someFilter As peptideFilterStructure = _
                              peptideFilterStructure.noPepFilter()

                            MSQuantCommon2.extractIntegerFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "chargeMin", someFilter.chargeMin)
                            MSQuantCommon2.extractIntegerFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "chargeMax", someFilter.chargeMax)

                            MSQuantCommon2.extractIntegerFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "seqLengthMin", someFilter.seqLengthMin)
                            MSQuantCommon2.extractIntegerFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "seqLengthMax", someFilter.seqLengthMax)

                            MSQuantCommon2.extractDoubleFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "massMin", someFilter.massMin)
                            MSQuantCommon2.extractDoubleFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "massMax", someFilter.massMax)

                            MSQuantCommon2.extractBooleanFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "highestScoringUniquelyModified", someFilter.highestScoringUniquelyModified)

                            MSQuantCommon2.extractDoubleFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "scoreMin", someFilter.scoreMin)
                            MSQuantCommon2.extractDoubleFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "scoreMax", someFilter.scoreMax2)

                            MSQuantCommon2.extractBooleanFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "quantifiedOnly", someFilter.quantifiedOnly)
                            MSQuantCommon2.extractBooleanFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "verifiedOnly", someFilter.verifiedOnly)

                            'Changed PM_MASSACC_PEPFILTER 2007-09-05
                            MSQuantCommon2.extractDoubleFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "massAccuracyMin", someFilter.massAccuracyMin)
                            MSQuantCommon2.extractDoubleFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "massAccuracyMax", someFilter.massAccuracyMax)

                            'Changed PM_RAWFILE_PEPFILTER 2007-11-17
                            MSQuantCommon2.extractIntegerFromXmlNode( _
                              someFilterNode, mOptionsNsManager, _
                              "rawFileID", someFilter.rawFileID)

                            If True Then 'Mod filter
                                'Changed PM_PEPTIDECOUNT_BUG 2007-09-04
                                'someFilter.pepModFilter3 = _
                                '  New List(Of Integer)
                                someFilter.pepModFilter3 = _
                                  Nothing

                                Dim modFilter As System.Xml.XmlNodeList = _
                                  someFilterNode.SelectNodes( _
                                    "modificationList/modID", mOptionsNsManager)
                                Dim someNode2 As System.Xml.XmlNode
                                For Each someNode2 In modFilter

                                    'Changed PM_PEPTIDECOUNT_BUG 2007-09-04
                                    If someFilter.pepModFilter3 Is Nothing Then

                                        'The list must never be empty,
                                        'Nothing or one or more items.
                                        someFilter.pepModFilter3 = _
                                          New List(Of Integer)
                                    End If

                                    Dim modID As Integer = -999999
                                    ' MSQuantCommon2.extractIntegerFromXmlNode( _
                                    '   someNode2, mOptionsNsManager, _
                                    '   "modID", modID)
                                    ' 
                                    Dim modIDStr As String = someNode2.InnerText
                                    modID = CInt(modIDStr)

                                    If modID <> -999999 Then
                                        someFilter.pepModFilter3.Add(modID)
                                    Else
                                        Dim peter2 As Integer = 2 'Why did this
                                        '  happen?? Because extractIntegerFromXmlNode()
                                        '  is picking out from a particular
                                        '  field in a container (e.g. "struct").
                                        '
                                        '  Whereas in this case we have a
                                        '  reference to the field itself.
                                    End If
                                Next 'Through modification list.
                            End If 'Mod filter

                            If validEnum Then 'We will ignore those for which
                                '  we don't have an enumeration.

                                mOptions.peptideFilters(key) = someFilter
                            End If
                        Next 'Through filters
                    End If 'Peptide filters. 

                    If True Then 'Export settings.
                        Dim exportSettings As System.Xml.XmlNode = _
                          optionsHandle.SelectSingleNode( _
                            "exportSettings", mOptionsNsManager)

                        MSQuantCommon2.extractBooleanFromXmlNode( _
                          exportSettings, mOptionsNsManager, "includePeptides", _
                          mOptions.exportSettings.includePeptides)

                        MSQuantCommon2.extractBooleanFromXmlNode( _
                          exportSettings, mOptionsNsManager, "includeProteinInformation", _
                          mOptions.exportSettings.includeProteinInformation2)

                        'Changed PM_SPECTRAEXPORT_GENERALISED 2008-05-05
                        MSQuantCommon2.extractBooleanFromXmlNode( _
                          exportSettings, mOptionsNsManager, "includeSpectra", _
                          mOptions.exportSettings.includeSpectra)
                    End If 'Export settings.

                    'Changed PM_HIDE_RECALIBVISUALISATION_WINDOW 2008-01-06
                    If True Then 'End of parse settings.
                        Dim endOfParseSettings As System.Xml.XmlNode = _
                          optionsHandle.SelectSingleNode( _
                            "endOfParseActions", mOptionsNsManager)

                        If Not endOfParseSettings Is Nothing Then 'It is Nothing
                            '  when reading an older version of the settings
                            '  file that does not have the group.
                            Dim act As endOfParseActionStructure
                            MSQuantCommon2.extractBooleanFromXmlNode( _
                              endOfParseSettings, mOptionsNsManager, _
                              "openRecalibrationVisualisationWindow", _
                              act.openRecalibrationVisualisationWindow)
                            mOptions.endOfParseAction = act
                        End If

                    End If 'End of parse settings.

                    MSQuantCommon2.extractIntegerFromXmlNode( _
                      optionsHandle, mOptionsNsManager, "checkSum", _
                      mOptions.checkSum)

                    'Changed PM_QUANT_ALL 2007-10-12
                    Dim extraStr As String = ""
                    MSQuantCommon2.extractStringFromXmlNode( _
                      optionsHandle, mOptionsNsManager, "extra", _
                      mOptions.extra2)

                Catch e2 As Exception
                    MsgBox( _
                      "Could not load settings from options file " & _
                      fileNameFullPath & _
                      ". Using default values instead." & ControlChars.NewLine & _
                      ControlChars.NewLine & _
                      "Some details, exception: " & e2.Message & "..........")

                    'Changed PM_LESSSTRICT_READINGOPTIONS 2007-08-22
                    ''Use some file name that does not exist to force loading default.
                    ''Should we change optionsFileLoad to have a parameter to force-load?
                    'Dim dummyFileDidNotExist As Boolean
                    'Dim struHandle2 As System.Xml.XmlNode = _
                    '  MSQuantCommon2.optionsFileLoad( _
                    '    "xyz921.xml", "MascotParserOptionsStruct2", 1200, _
                    '    defaultXML, NSSpec, mOptionsDOM, mOptionsNsManager, _
                    '    dummyFileDidNotExist)
                    'fileDidNotExist = True
                    PersistOptionsSettings(aFileName2, mOptions) 'Also
                    '  called somewhere else...
                End Try
            End If 'File exist.

            'Changed PM_LESSSTRICT_READINGOPTIONS 2007-08-22. Moved up.
            'If fileDidNotExist Then
            '    'If file did not exist:
            '    'Persist the default instead such that the configuration
            '    'file is always created if it does not exist.
            '    PersistOptionsSettings()
            'Else
            '    Dim peter9 As Integer = 9
            'End If

            'Changed PM_REFACTOR_TITLELINEPARSING 2007-06-08
            'We have to do this manually now, as misc options are now loaded before
            'user settings (that contain the raw file mode, .RAW/.WIFF/.DAT).
            'The old call to getMiscSettings() above failed...
            Me.patchSomeFields(mOptions.rawFileMode) 'For misc options

            anOutOptions = mOptions
        End Sub 'loadOptions


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub newOptions2( _
          ByRef anInNewSettings As OptionsStruct2)

            mOptions = anInNewSettings
            PersistOptionsSettings(mMSQOptionsFileName_FullPath, anInNewSettings)

            'Changed PM_RAWFILETYPE_CHANGE_QUANTBUG 2007-09-27
            patchSomeFields(anInNewSettings.rawFileMode)
        End Sub 'newOptions


        'Changed PM_MSQOPTIONS_SIMPLE_XML 2007-08-23. Old format. Delete at any time.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub PersistOptionsSettings_old()

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

            Dim xpathSpec As String = _
              MSQuantCommon2.construct_xPathSpec("MascotParserOptionsStruct2")

            'Note: we could use the SOAP formatter, but then we would loose forward
            '  compatibiliy - with this scheme any old field that we don't support  
            '  anymore is left unchanged (stored in the DOM object) and thus 
            '  older versions would be able to use a file that is written with
            '  this newer version.

            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.scoreA.ToString(), _
              "scoreA")
            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.scoreB.ToString(), _
              "scoreB")
            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.scoreC.ToString(), _
              "scoreC")

            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.dontShowIPI.ToString(), _
              "dontShowIPI")
            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.dontShowMosquito.ToString(), _
              "dontShowMosquito")
            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.dontShowProtWithNoPeptInABC.ToString(), _
              "dontShowProtWithNoPeptInABC")

            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.inclBoldRedPepts.ToString(), _
              "inclBoldRedPepts")
            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.inclLightRedPepts.ToString(), _
              "inclLightRedPepts")
            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.inclRedPeptsIfCheckedOnly.ToString(), _
              "inclRedPeptsIfCheckedOnly")

            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.inclBoldBlackPeptsIfChecked.ToString(), _
              "inclBoldBlackPeptsIfChecked")
            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.inclBoldBlackPepts.ToString(), _
              "inclBoldBlackPepts")
            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.inclPeptsInParens.ToString(), _
              "inclPeptsInParens")

            'Changed PM_REFACTOR 2006-10-25
            'Note: names are without "Score" for backward compatibility
            '      reasons.
            '      We could use element names with score here, but
            '      that would complicate the reading code. This however
            '      ought to be done at a later time.
            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.protDefaultValidationScoreThr.ToString(), _
              "protDefaultValidation")

            'Changed PM_VALIDATION_AS_PEPTFILTER 2007-09-05
            'insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
            '  mOptions.peptDefaultValidationScoreThr.ToString(), _
            '  "peptDefaultValidation")

            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.quantModeCode.ToString(), _
              "quantModeCode")
            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.checkSum.ToString(), _
              "checkSum")

            If True Then
                'We could use reflection here to get the encoding for the enumeration.
                Dim rawFileEnumEncoding As String = Nothing 'Keep compiler happy.
                Select Case mOptions.rawFileMode
                    Case rawFileModeEnum.enumAnalyst
                        rawFileEnumEncoding = "enumAnalyst"
                    Case rawFileModeEnum.enumFinnegan
                        rawFileEnumEncoding = "enumFinnegan"
                    Case rawFileModeEnum.enumMicromass
                        rawFileEnumEncoding = "enumMicromass"
                    Case Else
                        Trace.Assert(False, _
                          "PIL ASSERT. Select Case never fall-through")
                End Select
                insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
                  rawFileEnumEncoding, "rawFileMode")
            End If

            'Changed PM_SAVING_OPTIONS 2004-09-14
            If True Then

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

                'We could use reflection here to get the encoding for the enumeration.
                Dim QuantMSTypesEnumEncoding As String = Nothing 'Keep compiler happy.
                Select Case mOptions.MStypes
                    Case QuantMSTypesEnum.enumAllMStypes
                        QuantMSTypesEnumEncoding = "enumAllMStypes"
                    Case QuantMSTypesEnum.enumMS_SIM
                        QuantMSTypesEnumEncoding = "enumMS_SIM"
                    Case QuantMSTypesEnum.enumMSFullScan
                        QuantMSTypesEnumEncoding = "enumMSFullScan"
                    Case Else
                        Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
                End Select

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

                insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
                  QuantMSTypesEnumEncoding, "MStypes")

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

            'Changed PM_VALIDATION_AS_PEPTFILTER 2007-09-05
            'insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
            '  mOptions.peptideMaximumRelativeError_PPM.ToString, _
            '  "peptideMaximumRelativeError_PPM")

            'Changed PM_TITLELINEPARSING 2007-06-08
            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.TITLEparseDefsCode.ToString(), _
              "TITLEparseDefsCode")

            'Changed PM_REPORTS 2006-08-15
            insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
              mOptions.doNotShowDialogAfterParsing.ToString, _
              "doNotShowDialogAfterParsing")

            'Changed PM_COMVERSIONS 2007-07-24
            If True Then
                Dim str2 As String = Nothing 'Keep compiler happy.
                Select Case mOptions.COMversion
                    Case COMversionEnum.enumAnalystQS10
                        str2 = "enumAnalystQS10"

                    Case COMversionEnum.enumAnalystQS11
                        str2 = "enumAnalystQS11"

                    Case COMversionEnum.enumAnalystQS20
                        str2 = "enumAnalystQS20"

                    Case COMversionEnum.enumXCalibur143RC
                        str2 = "enumXCalibur143RC"

                    Case COMversionEnum.enumXCalibur20
                        str2 = "enumXCalibur20"

                    Case COMversionEnum.enumXCalibur20SR1
                        str2 = "enumXCalibur20SR1"

                    Case COMversionEnum.enumMassLynx40
                        str2 = "enumMassLynx40"

                    Case COMversionEnum.enumMassLynx41
                        str2 = "enumMassLynx41"

                    Case Else
                        Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
                End Select
                insertOrOverwriteSetting(mOptionsDOM, mOptionsNsManager, xpathSpec, _
                  str2, "COMversion")

                'Note: 
            End If 'COMversion

            'Changed PM_OPTIONSFILES_ONLYINBIN 2004-01-28
            Trace.Assert(MSQuantCommon2.isFullPathFileName( _
                mMSQOptionsFileName_FullPath), _
              "PIL ASSERT. Options file is not a full path name: " & _
              mMSQOptionsFileName_FullPath)
            mOptionsDOM.Save(mMSQOptionsFileName_FullPath) 'Note: this will
            '  save  that we don't know or don't care about.
        End Sub 'PersistOptionsSettings_old


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub outputCOMversion( _
          ByRef anInVendorStr As String, _
          ByRef anInVendorID As rawFileModeEnum, _
          ByRef anInCOMversion As COMversionEnum, _
          ByRef anInOutSf As XmlTextWriter)

            Dim str2 As String = Nothing 'Keep compiler happy.
            Select Case anInCOMversion
                Case COMversionEnum.enumAnalystQS10
                    str2 = "enumAnalystQS10"

                Case COMversionEnum.enumAnalystQS11
                    str2 = "enumAnalystQS11"

                Case COMversionEnum.enumAnalystQS20
                    str2 = "enumAnalystQS20"

                Case COMversionEnum.enumXCalibur143RC
                    str2 = "enumXCalibur143RC"

                Case COMversionEnum.enumXCalibur20
                    str2 = "enumXCalibur20"

                Case COMversionEnum.enumXCalibur20SR1
                    str2 = "enumXCalibur20SR1"

                Case COMversionEnum.enumMassLynx40
                    str2 = "enumMassLynx40"

                Case COMversionEnum.enumMassLynx41
                    str2 = "enumMassLynx41"

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

            anInOutSf.WriteStartElement("vendor")
            anInOutSf.WriteElementString( _
              "name", Nothing, anInVendorStr)
            anInOutSf.WriteElementString( _
              "ID", Nothing, anInVendorID.ToString())
            anInOutSf.WriteElementString( _
              "COMversion", Nothing, str2)
            'anInOutSf.WriteElementString( _
            '  "someOtherXXXX", Nothing, "XYZ")

            anInOutSf.WriteEndElement() 'For vendor
        End Sub 'outputCOMversion


        'Does not seem to be used. Delete?
        ' '****************************************************************************
        ' '*    <placeholder for header>                                              *
        ' '****************************************************************************
        ' Public Shared Sub outputPeptideFilter3( _
        '   ByRef anInOnePeptideFilter As String, _
        '   ByRef anInOutSf As XmlTextWriter)
        ' 
        '     'Later: change type of anInOnePeptideFilter
        ' 
        '     SDUPcomment(anInOutSf, _
        '       "<peptide filter>")
        '     anInOutSf.WriteStartElement("peptideFilter")
        ' 
        '     anInOutSf.WriteElementString( _
        '       "xxx", Nothing, "xxx")
        ' 
        '     anInOutSf.WriteEndElement() 'for peptideFilter
        ' End Sub 'outputPeptideFilter3


        'Changed PM_MSQOPTIONS_SIMPLE_XML 2007-08-23. New format for the
        'options file.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub PersistOptionsSettings( _
          ByRef anInPersist_fileNameFullPath As String, _
          ByRef anInSettings As OptionsStruct2)

            'Error detection: this field must stay constant
            Trace.Assert(anInSettings.checkSum = 8893, _
              "PIL ASSERT. Bad configuration file, " & _
              anInPersist_fileNameFullPath & _
              ". Delete it and restart the program.")

            'Changed PM_XMLCOMMENTS_LINEBREAK 2008-02-08
            Dim ssb As StringBuilder = New StringBuilder(100)

            Dim sfX As XmlTextWriter = _
              MSQuantCommon2.newStandardXMLout( _
                anInPersist_fileNameFullPath, Nothing, Nothing, _
                quantApplication.versionString_withDate())

            SDUP_emptyCommentLine(sfX)

            SDUPcomment(sfX, _
              "Note: this file is overwritten when the menu Tools/Options dialog is closed with OK.", _
              ssb)

            SDUP_emptyCommentLine(sfX)

            SDUPcomment(sfX, _
              "Changed: 2007-08-23 PM  Initial version of this non-SOAP/ DOM formatted file.", _
              ssb)
            SDUPcomment(sfX, "Changed: 2007-xx-xx PM", ssb)

            SDUP_emptyCommentLine(sfX)
            SDUP_emptyCommentLine(sfX)

            sfX.WriteStartElement("MascotParserOptionsStruct2")

            If True Then 'Single values, not grouped. Except for checksum.

                'Internal name ought to have "score" in it.
                sfX.WriteElementString( _
                  "protDefaultValidation", Nothing, _
                  anInSettings.protDefaultValidationScoreThr.ToString())

                sfX.WriteElementString( _
                  "quantModeCode", Nothing, _
                  anInSettings.quantModeCode.ToString())
                If True Then
                    'We could use reflection here to get the encoding for the enumeration.
                    Dim rawFileEnumEncoding As String = Nothing 'Keep compiler happy.
                    Select Case anInSettings.rawFileMode
                        Case rawFileModeEnum.enumAnalyst
                            rawFileEnumEncoding = "enumAnalyst"
                        Case rawFileModeEnum.enumFinnegan
                            rawFileEnumEncoding = "enumFinnegan"
                        Case rawFileModeEnum.enumMicromass
                            rawFileEnumEncoding = "enumMicromass"
                        Case Else
                            Trace.Assert(False, _
                              "PIL ASSERT. Select Case never fall-through")
                    End Select

                    sfX.WriteElementString( _
                      "rawFileMode", Nothing, _
                      rawFileEnumEncoding)
                End If

                If True Then
                    'We could use reflection here to get the encoding for the enumeration.
                    Dim QuantMSTypesEnumEncoding As String = Nothing 'Keep compiler happy.
                    Select Case anInSettings.MStypes
                        Case QuantMSTypesEnum.enumAllMStypes
                            QuantMSTypesEnumEncoding = "enumAllMStypes"
                        Case QuantMSTypesEnum.enumMS_SIM
                            QuantMSTypesEnumEncoding = "enumMS_SIM"
                        Case QuantMSTypesEnum.enumMSFullScan
                            QuantMSTypesEnumEncoding = "enumMSFullScan"
                        Case Else
                            Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
                    End Select

                    sfX.WriteElementString( _
                      "MStypes", Nothing, _
                      QuantMSTypesEnumEncoding)
                End If 'MStypes

                sfX.WriteElementString( _
                  "TITLEparseDefsCode", Nothing, _
                  anInSettings.TITLEparseDefsCode.ToString())

                sfX.WriteElementString( _
                  "doNotShowDialogAfterParsing", Nothing, _
                  anInSettings.doNotShowDialogAfterParsing.ToString())

                'Changed PM_PERSIST_RECALIBTYPE 2008-02-08
                If True Then
                    'We could use reflection here to get the encoding for the enumeration.
                    Dim recalibDomainEnumEncoding As String = Nothing 'Keep compiler happy.
                    Select Case anInSettings.recalibDomain
                        Case recalibDomainEnum.enumRecalibDomainMass
                            recalibDomainEnumEncoding = "enumRecalibDomainMass"
                        Case recalibDomainEnum.enumRecalibDomainFreq2
                            recalibDomainEnumEncoding = "enumRecalibDomainFreq"
                        Case recalibDomainEnum.enumRecalibDomainTOFtime
                            recalibDomainEnumEncoding = "enumRecalibDomainTOFtime"

                            'Changed PM_ORBI_AWARE_RECALIB 2008-02-14
                        Case recalibDomainEnum.enumRecalibDomainSqrtFreq
                            recalibDomainEnumEncoding = "enumRecalibDomainSqrtFreq"

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

                    sfX.WriteElementString( _
                      "recalibDomain", Nothing, _
                      recalibDomainEnumEncoding)
                End If 'Recalibration domain.
            End If 'Single values, not grouped. 

            If True Then 'Preselected peptides (PSPs).
                SDUP_emptyCommentLine(sfX)
                SDUPcomment(sfX, _
                  "Parameters for which peptides to include in the parse result.", _
                  ssb)
                sfX.WriteStartElement("preselectedPeptides")

                sfX.WriteElementString( _
                  "inclBoldRedPepts", Nothing, _
                  anInSettings.inclBoldRedPepts.ToString())
                sfX.WriteElementString( _
                  "inclLightRedPepts", Nothing, _
                  anInSettings.inclLightRedPepts.ToString())
                sfX.WriteElementString( _
                  "inclRedPeptsIfCheckedOnly", Nothing, _
                  anInSettings.inclRedPeptsIfCheckedOnly.ToString())

                sfX.WriteElementString( _
                  "inclBoldBlackPeptsIfChecked", Nothing, _
                  anInSettings.inclBoldBlackPeptsIfChecked.ToString())
                sfX.WriteElementString( _
                  "inclBoldBlackPepts", Nothing, _
                  anInSettings.inclBoldBlackPepts.ToString())
                sfX.WriteElementString( _
                  "inclPeptsInParens", Nothing, _
                  anInSettings.inclPeptsInParens.ToString())

                'Note: this is output separately, down below.
                'outputPeptideFilter("XYZ", sfX)

                sfX.WriteEndElement() 'For preselectedPeptides
                SDUP_emptyCommentLine(sfX)
            End If 'Preselected peptides (PSPs).

            If True Then 'Validation of preselected peptides (PSPs).
                SDUP_emptyCommentLine(sfX)
                SDUPcomment(sfX, _
                  "For preselected peptides (PSPs): validation (check-mark in Proten Validation window).", _
                  ssb)
                sfX.WriteStartElement("validationOfPreselectedPeptides")

                'Changed PM_VALIDATION_AS_PEPTFILTER 2007-09-05. Now in a peptide
                '  filter.
                'sfX.WriteElementString( _
                '  "peptDefaultValidation", Nothing, _
                '  anInSettings.peptDefaultValidationScoreThr.ToString())
                'sfX.WriteElementString( _
                '  "peptideMaximumRelativeError_PPM", Nothing, _
                '  anInSettings.peptideMaximumRelativeError_PPM.ToString())

                'Perhaps later: "delta score greater than "

                sfX.WriteEndElement() 'For validationOfPreselectedPeptides.
                SDUP_emptyCommentLine(sfX)
            End If 'Validation of preselected peptides (PSPs).

            If True Then 'Classification of preselected peptides (PSPs).
                SDUP_emptyCommentLine(sfX)
                SDUPcomment(sfX, _
                  "For preselected peptides (PSPs): classification into identification uncertain, certain and in-between these two.", _
                  ssb)
                sfX.WriteStartElement("classificationOfPreselectedPeptides")

                sfX.WriteElementString( _
                  "scoreA", Nothing, anInSettings.scoreA.ToString())
                sfX.WriteElementString( _
                  "scoreB", Nothing, anInSettings.scoreB.ToString())
                sfX.WriteElementString( _
                  "scoreC", Nothing, anInSettings.scoreC.ToString())

                sfX.WriteEndElement() 'For classificationOfPreselectedPeptides.
                SDUP_emptyCommentLine(sfX)
            End If 'Classification of preselected peptides (PSPs).

            'Changed PM_DISABLE_OLD_OPTIONS 2007-08-23
            'sfX.WriteElementString( _
            '  "dontShowIPI", Nothing, anInSettings.dontShowIPI.ToString())
            'sfX.WriteElementString( _
            '  "dontShowMosquito", Nothing, anInSettings.dontShowMosquito.ToString())
            'sfX.WriteElementString( _
            '  "dontShowProtWithNoPeptInABC", Nothing, _
            '  anInSettings.dontShowProtWithNoPeptInABC.ToString())

            'Note: names are without "Score" for backward compatibility
            '      reasons.
            '      We could use element names with score here, but
            '      that would complicate the reading code. This however
            '      ought to be done at a later time.

            If True Then
                SDUP_emptyCommentLine(sfX)
                SDUPcomment(sfX, _
                  "Settings for which there is set that must be remembered for each mass spectrometer type.", _
                  ssb)
                sfX.WriteStartElement("vendors") 'One block for each vendor,
                '  currently QSTAR/LTQ-FT/Qtof.
                '
                '  Future:
                '    MS types for quantitation. 

                'Later: in a loop. The fixed values will become the defaults for
                '  some items in a list.

                outputCOMversion( _
                  "QSTAR/Sciex/Analyst", rawFileModeEnum.enumAnalyst, _
                  anInSettings.COMversion, sfX)

                outputCOMversion( _
                  "LTQ-FT/Finnigan/XCalibur", rawFileModeEnum.enumFinnegan, _
                  COMversionEnum.enumXCalibur20SR1, sfX)

                outputCOMversion( _
                  "Qtof/Micromass/MassLynx", rawFileModeEnum.enumMicromass, _
                  COMversionEnum.enumMassLynx40, sfX)

                sfX.WriteEndElement() 'For vendors.
                SDUP_emptyCommentLine(sfX)
            End If

            If True Then
                sfX.WriteStartElement("peptideFilters") 'New section in this 
                '  new XML format. For saving one or more peptide filters.

                Dim hashEnumerator2 As Dictionary( _
                  Of peptideFilterEnum, peptideFilterStructure).Enumerator = _
                    anInSettings.peptideFilters.GetEnumerator()

                While hashEnumerator2.MoveNext()
                    Dim curKey As peptideFilterEnum = hashEnumerator2.Current.Key
                    Dim curValue As peptideFilterStructure = _
                       hashEnumerator2.Current.Value

                    sfX.WriteStartElement("peptideFilter")

                    'Call it something else?
                    sfX.WriteElementString( _
                      "key", Nothing, curKey.ToString())

                    sfX.WriteElementString( _
                      "chargeMin", Nothing, curValue.chargeMin.ToString())
                    sfX.WriteElementString( _
                      "chargeMax", Nothing, curValue.chargeMax.ToString())

                    sfX.WriteElementString( _
                      "seqLengthMin", Nothing, curValue.seqLengthMin.ToString())
                    sfX.WriteElementString( _
                      "seqLengthMax", Nothing, curValue.seqLengthMax.ToString())

                    'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-28
                    sfX.WriteElementString( _
                      "massMin", Nothing, curValue.massMin.ToString())
                    sfX.WriteElementString( _
                      "massMax", Nothing, curValue.massMax.ToString())

                    sfX.WriteElementString( _
                      "highestScoringUniquelyModified", Nothing, _
                      curValue.highestScoringUniquelyModified.ToString())

                    'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-25
                    sfX.WriteElementString( _
                      "scoreMin", Nothing, _
                      curValue.scoreMin.ToString())
                    sfX.WriteElementString( _
                      "scoreMax", Nothing, _
                      curValue.scoreMax2.ToString())
                    sfX.WriteElementString( _
                      "quantifiedOnly", Nothing, _
                      curValue.quantifiedOnly.ToString())
                    sfX.WriteElementString( _
                      "verifiedOnly", Nothing, _
                      curValue.verifiedOnly.ToString())

                    'Changed PM_MASSACC_PEPFILTER 2007-09-05
                    sfX.WriteElementString( _
                      "massAccuracyMin", Nothing, curValue.massAccuracyMin.ToString())
                    sfX.WriteElementString( _
                      "massAccuracyMax", Nothing, curValue.massAccuracyMax.ToString())

                    'Changed PM_RAWFILE_PEPFILTER 2007-11-17
                    sfX.WriteElementString( _
                      "rawFileID", Nothing, _
                      curValue.rawFileID.ToString())

                    If True Then 'Mod list
                        sfX.WriteStartElement("modificationList")

                        Dim modFilter As List(Of Integer) = _
                          curValue.pepModFilter3

                        If Not modFilter Is Nothing Then
                            Dim modID As Integer
                            For Each modID In modFilter
                                sfX.WriteElementString( _
                                  "modID", Nothing, _
                                  modID.ToString())
                            Next 'Through modFilter
                        End If

                        sfX.WriteEndElement() 'For modificationList.
                        SDUP_emptyCommentLine(sfX)
                    End If

                    sfX.WriteEndElement() 'For peptideFilter.
                    SDUP_emptyCommentLine(sfX)
                End While 'Hash iteration.

                sfX.WriteEndElement() 'For peptideFilters.
                SDUP_emptyCommentLine(sfX)
            End If 'Peptide filters.

            If True Then
                SDUP_emptyCommentLine(sfX)
                SDUPcomment(sfX, _
                  "For settings used by the export peptides and proteins function.", _
                  ssb)
                sfX.WriteStartElement("exportSettings")

                sfX.WriteElementString( _
                  "includePeptides", Nothing, _
                  anInSettings.exportSettings.includePeptides.ToString())
                sfX.WriteElementString( _
                  "includeProteinInformation", Nothing, _
                  anInSettings.exportSettings.includeProteinInformation2.ToString())

                'Changed PM_SPECTRAEXPORT_GENERALISED 2008-05-05
                sfX.WriteElementString( _
                  "includeSpectra", Nothing, _
                  anInSettings.exportSettings.includeSpectra.ToString())


                sfX.WriteEndElement() 'For exportSettings.
                SDUP_emptyCommentLine(sfX)
            End If

            'Changed PM_HIDE_RECALIBVISUALISATION_WINDOW 2008-01-06
            If True Then 'Action at the end of parse.
                SDUP_emptyCommentLine(sfX)
                SDUPcomment(sfX, _
                  "Options for what happens at the end of the parse, " & _
                  "e.g. whether or not the recalibration visualisation " & _
                  "window should be opened.", _
                  ssb)
                sfX.WriteStartElement("endOfParseActions")

                Dim act As endOfParseActionStructure = anInSettings.endOfParseAction

                sfX.WriteElementString( _
                  "openRecalibrationVisualisationWindow", Nothing, _
                  act.openRecalibrationVisualisationWindow.ToString())

                sfX.WriteEndElement() 'For endOfParseActions.
                SDUP_emptyCommentLine(sfX)
            End If 'Classification of preselected peptides (PSPs).

            sfX.WriteElementString( _
              "checkSum", Nothing, _
              anInSettings.checkSum.ToString())

            'Changed PM_QUANT_ALL 2007-10-12
            sfX.WriteElementString( _
              "extra", Nothing, _
              anInSettings.extra2.ToString())

            sfX.WriteEndElement() 'For MascotParserOptionsStruct2
            SDUP_emptyCommentLine(sfX)

            SDUP_emptyCommentLine(sfX)
            SDUP_emptyCommentLine(sfX)

            sfX.Flush()
            sfX.Close()
        End Sub 'PersistOptionsSettings


        '****************************************************************************
        '*    M I S C   O P T I O N S  ,   B E G I N                                *
        '****************************************************************************


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Function MassFunction_read( _
                    ByVal aFieldName As String, _
                    ByVal aDefaultValue As massWindowFunctionEnum, _
                    ByRef anInStruHandle As System.Xml.XmlNode) _
                    As massWindowFunctionEnum

            Dim toReturn As massWindowFunctionEnum = aDefaultValue

            Dim enumStr As String = Nothing 'Keep compiler happy.

            'Changed PM_IGNORED_MISCOPTIONS_BUG 2007-06-06. The level
            'is now different and new/old versions of the settings
            'file have different levels.
            'Dim xpathSpec As String = aFieldName
            Dim xpathSpec As String = "//" & aFieldName

            MSQuantCommon2.extractStringFromXmlNode( _
              anInStruHandle, mOptionsNsManager, xpathSpec, _
              enumStr)

            Select Case enumStr
                Case "enumConstantMass"
                    toReturn = massWindowFunctionEnum.enumConstantMass
                Case "enumSquareMass"
                    toReturn = massWindowFunctionEnum.enumSquareMass
                Case Else
                    'If it does not exist then we use the default.
            End Select

            'Changed PM_RETURN_VALUE_CHECK_MARKER 2005-07-12 !!!!!!!!!!!!!!!!!!!!!!!!
            'How to the let compiler check that there is a return
            'statement at the end???????

            Return toReturn
        End Function 'readMassFunction


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub loadMiscSettings(ByVal aFileName4 As String)

            'Changed PM_OPTIONSFILES_ONLYINBIN 2004-01-28
            Dim fileNameFullPath As String = _
              MSQuantCommon2.fullPathToFileInApplicationFolder(aFileName4)

            mMiscOptionsFileName_FullPath = fileNameFullPath

            Trace.Assert(MSQuantCommon2.isFullPathFileName( _
              mMiscOptionsFileName_FullPath), _
              "PIL ASSERT. Options file is not a full path name: " & _
              mMiscOptionsFileName_FullPath)

            defaultMiscSettings(mMiscSettings) 'This will fill in
            '  all fields, also those that may NOT be in the options file.
            '  This will be the case when the options file was created by 
            '  an older version of the program.

            'Old SOAP XML way...
            ' Dim defaultXML2 As String = _
            '   "<SOAP-ENV:Envelope   " & ControlChars.NewLine & _
            '   "    xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""                " & ControlChars.NewLine & _
            '   "    xmlns:xsd=""http://www.w3.org/2001/XMLSchema""                         " & ControlChars.NewLine & _
            '   "    xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/""           " & ControlChars.NewLine & _
            '   "    xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/""           " & ControlChars.NewLine & _
            '   "    xmlns:clr=""http://schemas.microsoft.com/soap/encoding/clr/1.0""       " & ControlChars.NewLine & _
            '   "    SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">  " & ControlChars.NewLine & _
            '   "  <SOAP-ENV:Body>                                                        " & ControlChars.NewLine & _
            '   "    <a1:miscSettingsStructure id=""ref-1""                                 " & ControlChars.NewLine & _
            '   "        xmlns:a1=""http://schemas.microsoft.com/clr/nsassem/massSpectrometryBase/Mascot%20Parser%2C%20Version%3D1.0.1419.18653%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"">  " & ControlChars.NewLine & _
            '   "                                  " & ControlChars.NewLine & _
            '   "    </a1:miscSettingsStructure>   " & ControlChars.NewLine & _
            '   "  </SOAP-ENV:Body>                " & ControlChars.NewLine & _
            '   "</SOAP-ENV:Envelope>              " & ControlChars.NewLine
            ' 
            ' Dim NSSpec2 As String = _
            '   "http://schemas.microsoft.com/clr/nsassem/massSpectrometryBase/Mascot%20Parser%2C%20Version%3D1.0.1419.18653%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"

            'Changed PM_MISCOPTIONS_SIMPLE_XML 2007-05-03
            Dim fileDidNotExist2 As Boolean = _
              Not File.Exists(fileNameFullPath)

            'Changed PM_MISCOPTIONS_SIMPLE_XML 2007-05-03
            'Note: we must test for existence as optionsFileLoad() will fail 
            '      in the way we use it now.
            If fileDidNotExist2 Then

                'Moved up here.

                'If file did not exist:
                'Persist the default instead such that the configuration
                'file is always created if it does not exist.

                'Changed PM_MISCOPTIONS_SIMPLE_XML 2007-05-02
                'old_PersistMiscSettings()
                PersistMiscSettings( _
                  mMiscOptionsFileName_FullPath, _
                  mMiscSettings)
            Else
                'Changed PM_MISCOPTIONS_SIMPLE_XML 2007-05-03
                'Dim struHandle As System.Xml.XmlNode = _
                '  MSQuantCommon2.optionsFileLoad( _
                '    fileNameFullPath, "miscSettingsStructure", 600, _
                '    defaultXML2, NSSpec, mMiscSettingsDOM, mMiscSettingsNsManager, _
                '    dummyFileDidNotExist)
                '
                'For misc settings.
                Dim dummyFileDidNotExist7 As Boolean

                Try
                    'From loadMiscSettings().
                    Dim struHandle As System.Xml.XmlNode = _
                      MSQuantCommon2.optionsFileLoad( _
                        fileNameFullPath, "/", 1300, _
                        "", "", mMiscSettingsDOM, mMiscSettingsNsManager, _
                        dummyFileDidNotExist7)

                    'Why don't we use the more robust way below instead of the less
                    'robust "deep" thingy further below??
                    '
                    'Dim struc2 As XmlNode = _
                    '  struHandle.SelectSingleNode( _
                    '     "//miscSettingsStructure" _
                    '    )

                    'Changed PM_FINNIGAN_QUANTWINDOW_RELATIVE 2005-07-12
                    ''Changed PM_VARIABLE_XIC_WINDOW_INSTRUMENTSPECIFIC 2004-06-29
                    ''Dim fileDidNotExist As Boolean = struHandle.SelectSingleNode( _
                    ''  "absoluteMassWindowForXIC", mMiscSettingsNsManager) Is Nothing
                    'Dim fileDidNotExist As Boolean = struHandle.SelectSingleNode( _
                    '  "absoluteMassWindowForXIC_QSTAR", mMiscSettingsNsManager) Is Nothing

                    'Old SOAP XML way...
                    ' Dim fileDidNotExist8 As Boolean = struHandle.SelectSingleNode( _
                    '   "massWindowForXIC_QSTAR", mMiscSettingsNsManager) Is Nothing

                    'Changed PM_FINNIGAN_QUANTWINDOW_RELATIVE 2005-07-12. Old way.
                    ''Changed PM_VARIABLE_XIC_WINDOW_INSTRUMENTSPECIFIC 2004-06-29. We no longer
                    ''load this value...
                    'MSQuantCommon2.extractDoubleFromXmlNode( _
                    '  struHandle, mMiscSettingsNsManager, _
                    '  "absoluteMassWindowForXIC_QSTAR", _
                    '  mMiscSettings.absoluteMassWindowForXIC_QSTAR)
                    'MSQuantCommon2.extractDoubleFromXmlNode( _
                    '  struHandle, mMiscSettingsNsManager, _
                    '  "absoluteMassWindowForXIC_LTQFT", _
                    '  mMiscSettings.absoluteMassWindowForXIC_LTQFT)
                    'MSQuantCommon2.extractDoubleFromXmlNode( _
                    '  struHandle, mMiscSettingsNsManager, _
                    '  "absoluteMassWindowForXIC_Qtof", _
                    '  mMiscSettings.absoluteMassWindowForXIC_Qtof)

                    'Changed PM_IGNORED_MISCOPTIONS_BUG 2007-06-06
                    'Note: we must use the new deep versions as we are no
                    '      longer loading at the same level as before (now 
                    '      from the top, was at level "miscSettingsStructure")
                    '      and for the new format the fields are now one level
                    '      lower, down in <instrument>.

                    'QSTAR
                    MSQuantCommon2.extractDoubleFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "massWindowForXIC_QSTAR", _
                      mMiscSettings.QSTARsettingsXIC.massWindowForXIC2)
                    MSQuantCommon2.extractDoubleFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "massForMassWindow_QSTAR", _
                      mMiscSettings.QSTARsettingsXIC.massForMassWindow)
                    mMiscSettings.QSTARsettingsXIC.massWindowFunction = _
                      Me.MassFunction_read( _
                        "massWindowFunction_QSTAR", _
                        massWindowFunctionEnum.enumConstantMass, _
                        struHandle)
                    'Changed PM_USERDEFINED_QUANT_THRESHOLD 2006-11-10
                    MSQuantCommon2.extractDoubleFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "quantThreshold_QSTAR", _
                      mMiscSettings.QSTARsettingsXIC.quantThreshold)

                    'Finnigan
                    'MSQuantCommon2.extractDoubleFromXmlNode( _
                    '  struHandle, mMiscSettingsNsManager, _
                    '  "massWindowForXIC_LTQFT", _
                    '  mMiscSettings.LTQFTsettingsXIC.massWindowForXIC2)
                    MSQuantCommon2.extractDoubleFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "massWindowForXIC_LTQFT", _
                      mMiscSettings.LTQFTsettingsXIC.massWindowForXIC2)
                    MSQuantCommon2.extractDoubleFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "massForMassWindow_LTQFT", _
                      mMiscSettings.LTQFTsettingsXIC.massForMassWindow)
                    mMiscSettings.LTQFTsettingsXIC.massWindowFunction = _
                      Me.MassFunction_read( _
                        "massWindowFunction_LTQFT", _
                        massWindowFunctionEnum.enumSquareMass, _
                        struHandle)
                    'Changed PM_USERDEFINED_QUANT_THRESHOLD 2006-11-10
                    MSQuantCommon2.extractDoubleFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "quantThreshold_LTQFT", _
                      mMiscSettings.LTQFTsettingsXIC.quantThreshold)

                    'Micromass
                    MSQuantCommon2.extractDoubleFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "massWindowForXIC_Qtof", _
                      mMiscSettings.QtofsettingsXIC.massWindowForXIC2)
                    MSQuantCommon2.extractDoubleFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "massForMassWindow_Qtof", _
                      mMiscSettings.QtofsettingsXIC.massForMassWindow)
                    mMiscSettings.QtofsettingsXIC.massWindowFunction = _
                      Me.MassFunction_read( _
                        "massWindowFunction_Qtof", _
                        massWindowFunctionEnum.enumConstantMass, _
                        struHandle)
                    'Changed PM_USERDEFINED_QUANT_THRESHOLD 2006-11-10
                    MSQuantCommon2.extractDoubleFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "quantThreshold_Qtof", _
                      mMiscSettings.QtofsettingsXIC.quantThreshold)

                    ''Note: read-only... (- normal write is in Sub PersistMiscSettings())
                    'MSQuantCommon2.extractIntegerFromXmlNode_deep( _
                    '  struHandle, mMiscSettingsNsManager, _
                    '      "option1", _
                    '  mMiscSettings.option1)
                    ''mMiscSettings.option1 = 1 'Override...

                    MSQuantCommon2.extractIntegerFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "maxDisplayedPTMcombinations", _
                      mMiscSettings.maxDisplayedPTMcombinations2)
                    MSQuantCommon2.extractDoubleFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "PTMminimumScore", _
                      mMiscSettings.PTMminimumScore)
                    MSQuantCommon2.extractDoubleFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "minimumPTMdeltaScore", _
                      mMiscSettings.minimumPTMdeltaScore)

                    'Changed PM_LIMIT_PTMCOMBINATIONS 2008-01-15
                    MSQuantCommon2.extractDoubleFromXmlNode_deep( _
                      struHandle, mMiscSettingsNsManager, _
                      "maxCombinations", _
                      mMiscSettings.maxCombinations)


                    Dim TITLElineDefs As TITLElineDefinitions = _
                      New TITLElineDefinitions()

                    'Changed PM_READ_TITLELINEDEFINITIONS 2008-02-07
                    If True Then 'Newer, non-flat structures. In fact it is 
                        '  required as we have lists of line parsing definitions
                        '  and each definition has a list of items.

                        Dim newMiscOptionsHandle As System.Xml.XmlNode = _
                          struHandle.SelectSingleNode( _
                            "//miscSettingsStructure", mOptionsNsManager)

                        Dim titleLinesHandle As System.Xml.XmlNodeList = _
                          newMiscOptionsHandle.SelectNodes( _
                            "TITLElineParseDefinitions/parseFormat", mOptionsNsManager)

                        Dim someNode2 As System.Xml.XmlNode
                        For Each someNode2 In titleLinesHandle

                            Dim someTITLElineItem As TITLElineParsingStructure
                            'asdad() 'Compiler warnings below,
                            '  TITLElineDefs.addItem2(someTITLElineItem). Use
                            '  getTITLElineParseDef() (or refactor it) ?

                            someTITLElineItem.formatName = Nothing
                            MSQuantCommon2.extractStringFromXmlNode( _
                              someNode2, mMiscSettingsNsManager, "formatName", _
                              someTITLElineItem.formatName)

                            MSQuantCommon2.extractIntegerFromXmlNode( _
                              someNode2, mMiscSettingsNsManager, _
                              "formatID", _
                              someTITLElineItem.ID3)

                            MSQuantCommon2.extractIntegerFromXmlNode( _
                              someNode2, mMiscSettingsNsManager, _
                              "GUInameIndex", _
                              someTITLElineItem.GUInameIndex2)

                            Dim parseItemsHandle As System.Xml.XmlNodeList = _
                              someNode2.SelectNodes( _
                                "parseItem", mOptionsNsManager)
                            Dim someParseItemNode As System.Xml.XmlNode
                            For Each someParseItemNode In parseItemsHandle

                                Dim someParseMatchItem As parseMatchItemStructure

                                Dim parseItemName As String = Nothing
                                MSQuantCommon2.extractStringFromXmlNode( _
                                  someParseItemNode, mMiscSettingsNsManager, _
                                  "itemName", _
                                  parseItemName)

                                someParseMatchItem.regularExpression = Nothing
                                MSQuantCommon2.extractStringFromXmlNode( _
                                  someParseItemNode, mMiscSettingsNsManager, _
                                  "regularExpression", _
                                  someParseMatchItem.regularExpression)

                                MSQuantCommon2.extractDoubleFromXmlNode( _
                                  someParseItemNode, mMiscSettingsNsManager, _
                                  "offset", _
                                  someParseMatchItem.offset)

                                'Note: there is no defaultComment field in 
                                '  the XML. It is a helper field to write out
                                '  XML comments during ***writing*** of the options
                                '  file.
                                someParseMatchItem.defaultComment = "XYZ"

                                Select Case parseItemName
                                    Case "retentionTime"
                                        someTITLElineItem.retentionTime3 = _
                                          someParseMatchItem

                                    Case "experiment"
                                        someTITLElineItem.experiment3 = _
                                          someParseMatchItem

                                    Case "cycles"
                                        someTITLElineItem.cycles3 = _
                                          someParseMatchItem

                                    Case "rawFileOrPeriod"
                                        'Note: this is for backward compatibilty
                                        '  only (reading options file generated 
                                        '  with older versions of the program); 
                                        '  the field was renamed to rawFile.
                                        someTITLElineItem.rawFile3 = _
                                          someParseMatchItem

                                    Case "rawFile"
                                        'Changed PM_RAWFILEORPERIOD_DEPRECATED 2008-02-08.
                                        'New name for this field/content - raw file
                                        'name.
                                        someTITLElineItem.rawFile3 = _
                                          someParseMatchItem

                                    Case "scanNumber"
                                        someTITLElineItem.scanNumber3 = _
                                          someParseMatchItem

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

                            Next 'Through parse items (for a single MGF file
                            '  generator item.)

                            TITLElineDefs.addItem2(someTITLElineItem)
                        Next 'Through titleLinesHandle. One for each MGF file generator. 

                    End If 'Block. Newer, non-flat structures. For new_MiscOptions.xml.
                    If TITLElineDefs.getDefinitions() > 0 Then
                        mMiscSettings.TITLElineDefs = TITLElineDefs
                    Else
                        'Older settings file, does not contain TITLE line definitions.
                        Dim peter2 As Integer = 2
                    End If

                Catch exceptionObject As Exception
                    Dim cr As String = ControlChars.NewLine 'Shortcut..
                    Dim extraInfo As String = _
                      "Reading of misc. options file, " & _
                      fileNameFullPath & ",  failed. " & _
                      cr & _
                      cr
                    MSQuantCommon2.displayStandardExceptionInfo( _
                      exceptionObject, _
                      extraInfo)
                    Exit Sub
                End Try
            End If 'Else, option file already exists


            'Old. Which one should we use?
            ' Try
            ' 
            ' Catch e2 As Exception
            '     MsgBox("Could load settings from options file " & fileNameFullPath & _
            '       ". Using default values instead." & ControlChars.NewLine & ControlChars.NewLine & _
            '       "Some details, exception: " & e2.Message & "..........")
            ' End Try
        End Sub 'loadMiscSettings


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Sub writeMassFunction( _
          ByVal aFieldName As String, _
          ByVal aMassWindowFunction As massWindowFunctionEnum, _
          ByRef anInXpathSpec As String)

            'We could use reflection here to get the encoding for the enumeration.
            Dim massFunctionEnumEncoding As String = Nothing 'Keep compiler happy.
            Select Case aMassWindowFunction
                Case massWindowFunctionEnum.enumConstantMass
                    massFunctionEnumEncoding = "enumConstantMass"
                Case massWindowFunctionEnum.enumSquareMass
                    massFunctionEnumEncoding = "enumSquareMass"
                Case Else
                    Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
            End Select
            insertOrOverwriteSetting( _
              mMiscSettingsDOM, mMiscSettingsNsManager, anInXpathSpec, _
              massFunctionEnumEncoding, aFieldName)
        End Sub 'writeMassFunction


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub old_PersistMiscSettings()

            Dim xpathSpec As String = _
              MSQuantCommon2.construct_xPathSpec("miscSettingsStructure")

            If False Then 'Test only, should be false...
                insertOrOverwriteSetting( _
                  mMiscSettingsDOM, mMiscSettingsNsManager, _
                  xpathSpec, _
                  "77.777777", _
                  "someExtraField")

                'Test only!!!!
                insertOrOverwriteSetting( _
                  mMiscSettingsDOM, mMiscSettingsNsManager, _
                  xpathSpec, _
                  "671212000.1", _
                  "absoluteMassWindowForXIC")
                insertOrOverwriteSetting( _
                  mMiscSettingsDOM, mMiscSettingsNsManager, _
                  xpathSpec, _
                  "888.8", _
                  "absoluteMassWindowForXIC")
            End If

            'Changed PM_VARIABLE_XIC_WINDOW_INSTRUMENTSPECIFIC 2004-06-29
            'We no longer save it....
            'insertOrOverwriteSetting( _
            '  mMiscSettingsDOM, mMiscSettingsNsManager, _
            '  xpathSpec, _
            '  mMiscSettings.absoluteMassWindowForXIC.ToString(), _
            '  "absoluteMassWindowForXIC")

            'Changed PM_FINNIGAN_QUANTWINDOW_RELATIVE 2005-07-12. Old way.
            ''Changed PM_VARIABLE_XIC_WINDOW_INSTRUMENTSPECIFIC 2004-06-29
            'insertOrOverwriteSetting( _
            '  mMiscSettingsDOM, mMiscSettingsNsManager, _
            '  xpathSpec, _
            '  mMiscSettings.absoluteMassWindowForXIC_QSTAR.ToString(), _
            '  "absoluteMassWindowForXIC_QSTAR")
            'insertOrOverwriteSetting( _
            '  mMiscSettingsDOM, mMiscSettingsNsManager, _
            '  xpathSpec, _
            '  mMiscSettings.absoluteMassWindowForXIC_LTQFT.ToString(), _
            '  "absoluteMassWindowForXIC_LTQFT")
            'insertOrOverwriteSetting( _
            '  mMiscSettingsDOM, mMiscSettingsNsManager, _
            '  xpathSpec, _
            '  mMiscSettings.absoluteMassWindowForXIC_Qtof.ToString(), _
            '  "absoluteMassWindowForXIC_Qtof")

            'QSTAR
            insertOrOverwriteSetting( _
              mMiscSettingsDOM, mMiscSettingsNsManager, _
              xpathSpec, _
              mMiscSettings.QSTARsettingsXIC.massWindowForXIC2.ToString(), _
              "massWindowForXIC_QSTAR")
            insertOrOverwriteSetting( _
              mMiscSettingsDOM, mMiscSettingsNsManager, _
              xpathSpec, _
              mMiscSettings.QSTARsettingsXIC.massForMassWindow.ToString(), _
              "massForMassWindow_QSTAR")
            'insertOrOverwriteSetting( _
            '  mMiscSettingsDOM, mMiscSettingsNsManager, _
            '  xpathSpec, _
            '  mMiscSettings.QSTARsettingsXIC.massWindowFunction.ToString(), _
            '  "massWindowFunction_QSTAR")
            Me.writeMassFunction( _
              "massWindowFunction_QSTAR", _
              mMiscSettings.QSTARsettingsXIC.massWindowFunction, _
              xpathSpec)
            'Changed PM_USERDEFINED_QUANT_THRESHOLD 2006-11-10
            insertOrOverwriteSetting( _
              mMiscSettingsDOM, mMiscSettingsNsManager, _
              xpathSpec, _
              mMiscSettings.QSTARsettingsXIC.quantThreshold.ToString(), _
              "quantThreshold_QSTAR")


            'Finnigan
            insertOrOverwriteSetting( _
              mMiscSettingsDOM, mMiscSettingsNsManager, _
              xpathSpec, _
              mMiscSettings.LTQFTsettingsXIC.massWindowForXIC2.ToString(), _
              "massWindowForXIC_LTQFT")
            insertOrOverwriteSetting( _
              mMiscSettingsDOM, mMiscSettingsNsManager, _
              xpathSpec, _
              mMiscSettings.LTQFTsettingsXIC.massForMassWindow.ToString(), _
              "massForMassWindow_LTQFT")
            'insertOrOverwriteSetting( _
            '  mMiscSettingsDOM, mMiscSettingsNsManager, _
            '  xpathSpec, _
            '  mMiscSettings.LTQFTsettingsXIC.massWindowFunction.ToString(), _
            '  "massWindowFunction_LTQFT")
            Me.writeMassFunction( _
              "massWindowFunction_LTQFT", _
              mMiscSettings.LTQFTsettingsXIC.massWindowFunction, _
              xpathSpec)
            'Changed PM_USERDEFINED_QUANT_THRESHOLD 2006-11-10
            insertOrOverwriteSetting( _
              mMiscSettingsDOM, mMiscSettingsNsManager, _
              xpathSpec, _
              mMiscSettings.LTQFTsettingsXIC.quantThreshold.ToString(), _
              "quantThreshold_LTQFT")

            'Micromass
            insertOrOverwriteSetting( _
              mMiscSettingsDOM, mMiscSettingsNsManager, _
              xpathSpec, _
              mMiscSettings.QtofsettingsXIC.massWindowForXIC2.ToString(), _
              "massWindowForXIC_Qtof")
            insertOrOverwriteSetting( _
              mMiscSettingsDOM, mMiscSettingsNsManager, _
              xpathSpec, _
              mMiscSettings.QtofsettingsXIC.massForMassWindow.ToString(), _
              "massForMassWindow_Qtof")
            'insertOrOverwriteSetting( _
            '  mMiscSettingsDOM, mMiscSettingsNsManager, _
            '  xpathSpec, _
            '  mMiscSettings.QtofsettingsXIC.massWindowFunction.ToString(), _
            '  "massWindowFunction_Qtof")
            Me.writeMassFunction( _
              "massWindowFunction_Qtof", _
              mMiscSettings.QtofsettingsXIC.massWindowFunction, _
              xpathSpec)
            'Changed PM_USERDEFINED_QUANT_THRESHOLD 2006-11-10
            insertOrOverwriteSetting( _
              mMiscSettingsDOM, mMiscSettingsNsManager, _
              xpathSpec, _
              mMiscSettings.QtofsettingsXIC.quantThreshold.ToString(), _
              "quantThreshold_Qtof")


            If True Then 'PTM stuff
                'Changed PM_PHOSPHO_SCORING 2006-01-09
                insertOrOverwriteSetting( _
                  mMiscSettingsDOM, mMiscSettingsNsManager, _
                  xpathSpec, _
                  mMiscSettings.maxDisplayedPTMcombinations2.ToString(), _
                  "maxDisplayedPTMcombinations")
                insertOrOverwriteSetting( _
                  mMiscSettingsDOM, mMiscSettingsNsManager, _
                  xpathSpec, _
                  mMiscSettings.PTMminimumScore.ToString("0.000"), _
                  "PTMminimumScore")
                insertOrOverwriteSetting( _
                  mMiscSettingsDOM, mMiscSettingsNsManager, _
                  xpathSpec, _
                  mMiscSettings.minimumPTMdeltaScore.ToString(), _
                  "minimumPTMdeltaScore")

                'Changed PM_LIMIT_PTMCOMBINATIONS 2008-01-15
                insertOrOverwriteSetting( _
                  mMiscSettingsDOM, mMiscSettingsNsManager, _
                  xpathSpec, _
                  mMiscSettings.maxCombinations.ToString(), _
                  "maxCombinations")
            End If

            'Changed PM_OPTIONSFILES_ONLYINBIN 2004-01-28
            Trace.Assert( _
                MSQuantCommon2.isFullPathFileName(mMiscOptionsFileName_FullPath), _
              "PIL ASSERT. Options file is not a full path name: " & _
              mMiscOptionsFileName_FullPath)

            'Will use the SOAP formatter...
            mMiscSettingsDOM.Save(mMiscOptionsFileName_FullPath)
        End Sub 'old_PersistMiscSettings


        'Changed PM_TITLELINEPARSING_WRITEOUT 2007-06-11
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Shared Sub outputParseItem( _
          ByRef anInItemName As String, _
          ByVal aSomeItem As parseMatchItemStructure, _
          ByRef anInOutWr As XmlTextWriter, _
          ByRef anInOutScratch As StringBuilder)

            anInOutWr.WriteStartElement("parseItem")

            SDUPcomment(anInOutWr, aSomeItem.defaultComment, anInOutScratch)

            'Should it be an enum instead??
            anInOutWr.WriteElementString( _
              "itemName", Nothing, _
              anInItemName)

            anInOutWr.WriteElementString( _
              "regularExpression", Nothing, _
              aSomeItem.regularExpression)

            anInOutWr.WriteElementString( _
              "offset", Nothing, _
              aSomeItem.offset.ToString())

            anInOutWr.WriteEndElement() 'For parseItem

            SDUP_emptyCommentLine(anInOutWr)
        End Sub 'outputParseItem


        'Changed PM_MISCOPTIONS_SIMPLE_XML 2007-05-02
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub PersistMiscSettings( _
          ByRef anInPersist_fileNameFullPath As String, _
          ByRef anInSettings As miscSettingsStructure2Struct)

            'Changed PM_XMLCOMMENTS_LINEBREAK 2008-02-08
            Dim ssb As StringBuilder = New StringBuilder(100)

            Dim sfX As XmlTextWriter = _
              MSQuantCommon2.newStandardXMLout( _
                anInPersist_fileNameFullPath, Nothing, Nothing, _
                quantApplication.versionString_withDate())

            SDUP_emptyCommentLine(sfX)

            SDUPcomment(sfX, _
              "Changed: 2007-05-02 PM  Initial version of this non-SOAP formatted file.", _
              ssb)
            SDUPcomment(sfX, _
              "Changed: 2007-05-03 PM  New standard comment header.", ssb)
            SDUPcomment(sfX, "Changed: 2007-xx-xx PM", ssb)

            SDUP_emptyCommentLine(sfX)

            'Perhaps later:
            '  list of instruments/more structured XML document. There
            '  would be a problem with backward compatibility.

            sfX.WriteStartElement("miscSettingsStructure")

            sfX.WriteStartElement("quantitationSettings")

            If True Then 'QSTAR
                SDUP_emptyCommentLine(sfX)
                SDUP_emptyCommentLine(sfX)
                SDUPcomment(sfX, "QSTAR/Sciex/Analyst", ssb)
                sfX.WriteStartElement("instrument")

                sfX.WriteElementString( _
                  "massWindowForXIC_QSTAR", Nothing, _
                  anInSettings.QSTARsettingsXIC.massWindowForXIC2.ToString())

                sfX.WriteElementString( _
                  "massForMassWindow_QSTAR", Nothing, _
                  anInSettings.QSTARsettingsXIC.massForMassWindow.ToString())

                sfX.WriteElementString( _
                  "massWindowFunction_QSTAR", Nothing, _
                  anInSettings.QSTARsettingsXIC.massWindowFunction.ToString())

                sfX.WriteElementString( _
                  "quantThreshold_QSTAR", Nothing, _
                  anInSettings.QSTARsettingsXIC.quantThreshold.ToString())

                sfX.WriteEndElement() 'For instrument
            End If

            If True Then 'Finnigan
                SDUP_emptyCommentLine(sfX)
                SDUP_emptyCommentLine(sfX)
                SDUPcomment(sfX, "LTQ-FT/Finnigan/XCalibur", ssb)
                sfX.WriteStartElement("instrument")

                sfX.WriteElementString( _
                  "massWindowForXIC_LTQFT", Nothing, _
                  anInSettings.LTQFTsettingsXIC.massWindowForXIC2.ToString())

                sfX.WriteElementString( _
                  "massForMassWindow_LTQFT", Nothing, _
                  anInSettings.LTQFTsettingsXIC.massForMassWindow.ToString())
                sfX.WriteElementString( _
                  "massWindowFunction_LTQFT", Nothing, _
                  anInSettings.LTQFTsettingsXIC.massWindowFunction.ToString())
                sfX.WriteElementString( _
                  "quantThreshold_LTQFT", Nothing, _
                  anInSettings.LTQFTsettingsXIC.quantThreshold.ToString())

                sfX.WriteEndElement() 'For instrument
            End If

            If True Then
                SDUP_emptyCommentLine(sfX)
                SDUP_emptyCommentLine(sfX)
                SDUPcomment(sfX, "Qtof/Micromass/MassLynx", ssb)
                sfX.WriteStartElement("instrument")

                sfX.WriteElementString( _
                  "massWindowForXIC_Qtof", Nothing, _
                  anInSettings.QtofsettingsXIC.massWindowForXIC2.ToString())

                sfX.WriteElementString( _
                  "massForMassWindow_Qtof", Nothing, _
                  anInSettings.QtofsettingsXIC.massForMassWindow.ToString())
                sfX.WriteElementString( _
                  "massWindowFunction_Qtof", Nothing, _
                  anInSettings.QtofsettingsXIC.massWindowFunction.ToString())
                sfX.WriteElementString( _
                  "quantThreshold_Qtof", Nothing, _
                  anInSettings.QtofsettingsXIC.quantThreshold.ToString())

                sfX.WriteEndElement() 'For instrument
            End If

            sfX.WriteEndElement() 'For quantitationSettings

            SDUP_emptyCommentLine(sfX)
            SDUP_emptyCommentLine(sfX)

            If True Then 'PTM stuff
                sfX.WriteStartElement("PTMscoreSettings")

                sfX.WriteElementString( _
                  "PTMminimumScore", Nothing, _
                  anInSettings.PTMminimumScore.ToString("0.000"))

                sfX.WriteElementString( _
                  "maxDisplayedPTMcombinations", Nothing, _
                 anInSettings.maxDisplayedPTMcombinations2.ToString())

                sfX.WriteElementString( _
                  "minimumPTMdeltaScore", Nothing, _
                  anInSettings.minimumPTMdeltaScore.ToString())

                sfX.WriteElementString( _
                  "maxCombinations", Nothing, _
                  anInSettings.maxCombinations.ToString())

                sfX.WriteEndElement() 'For PTMscoreSettings
                SDUP_emptyCommentLine(sfX)
                SDUP_emptyCommentLine(sfX)
            End If

            'Changed PM_TITLELINEPARSING_WRITEOUT 2007-06-11
            If True Then 'TITLE parsing stuff
                sfX.WriteStartElement("TITLElineParseDefinitions")

                'We could get them in any order... But least it will be in
                'same the order as in the user interface.
                Dim tList As List(Of TITLElineParsingStructure) = _
                  anInSettings.TITLElineDefs.getTITLEdefs_GUIIndexOrder()

                Dim someItem As TITLElineParsingStructure
                For Each someItem In tList

                    sfX.WriteStartElement("parseFormat")

                    'Changed PM_PARSEFORMAT_OVERALL_COMMENT 2008-02-08
                    SDUPcomment(sfX, someItem.parseFormatComments, ssb)

                    sfX.WriteElementString( _
                      "formatName", Nothing, _
                      someItem.formatName)

                    sfX.WriteElementString( _
                      "formatID", Nothing, _
                      someItem.ID3.ToString())

                    sfX.WriteElementString( _
                      "GUInameIndex", Nothing, _
                      someItem.GUInameIndex2.ToString())
                    SDUP_emptyCommentLine(sfX)

                    outputParseItem( _
                      "retentionTime", someItem.retentionTime3, sfX, ssb)
                    outputParseItem("experiment", someItem.experiment3, sfX, ssb)
                    outputParseItem("cycles", someItem.cycles3, sfX, ssb)

                    'Changed PM_RAWFILEORPERIOD_DEPRECATED 2008-02-08
                    'outputParseItem("rawFileOrPeriod", someItem.rawFile3, sfX, ssb)
                    outputParseItem("rawFile", someItem.rawFile3, sfX, ssb)

                    'Changed PM_TITLELINEPARSING 2007-06-14
                    outputParseItem("scanNumber", someItem.scanNumber3, sfX, ssb)

                    sfX.WriteEndElement() 'For parseFormat
                    SDUP_emptyCommentLine(sfX)
                    SDUP_emptyCommentLine(sfX)
                Next

                sfX.WriteEndElement() 'For TITLElineParseDefinitions
                SDUP_emptyCommentLine(sfX)
                SDUP_emptyCommentLine(sfX)
            End If

            sfX.WriteEndElement() 'For miscSettingsStructure

            SDUP_emptyCommentLine(sfX)
            SDUP_emptyCommentLine(sfX)

            sfX.Flush()
            sfX.Close()
        End Sub 'PersistMiscSettings


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function getMiscSettings() As miscSettingsStructure2Struct

            Return mMiscSettings
        End Function 'getMiscSettings


        'Changed PM_REFACTOR_TITLELINEPARSING 2007-06-08
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub patchSomeFields(ByVal anInRawFileMode As rawFileModeEnum)

            'Changed PM_VARIABLE_XIC_WINDOW_INSTRUMENTSPECIFIC 2004-06-29
            Select Case anInRawFileMode
                Case rawFileModeEnum.enumAnalyst
                    mMiscSettings.currentXICwindowSetings = _
                      mMiscSettings.QSTARsettingsXIC
                Case rawFileModeEnum.enumFinnegan
                    mMiscSettings.currentXICwindowSetings = _
                      mMiscSettings.LTQFTsettingsXIC
                Case rawFileModeEnum.enumMicromass
                    mMiscSettings.currentXICwindowSetings = _
                      mMiscSettings.QtofsettingsXIC
                Case Else
                    Trace.Assert(False, "PIL ASSERT. Select Case never fall-through")
            End Select
        End Sub 'patchSomeFields


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '*   Note: anOutDouble is ***unchanged*** if the field does not exist!
        '****************************************************************************
        Private Shared Sub insertOrOverwriteSetting( _
          ByVal aSettingsDOM As System.Xml.XmlDocument, _
          ByRef anInNameSpaceManager As System.Xml.XmlNamespaceManager, _
          ByVal aContainerToInsertInSpec As String, _
          ByVal aValue As String, _
          ByVal aFieldName As String _
          )

            Dim containerHandle As System.Xml.XmlNode = _
              aSettingsDOM.SelectSingleNode( _
                aContainerToInsertInSpec, anInNameSpaceManager)

            'Changed PM_LOAD_OPTIONS_AGAIN 2003-12-12
            Trace.Assert(Not containerHandle Is Nothing, _
              "PIL ASSERT. containerHandle is Nothing. In insertOrOverwriteSetting().")

            Dim oldNode As System.Xml.XmlNode = containerHandle.SelectSingleNode( _
              aFieldName, anInNameSpaceManager)

            Dim nodeToUse As System.Xml.XmlElement
            nodeToUse = aSettingsDOM.CreateElement(aFieldName)  'CreateElement()
            '  is a wrapper function. The more general function is CreateNode().
            nodeToUse.InnerText = aValue

            If oldNode Is Nothing Then
                'The field does not already exist. Insert new node
                containerHandle.AppendChild(nodeToUse)
            Else
                containerHandle.ReplaceChild(nodeToUse, oldNode)  'Note: parent
                '  node because oldNode is the **text** node and not the named field.....
            End If
        End Sub 'insertOrOverwriteSetting


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Sub defaultMiscSettings( _
          ByRef aMiscSettingsStructure2 As miscSettingsStructure2Struct)

            'Constants moved from QuantWindow.vb, to be used for the defaults
            'They also changed because MS peak area is now used instead of
            'sum of MS intensities.

            'Changed PM_USERDEFINED_QUANT_THRESHOLD 2006-11-10
            ' 'Changed PM_QUANTTHRESHOLD_FROM_50_TO_20 2003-03-16
            ' 'Const MIN_SIGN_QUANT As Double = 50.0 'Otherwise we will not
            ' '  count the peptide by default.
            ' Const MIN_SIGN_QUANT_ANALYST As Double = 20.0 'Otherwise we will 
            ' '  not count the peptide by default.
            ' 
            ' 'Changed PM_FINNEGAN_COUNT_THRESHOLD 2003-12-22
            ' 'Const MIN_SIGN_QUANT_FINNEGAN As Double = 2000.0 'Otherwise we will
            ' '  not count the peptide by default
            ' Const MIN_SIGN_QUANT_FINNEGAN As Double = 10000.0 'Otherwise we will not
            ' '  count the peptide by default.
            ' 
            ' 'Changed JWG_MICROMASS_COUNT_THRESHOLD 2004-02-18
            ' Const MIN_SIGN_QUANT_MICROMASS As Double = 1.0 're-value later
            Const MIN_SIGN_QUANT_ANALYST As Double = 20.0 / 2000.0
            Const MIN_SIGN_QUANT_FINNEGAN As Double = 5.0
            Const MIN_SIGN_QUANT_MICROMASS As Double = 1.0


            'Default values if configuration does not exist.
            'aMiscSettingsStructure2.useAbsoluteMassWindowForXIC = True  old delete at any time.
            'aMiscSettingsStructure2.absoluteMassWindowForXIC = 0.2

            aMiscSettingsStructure2.MSpeakThresholdPercentageForXIC = 80.0

            'Changed PM_FINNIGAN_QUANTWINDOW_RELATIVE 2005-07-12
            ''Changed PM_VARIABLE_XIC_WINDOW_INSTRUMENTSPECIFIC 2004-06-29
            'aMiscSettingsStructure2.absoluteMassWindowForXIC_QSTAR = 0.2
            'aMiscSettingsStructure2.absoluteMassWindowForXIC_LTQFT = 0.03
            'aMiscSettingsStructure2.absoluteMassWindowForXIC_Qtof = 0.2

            aMiscSettingsStructure2.QSTARsettingsXIC.massWindowForXIC2 = 0.2
            aMiscSettingsStructure2.QSTARsettingsXIC.massForMassWindow = -1000.0
            aMiscSettingsStructure2.QSTARsettingsXIC.massWindowFunction = _
              massWindowFunctionEnum.enumConstantMass
            aMiscSettingsStructure2.QSTARsettingsXIC.quantThreshold = _
              MIN_SIGN_QUANT_ANALYST

            aMiscSettingsStructure2.LTQFTsettingsXIC.massWindowForXIC2 = 0.01
            aMiscSettingsStructure2.LTQFTsettingsXIC.massForMassWindow = 400.0
            aMiscSettingsStructure2.LTQFTsettingsXIC.massWindowFunction = _
              massWindowFunctionEnum.enumSquareMass
            aMiscSettingsStructure2.LTQFTsettingsXIC.quantThreshold = _
              MIN_SIGN_QUANT_FINNEGAN

            aMiscSettingsStructure2.QtofsettingsXIC.massWindowForXIC2 = 0.2
            aMiscSettingsStructure2.QtofsettingsXIC.massForMassWindow = -1000.0
            aMiscSettingsStructure2.QtofsettingsXIC.massWindowFunction = _
              massWindowFunctionEnum.enumConstantMass
            aMiscSettingsStructure2.QtofsettingsXIC.quantThreshold = _
              MIN_SIGN_QUANT_MICROMASS

            aMiscSettingsStructure2.option1 = 0

            'Changed PM_PHOSPHO_SCORING 2006-01-09
            aMiscSettingsStructure2.maxDisplayedPTMcombinations2 = 25
            aMiscSettingsStructure2.PTMminimumScore = 14.0
            aMiscSettingsStructure2.minimumPTMdeltaScore = 0.1

            'Changed PM_LIMIT_PTMCOMBINATIONS 2008-01-15
            aMiscSettingsStructure2.maxCombinations = 1000

            'Changed PM_TITLELINEPARSING 2007-06-08
            aMiscSettingsStructure2.TITLElineDefs = _
              TITLElineDefinitions.defaultTITLEparseDefs()
        End Sub 'defaultMiscSettings


        '****************************************************************************
        '*    M I S C   O P T I O N S  ,   E N D                                    *
        '****************************************************************************


        '****************************************************************************
        '*    E X T E R N A L   Q U A N T I T A T I O N   S P E C I F I C A T I O N   ,  B E G I N *
        '****************************************************************************


        'Changed PM_GENERALISED_QUANT_MODE 2003-12-08
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function getQuantitationModesObject() As QuantitationModes
            Return mQuantitationModes
        End Function


        'Changed PM_EVENMORE_GENERALISED_QUANTMODES 2005-04-07
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function getQuantModes() As QuantitationModes_moreGeneral
            Return mQuantitationModes_new
        End Function 'getQuantModes


        'Changed PM_REFACTOR 2006-10-16
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function getDishes(ByVal aQuantModeCode As Integer) As Integer

            Dim toReturn As Integer = 0

            Dim quantitationModesObject As QuantitationModes_moreGeneral = _
              Me.getQuantModes()

            Dim curQuantMode As generalisedQuantModeStructure = _
              quantitationModesObject.getQuantitationMode(aQuantModeCode)

            toReturn = _
              curQuantMode.dishes_StartingFromDish2.Count + 1

            Return toReturn
        End Function 'getDishes


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub loadQuantitationSpecificationSettings(ByVal aFileName4 As String)

            ''Changed PM_OPTIONSFILES_ONLYINBIN 2004-01-28
            'Dim fileNameFullPath As String = MSQFullPath(aFileName4)
            'mMiscOptionsFileName_FullPath = fileNameFullPath
            'Trace.Assert(isFullPathFileName(mMiscOptionsFileName_FullPath), _
            '  "PIL ASSERT. Options file is not a full path name: " & _
            '  mMiscOptionsFileName_FullPath)

            'defaultQuantitationSpecificationSettings(mMiscSettings) 'This will fill in
            ''  all fields, also those that may NOT be in the options file.
            ''  This will be the case when the options file was created by 
            ''  an older version of the program.
            'Try
            '    Dim defaultXML As String = _
            '      "<SOAP-ENV:Envelope   " & ControlChars.NewLine & _
            '      "    xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""                " & ControlChars.NewLine & _
            '      "    xmlns:xsd=""http://www.w3.org/2001/XMLSchema""                         " & ControlChars.NewLine & _
            '      "    xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/""           " & ControlChars.NewLine & _
            '      "    xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/""           " & ControlChars.NewLine & _
            '      "    xmlns:clr=""http://schemas.microsoft.com/soap/encoding/clr/1.0""       " & ControlChars.NewLine & _
            '      "    SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">  " & ControlChars.NewLine & _
            '      "  <SOAP-ENV:Body>                                                        " & ControlChars.NewLine & _
            '      "    <a1:miscSettingsStructure id=""ref-1""                                 " & ControlChars.NewLine & _
            '      "        xmlns:a1=""http://schemas.microsoft.com/clr/nsassem/massSpectrometryBase/Mascot%20Parser%2C%20Version%3D1.0.1419.18653%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"">  " & ControlChars.NewLine & _
            '      "                                  " & ControlChars.NewLine & _
            '      "    </a1:miscSettingsStructure>   " & ControlChars.NewLine & _
            '      "  </SOAP-ENV:Body>                " & ControlChars.NewLine & _
            '      "</SOAP-ENV:Envelope>              " & ControlChars.NewLine

            '    Dim NSSpec As String = _
            '      "http://schemas.microsoft.com/clr/nsassem/massSpectrometryBase/Mascot%20Parser%2C%20Version%3D1.0.1419.18653%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"

            '    'For misc settings.
            '    Dim struHandle As System.Xml.XmlNode = optionsFileLoad( _
            '      fileNameFullPath, "miscSettingsStructure", 600, _
            '       defaultXML, NSSpec, mMiscSettingsDOM, mMiscSettingsNsManager)
            '    Dim fileDidNotExist As Boolean = struHandle.SelectSingleNode( _
            '      "absoluteMassWindowForXIC", mMiscSettingsNsManager) Is Nothing

            '    extractDoubleFromXmlNode( _
            '      struHandle, mMiscSettingsNsManager, _
            '      "absoluteMassWindowForXIC", _
            '      mMiscSettings.absoluteMassWindowForXIC)

            '    If fileDidNotExist Then
            '        'If file did not exist:
            '        'Persist the default instead such that the configuration
            '        'file is always created if it does not exist.

            '        PersistMiscSettings()
            '    Else
            '        Dim peter9 As Integer = 9
            '    End If

            'Catch e2 As Exception
            '    MsgBox("Could load settings from options file " & fileNameFullPath & _
            '      ". Using default values instead." & ControlChars.NewLine & ControlChars.NewLine & _
            '      "Some details, exception: " & e2.Message & "..........")
            'End Try
        End Sub 'loadQuantitationSpecificationSettings


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Function outputXMLnodeList( _
          ByVal anXMLnodeList As System.Xml.XmlNodeList) As String

            Dim toReturn As String = ""
            Dim xyz As System.Xml.XmlNode
            For Each xyz In anXMLnodeList
                toReturn &= MSQuantCommon2.outputXMLnode(xyz) & _
                  ControlChars.NewLine & _
                  "=======================" & ControlChars.NewLine
            Next
            Return toReturn
        End Function 'outputXMLnodeList


        'Here was loadQuantitationDefinitions(), refactored into MSQuantCommon.vb, in the
        'SqlInterface project.

        '****************************************************************************
        '*    E X T E R N A L   Q U A N T I T A T I O N   S P E C I F I C A T I O N   ,   E N D *
        '****************************************************************************


        '****************************************************************************
        '*    C O R R E L A T I O N   S E T T I N G S ,   B E G I N                 *
        '****************************************************************************


        'Changed PM_CORRELATION_DIALOG 2003-10-21
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Shared Sub defaultCorrSettings( _
          ByRef aOutCorrSettings As _
            massSpectrometryBase.correlationSettingsStructure)

            'Default values if configuration does not exist.

            'Changed PM_DEFAULT_NOINSERTIONOFPEPTIDES 2006-07-26
            'aOutCorrSettings.doNotInsertNewPeptides = False
            aOutCorrSettings.doNotInsertNewPeptides = True

            aOutCorrSettings.insertPeptidesInLCTimeRange = False
            aOutCorrSettings.startLCtimeForInsertion_Secs = 2.1 * 60.0
            aOutCorrSettings.endLCtimeForInsertion_Secs = 8907.6 * 60.0

            'Changed PM_LCPEAK_WINDOW_USERDEFINED 2003-12-18
            aOutCorrSettings.leftLCwindowSecs = 60.0
            aOutCorrSettings.rightLCwindowSecs = 90.0

            'Changed PM_LCPEAKDETECTION_OPTIONS 2006-06-16
            aOutCorrSettings.SILACdishForLCpeakDetection = 1
            aOutCorrSettings.useHighestLCprofileForLCpeakDetection = False
        End Sub 'defaultCorrSettings


        'Changed PM_REFACTOR 2003-12-17
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub old_PersistCorrSettings()

            Dim xpathSpec As String = _
              MSQuantCommon2.construct_xPathSpec("correlationSettingsStructure")

            insertOrOverwriteSetting( _
              mCorrelationSettingsDOM, mCorrelationSettingsNsManager, _
              xpathSpec, _
              mCorrSettings.doNotInsertNewPeptides.ToString(), _
              "doNotInsertNewPeptides")

            'Changed PM_LC_TIMERANGE 2003-12-17
            insertOrOverwriteSetting( _
              mCorrelationSettingsDOM, mCorrelationSettingsNsManager, _
              xpathSpec, _
              mCorrSettings.insertPeptidesInLCTimeRange.ToString(), _
              "insertPeptidesInLCTimeRange")
            insertOrOverwriteSetting( _
              mCorrelationSettingsDOM, mCorrelationSettingsNsManager, _
              xpathSpec, _
              mCorrSettings.startLCtimeForInsertion_Secs.ToString(), _
              "startLCtimeForInsertion_Secs")
            insertOrOverwriteSetting( _
              mCorrelationSettingsDOM, mCorrelationSettingsNsManager, _
              xpathSpec, _
              mCorrSettings.endLCtimeForInsertion_Secs.ToString(), _
              "endLCtimeForInsertion_Secs")

            'Changed PM_LCPEAK_WINDOW_USERDEFINED 2003-12-18
            insertOrOverwriteSetting( _
              mCorrelationSettingsDOM, mCorrelationSettingsNsManager, _
              xpathSpec, _
              mCorrSettings.leftLCwindowSecs.ToString(), _
              "leftLCwindowSecs")
            insertOrOverwriteSetting( _
              mCorrelationSettingsDOM, mCorrelationSettingsNsManager, _
              xpathSpec, _
              mCorrSettings.rightLCwindowSecs.ToString(), _
              "rightLCwindowSecs")

            'Changed PM_OPTIONSFILES_ONLYINBIN 2004-01-28
            Trace.Assert(MSQuantCommon2.isFullPathFileName( _
                mCorrelationSettingsFileName_FullPath), _
              "PIL ASSERT. Options file is not a full path name: " & _
              mCorrelationSettingsFileName_FullPath)
            mCorrelationSettingsDOM.Save(mCorrelationSettingsFileName_FullPath)
        End Sub 'old_PersistCorrSettings


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub newCorrelationSettings( _
          ByVal aFileName4 As String, _
          ByRef anInNewSettings As correlationSettingsStructure)

            mCorrSettings = anInNewSettings

            Dim fileNameFullPath As String = _
              MSQuantCommon2.fullPathToFileInApplicationFolder(aFileName4)

            PersistCorrSettings( _
              fileNameFullPath, mCorrSettings)
        End Sub 'newCorrelationSettings


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function getCorrSettings() As correlationSettingsStructure
            Return mCorrSettings
        End Function 'getMiscSettings


        '****************************************************************************
        '*    C O R R E L A T I O N   S E T T I N G S ,   E N D                     *
        '****************************************************************************


        'Changed PM_QUANTGENERAL_BUGFIX_MORETHAN3DISHES 2007-01-09. Disabled, is
        '  not used. But do not delete yet.
        ' 'Changed PM_REFACTOR 2004-02-04
        ' '****************************************************************************
        ' '*    <placeholder for header>                                              *
        ' '****************************************************************************
        ' Public Function isTripleEncoding2(ByRef aQuantModeCode As Integer) _
        ' As Boolean
        ' 
        '     'Changed PM_EVENMORE_GENERALISED_QUANTMODES 2005-04-08
        '     'Dim quantitationModesObject As QuantitationModes = _
        '     '  Me.getQuantitationModesObject()
        '     Dim quantitationModesObject As QuantitationModes_moreGeneral = _
        '       Me.getQuantModes()
        ' 
        '     'Changed PM_EVENMORE_GENERALISED_QUANTMODES 2005-04-08
        '     'Dim curQuantMode As quantitationModeStructure = _
        '     '  quantitationModesObject.getQuantitationMode(aQuantModeCode)
        '     Dim curQuantMode As generalisedQuantModeStructure = _
        '       quantitationModesObject.getQuantitationMode(aQuantModeCode)
        ' 
        '     Dim isTriple As Boolean = _
        '       QuantitationModes_moreGeneral.isTripleQuant_new2(curQuantMode)
        '     Return isTriple
        ' End Function 'getMiscSettings


        'Should it be somewhere else?? Some class for testing? And independent
        'of the MSQuant application.
        'Changed PM_MEMORY_ALLOCATION_TEST 2004-07-26
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub stopNow( _
          ByVal aMsg As String, ByVal aGoIntoInfiniteLoop As Boolean)

            If False Then 'True for testing, False for normal
                MsgBox(aMsg)

                Dim j As Integer
                For j = 0 To 2000
                    System.Threading.Thread.Sleep(0) 'Yield.
                Next j

                While aGoIntoInfiniteLoop
                    'Application.DoEvents()

                    'From <http://www.dotnet247.com/247reference/msgs/48/243118.aspx>.
                    System.Threading.Thread.Sleep(0) 'use System.Threading.Thread.Sleep(0) to yield.

                    Dim peter2 As Integer = 2
                End While
            End If
        End Sub 'stopNow


        'Changed PM_MEMORY_ALLOCATION 2004-08-06
        'This function is completely general and should be moved somewhere else
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '*   Purpose: convenience function for memory garbage collection.           *
        '*            Essentially calls System.GC.Collect() but also times it       *
        '*            and has breakpoint, etc.                                      *
        '****************************************************************************
        Public Shared Sub GarbageCollect(ByRef aLogger As SDUPlogger, _
          ByRef anOutMBsaved As Double, ByRef anOutCollectTimeSecs As Double)

            If Not aLogger Is Nothing Then
                aLogger.timeLog("**Before call of System.GC.Collect().")
            End If

            'Changed PM_MEMORY_ALLOCATION 2004-08-03
            Dim beforeBytes As Long = System.GC.GetTotalMemory(False)
            Dim tickCount1 As Integer = Environment.TickCount
            System.GC.Collect()
            Dim tickCount2 As Integer = Environment.TickCount
            Dim afterBytes As Long = System.GC.GetTotalMemory(False)

            If Not aLogger Is Nothing Then
                aLogger.timeLog("**After call of System.GC.Collect().")
            End If

            anOutMBsaved = _
              (CDbl(beforeBytes - afterBytes)) / 1024 / 1024
            anOutCollectTimeSecs = (tickCount2 - tickCount1) / 1000.0
        End Sub 'GarbageCollect


        'Changed PM_REFACTOR 2004-09-06
        '****************************************************************************
        '*    Purpose: wrapper for now common function                              *
        '*             MSQuantCommon.loadQuantitationDefinitions.                   *
        '*             We want to store some information in this class, the         *
        '*             application - returned from the function.                    *
        '*                                                                          *
        '****************************************************************************
        Public Sub appLoadQuantitationDefinitions( _
          ByVal aFileName3 As String, _
          ByRef anOutModificationsAccepted As Boolean, _
          ByRef anOutErrStr As String)

            MSQuantCommon.loadQuantitationDefinitions( _
              aFileName3, _
              mQuantitationDefinitionsFileName, _
              mQuantitationModes, _
              mQuantitationModesDOM, _
              mQuantitationModesNsManager, _
              mQuantitationModes_new, _
              quantApplication.versionString_withDate(), _
              anOutModificationsAccepted, anOutErrStr _
              )
        End Sub 'appLoadQuantitationDefinitions


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Function deserialiseDocumentDataStructures4( _
          ByRef aBinFile_fullPath As String, _
          ByRef aResultMsg As String, _
          ByRef aOutDoc As MSQuantDocumentStructure, _
          ByRef anInOutApplication As quantApplication, _
          ByRef anOutLoadInfoStr As String _
          ) _
          As Boolean

            Dim toReturn As Boolean = False 'Will stay if exception happens 
            '  in loading the binary file. This can easily happen if
            '  the type of binary does not match the current version of 
            '  MSQuant.
            '
            '  Should we insist on the expected extension??

            anInOutApplication.startStopWatch()

            aResultMsg = ""
            Dim proteins As Integer = 0

            If File.Exists(aBinFile_fullPath) Then

                'Default message if it fails...
                aResultMsg = _
                  "Could not open file " & aBinFile_fullPath & _
                  ". The file is probably not in the right format. " & _
                  "Specify a file with the expected format."

                Dim BFormatter As New BinaryFormatter()

                'Up here for the exception handler.
                Dim binFile As FileStream = Nothing 'Keep compiler happy.
                Try
                    binFile = File.OpenRead(aBinFile_fullPath)

                    'Formatters.Binary.BinaryFormatter()

                    aOutDoc = _
                      CType(BFormatter.Deserialize(binFile), MSQuantDocumentStructure)
                    binFile.Close()

                    'mOptions = CType(BFormatter.Deserialize(theFile), OptionsStruct2)
                    'mWiffFileStr = CType(BFormatter.Deserialize(theFile), String)
                    'mMascotWebOutputFileName = CType(BFormatter.Deserialize(theFile), String)

                    If Not aOutDoc.rawFileStr Is Nothing Then
                        'Is this used/visible?? Or is it overwritten??
                        aResultMsg = _
                          "Opened protein hits from file" & aBinFile_fullPath

                        toReturn = True 'We succeeded!
                    End If

                Catch exceptionObject As Exception

                    If Not binFile Is Nothing Then
                        binFile.Close()
                    End If

                    MsgBox(aResultMsg)
                End Try

                proteins = aOutDoc.parsedProts3.Count()
            Else
                'File does not exist. This can happen when using
                'the command line interface.
                aResultMsg = _
                  "Could not load the specified file. " & _
                  "The specified file """ & aBinFile_fullPath & _
                  """ does not exist. " & _
                  "Specify an existing file."
                MsgBox(aResultMsg)
            End If

            If True Then
                Dim memDiff_MB As Double
                Dim parseTimeSecs As Double = _
                  anInOutApplication.stopStopWatch(memDiff_MB)

                anOutLoadInfoStr = _
                  "Loaded " & proteins & _
                  " protein hits from file. Time: " & _
                  parseTimeSecs.ToString("0.00") & " seconds."
            End If

            Trace.Assert(aResultMsg.Length() > 0, _
              "PIL ASSERT. Internal error: result message not set.")

            Return toReturn
        End Function 'deserialiseDocumentDataStructures4


        'Changed PM_MB3_RELOCATION 2008-05-23
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub patchDocumentDataStructures( _
          ByRef anInOutDoc As MSQuantDocumentStructure, _
          ByRef anInResultFile As String, _
          ByRef anInRawFile2 As String, _
          ByVal aOnlyOneRawFile As Boolean)

            'Should check existence of the two files or trust the caller?

            Dim newFolderBase As String = Path.GetDirectoryName(anInRawFile2)

            anInOutDoc.mascotFileStr = anInResultFile
            anInOutDoc.rawFileStr = anInRawFile2

            'Adjust folder base, assuming raw files are in the same folder.
            Dim rlen As Integer = anInOutDoc.rawFiles.Length()

            Dim oneRawFilePath As String = "" 'This value is used as a flag below
            If aOnlyOneRawFile Then
                oneRawFilePath = _
                  PILInputOutput.newFolderBase(anInRawFile2, newFolderBase)

                Dim firstItem As fileSpecStructure = anInOutDoc.rawFiles(0)

                'Reduce raw list to one. Otherwise we get in
                'trouble elsewhere in the program.
                ReDim anInOutDoc.rawFiles(0)

                firstItem.path = oneRawFilePath
                firstItem.tag2 = MultipleRawFilesHandling.RAWFILEREF_NOTMULTIPLE 'Needed?
                anInOutDoc.rawFiles(0) = firstItem
            Else
                Dim lastIndex As Integer = rlen - 1
                Dim j As Integer
                For j = 0 To lastIndex

                    Dim someRawFile As fileSpecStructure = anInOutDoc.rawFiles(j)

                    'Dim fileName As String = Path.GetFileName(someRawFile.path)
                    'Replace with new folder base.
                    'someRawFile.path = newFolderBase & Path.DirectorySeparatorChar & fileName
                    someRawFile.path = _
                      PILInputOutput.newFolderBase(someRawFile.path, newFolderBase)

                    anInOutDoc.rawFiles(j) = someRawFile 'Write back.
                Next j
            End If

            'Patch peptide fields with absolute path Mascot result file and raw file.
            If True Then
                Dim lastProteinIndex As Integer = anInOutDoc.parsedProts3.Count - 1
                Dim i As Integer
                For i = 0 To lastProteinIndex
                    Dim protein As ProteinHitStructure = anInOutDoc.parsedProts3(i)

                    protein.resultFilePath2 = _
                      PILInputOutput.newFolderBase( _
                        protein.resultFilePath2, newFolderBase)

                    Dim pept As PeptideHitStructure = _
                      helper.blankPeptide() 'Keep compiler happy.
                    Dim pepIter As peptideListIterator = _
                      New peptideListIterator(protein.peptides)
                    While Not pepIter.nextPeptide(pept)

                        'Note: Mascot result file is NOT store in the peptide, only
                        '      the raw (as it can be different for each peptide).
                        If oneRawFilePath.Length() = 0 Then
                            'This is the normal action.
                            pept.rawFileFullPath = _
                              PILInputOutput.newFolderBase( _
                                pept.rawFileFullPath, newFolderBase)
                        Else
                            'This is only for testing purposes where a script
                            'has removed raw file references and thus not all
                            'raw needs to be copied for testing.
                            pept.rawFileFullPath = oneRawFilePath
                            pept.rawFileID = MultipleRawFilesHandling.RAWFILEREF_NOTMULTIPLE
                        End If

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

                    anInOutDoc.parsedProts3(i) = protein 'write-back. All the changed
                    '  peptide values..
                Next 'Through proteins.

            End If 'Patch full paths.

        End Sub 'patchDocumentDataStructures


        'Changed PM_REMEMBER_SELECTION 2005-03-01
        'This utility function should be somewhere else as it is
        'not MSQuant specific, but is more general. 
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Function copySelectedIndices2( _
          ByRef aInSelectedIndices As _
            System.Windows.Forms.ListView.SelectedIndexCollection) _
          As List(Of Integer)

            'Old return type:
            '  As ArrayList

            Dim len As Integer = aInSelectedIndices.Count
            Dim toReturn As List(Of Integer) = _
              New List(Of Integer)(len)

            Dim lastIndex As Integer = len - 1
            Dim i As Integer
            For i = 0 To lastIndex
                Dim index As Integer = aInSelectedIndices.Item(i)
                toReturn.Add(index)
            Next
            Return toReturn
        End Function 'copySelectedIndices


        'Changed PM_REFACTOR 2008-05-01
        'This utility function should be somewhere else as it is
        'not MSQuant specific, but is more general. 
        '****************************************************************************
        '*    Change all selected item's "checked" status to true (in a ListView)   *
        '****************************************************************************
        Public Shared Sub setCheckedStatusForSelected( _
          ByRef aListView As System.Windows.Forms.ListView, _
          ByVal aCheckedState As Boolean)

            'Note: why do we go through every item? Why not
            '      use aListView.SelectedIndices ?

            Dim lastIndex As Integer = aListView.Items.Count - 1
            Dim i As Integer
            For i = 0 To lastIndex
                If aListView.Items(i).Selected Then
                    aListView.Items(i).Checked = aCheckedState 'Will this fire events?
                End If
            Next
        End Sub 'setCheckedStatusForSelected


        'Changed PM_REFACTOR 2008-05-01
        'This utility function should be somewhere else as it is
        'not MSQuant specific, but is more general. 
        '****************************************************************************
        '*    Change all selected item's "checked" status to true (in a ListView)   *
        '****************************************************************************
        Public Shared Sub toggleCheckedStatusForSelected( _
          ByRef aListView As System.Windows.Forms.ListView)

            'Note: why do we go through every item? Why not
            '      use aListView.SelectedIndices ?

            Dim lastIndex As Integer = aListView.Items.Count - 1
            Dim i As Integer
            For i = 0 To lastIndex
                If aListView.Items(i).Selected Then
                    aListView.Items(i).Checked = Not (aListView.Items(i).Checked)
                End If
            Next
        End Sub 'setCheckedStatusForSelected


        'Changed PM_REFACTOR 2008-05-01
        'This utility function should be somewhere else as it is
        'not MSQuant specific, but is more general. 
        '****************************************************************************
        '*    Change all selected item's "checked" status to true (in a ListView)   *
        '****************************************************************************
        Public Shared Sub selectAllOrSome( _
          ByRef aListView As System.Windows.Forms.ListView, _
          ByVal aChangeOnlyChecked As Boolean)

            Dim lastIndex As Integer = aListView.Items.Count - 1
            Dim i As Integer
            For i = 0 To lastIndex
                Dim newVal As Boolean = True
                If aChangeOnlyChecked Then
                    Dim visualCheckStatus As Boolean = aListView.Items(i).Checked
                    If visualCheckStatus = False Then
                        newVal = False
                    End If
                End If
                aListView.Items(i).Selected = newVal
            Next
        End Sub 'setCheckedStatusForSelected


        'Changed PM_REFACTOR 2008-05-01
        'This utility function should be somewhere else as it is
        'not MSQuant specific, but is more general. 
        '****************************************************************************
        '*    Change all selected item's "checked" status to true (in a ListView)   *
        '****************************************************************************
        Public Shared Sub invertSelection( _
          ByRef aListView As System.Windows.Forms.ListView)

            Dim lastIndex As Integer = aListView.Items.Count - 1
            Dim i As Integer
            For i = 0 To lastIndex
                aListView.Items(i).Selected = Not aListView.Items(i).Selected
            Next
        End Sub 'setCheckedStatusForSelected


        'Changed PM_REFACTOR 2007-02-23
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Shared Sub proteinRatiosAndStds( _
          ByRef anInProt As ProteinHitStructure, ByVal aDishes As Integer, _
          ByRef aInOutBuf As StringBuilder)

            'Changed PM_DEEPER_BAD_VALUE 2007-03-13
            Const BAD_PROTEIN_VALUE As Double = -8888.8888

            Dim lastIndex6 As Integer = aDishes - 1
            Dim dish As Integer
            For dish = 0 To lastIndex6

                'Changed PM_REFACTOR 2006-10-18. Now handle the situation that
                'the protein has not been quantified.
                Dim someItem As protSILACresultStructure

                'Changed PM_DEEPER_BAD_VALUE 2007-03-13. Now the
                'protein ratio is also a large negative values so if
                'it is used in some calculation it will be apparent.
                'Default if the protein has not been quantified.
                'someItem.averageRatioToBase = 0.0
                'someItem.stdDevAverageRatioToBase = -77.7777
                'someItem.inv_averageRatioToBase = 0.0
                'someItem.inv_stdDevAverageRatioToBase = -888.888888
                someItem.averageRatioToBase = BAD_PROTEIN_VALUE
                someItem.stdDevAverageRatioToBase = BAD_PROTEIN_VALUE
                someItem.inv_averageRatioToBase = BAD_PROTEIN_VALUE
                someItem.inv_stdDevAverageRatioToBase = BAD_PROTEIN_VALUE

                If Not anInProt.quantResults3 Is Nothing Then
                    If dish = 0 Then
                        Dim dishesInResult As Integer = anInProt.quantResults3.Count
                        Trace.Assert( _
                          aDishes = dishesInResult, _
                          "PIL ASSERT. " & _
                          "Number of SILAC dishes in quantitation result, " & _
                          dishesInResult & ",  is not the expected, " & aDishes & ".")
                    End If

                    Dim oneDish As oneDishResultStructure = _
                      anInProt.quantResults3(dish)

                    someItem = _
                      MSQuantCommon.getProteinQuantValues( _
                        dish, _
                        MultipleRawFilesHandling.REF_WHOLEPROTEIN, _
                        anInProt.quantResults3)
                Else
                    Dim peter7 As Integer = 7
                End If

                'Changed PM_EXPORT_DECIMALS 2007-03-12
                ''Changed PM_LIMIT_EXPORT 2006-11-08
                ''sbStr.Append(someItem.averageRatioToBase)
                'aInOutBuf.Append(someItem.averageRatioToBase.ToString("0.00"))
                aInOutBuf.Append(someItem.averageRatioToBase.ToString("0.000"))
                aInOutBuf.Append(vbTab)

                'Changed PM_LIMIT_EXPORT 2006-11-08
                'sbStr.Append(someItem.stdDevAverageRatioToBase)
                aInOutBuf.Append(someItem.stdDevAverageRatioToBase.ToString("0.00"))
                aInOutBuf.Append(vbTab)
            Next dish

        End Sub 'proteinRatiosAndStds


        'Changed PM_REFACTOR 2003-04-16
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        '  This function is coupled to function xyz().
        '  Parameter aProt: const ref.
        '
        Public Shared Function proteinInformation_PrefixForPeptideLine( _
          ByRef anInProt As ProteinHitStructure, ByVal aDishes As Integer) _
          As String

            'Future: use StringBuilder
            Dim sbStr As StringBuilder = New StringBuilder(200)

            'Changed PM_REFACTOR 2006-10-18
            If True Then 'Now only for error detection.
                Dim lastIndex5 As Integer = -1
                If Not anInProt.quantResults3 Is Nothing Then
                    lastIndex5 = anInProt.quantResults3.Count - 1
                End If

                Dim qCount As Integer = lastIndex5 + 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
            End If

            'Changed PM_STATISTICS_N 2007-02-23
            ''Changed PM_STATISTICS_N 2007-01-11
            'sbStr.Append("N")
            '
            '  Not yet!!!
            Dim N As Integer = -1
            sbStr.Append(N)

            sbStr.Append(vbTab)

            'Changed PM_REFACTOR 2007-02-23
            quantApplication.proteinRatiosAndStds(anInProt, aDishes, sbStr)

            sbStr.Append(anInProt.accNum)
            sbStr.Append(vbTab)

            Dim monoMass As Double = anInProt.monoIsotopicMass
            sbStr.Append(monoMass.ToString("0.00"))
            sbStr.Append(vbTab)

            sbStr.Append("SPACER")
            sbStr.Append(vbTab)

            sbStr.Append(anInProt.description2)
            'sbStr.Append(vbTab)  not included...

            Dim someStr As String = sbStr.ToString
            Return someStr
        End Function 'proteinInformation_PrefixForPeptideLine


        'Changed PM_REFACTOR 2005-03-07
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub addProteinTableHeaders( _
          ByVal aDishes As Integer, ByRef aInOutBuf As StringBuilder)

            aInOutBuf.Append("")
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append("Mascot Hit")
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append("Accession number")
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append("Mass [Da]")
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append("pepts in A")
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append("pepts in B")
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append("pepts in C")
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append("pepts in A,B,C")
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append("score in A,B,C")
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append("Description")
            aInOutBuf.Append(vbTab)

            'Changed PM_MORETHAN3DISHES_PROTEINHEADER 2007-02-23
            'aInOutBuf.Append("Ave i/w")
            'aInOutBuf.Append(vbTab)
            'aInOutBuf.Append("StDev i/w")
            'aInOutBuf.Append(vbTab)
            'aInOutBuf.Append("Ave h/w")
            'aInOutBuf.Append(vbTab)
            'aInOutBuf.Append("StDev h/w")
            'aInOutBuf.Append(vbTab)
            quantApplication.ratioAndStdHeaders(aDishes, aInOutBuf)

            aInOutBuf.Append("Checked/Verified")
            aInOutBuf.Append(vbTab)

            aInOutBuf.Append("Quantified")
            aInOutBuf.Append(vbTab)

            aInOutBuf.Append("Amino acid sequence")
            aInOutBuf.Append(vbTab)

            'Changed PM_SEQUENCE_COVERAGE 2008-04-16
            aInOutBuf.Append("Sequence coverage")
            aInOutBuf.Append(vbTab)

            aInOutBuf.Append(vbCrLf)
        End Sub 'proteinTableHeaders


        'Changed PM_REFACTOR 2005-03-07
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub addProteinLine( _
          ByRef anInProtein As ProteinHitStructure, _
          ByRef aInOutBuf As StringBuilder, _
          ByVal aDishes As Integer)

            aInOutBuf.Append("PROTEIN")
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append(anInProtein.hitNumber.ToString)
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append(anInProtein.accNum)
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append(anInProtein.monoIsotopicMass.ToString("0.00"))
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append(anInProtein.numPeptsInA.ToString)
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append(anInProtein.numPeptsInB.ToString)
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append(anInProtein.numPeptsInC.ToString)
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append(anInProtein.peptsInABC)
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append(anInProtein.scoreInABC)
            aInOutBuf.Append(vbTab)
            aInOutBuf.Append(anInProtein.description2)
            aInOutBuf.Append(vbTab)

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

            'Changed PM_REFACTOR 2007-02-23
            ' Dim dish As Integer
            ' Dim n As Integer = -1
            ' Dim lastIndex As Integer = aDishes - 1
            ' For dish = 0 To lastIndex
            '     Dim someItem As protSILACresultStructure
            '     someItem.averageRatioToBase = 0.0
            '     someItem.inv_averageRatioToBase = 0.0
            '     someItem.inv_stdDevAverageRatioToBase = 0.0
            '     someItem.stdDevAverageRatioToBase = 0.0
            ' 
            '     'Changed PM_PROTEINEXPORT_EXCEPTION 2006-11-08
            '     If Not anInProtein.quantResults3 Is Nothing Then
            '         someItem = _
            '             MSQuantCommon.getProteinQuantValues( _
            '               dish, _
            '               MultipleRawFilesHandling.REF_WHOLEPROTEIN, _
            '               anInProtein.quantResults3)
            '     End If
            ' 
            '     aInOutBuf.Append(someItem.averageRatioToBase)
            '     aInOutBuf.Append(vbTab)
            ' 
            '     aInOutBuf.Append(someItem.stdDevAverageRatioToBase)
            '     aInOutBuf.Append(vbTab)
            ' Next
            quantApplication.proteinRatiosAndStds(anInProtein, aDishes, aInOutBuf)


            addBooleanString(anInProtein.proteinHasBeenChecked, aInOutBuf)
            aInOutBuf.Append(vbTab)

            addBooleanString(anInProtein.proteinHasBeenQuantified, aInOutBuf)
            aInOutBuf.Append(vbTab)

            'Changed PM_RETRIEVE_PROTEIN_SEQUENCES 2008-04-14
            Dim seqToExport As String = anInProtein.sequence2
            If seqToExport Is Nothing OrElse seqToExport.Length() = 0 Then 'Note:
                '  relies on boolean short-curcuit...
                seqToExport = "<none>"
            End If

            aInOutBuf.Append(seqToExport)
            aInOutBuf.Append(vbTab)

            'Changed PM_SEQUENCE_COVERAGE 2008-04-16
            aInOutBuf.Append(anInProtein.sequenceCoverage.ToString("0.00"))
            aInOutBuf.Append(vbTab)

            aInOutBuf.Append(vbCrLf)
        End Sub 'addProteinLine


        'Changed PM_REFACTOR 2005-03-07. Moved to here. Perhaps later move to 
        '  a place/file that have quantitation mode stuff.
        'Changed PM_QUANTMODESTR_DISPLAY 2003-09-29
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Function quantModeString( _
          ByVal aQuantModeCode As Integer, _
          ByRef anApplication As quantApplication) As String

            Dim toReturn As String = Nothing 'Keep compiler happy.

            Dim quantitationModesObject As QuantitationModes_moreGeneral = _
              anApplication.getQuantModes()

            'New method
            If True Then
                Dim quantMode As generalisedQuantModeStructure = _
                  quantitationModesObject.getQuantitationMode(aQuantModeCode)
                toReturn = quantMode.GUIname
            End If

            'Old method. Very round-about way to find the string. Delete at any time.
            ' If True Then
            '     Dim cIndex As Integer = QuantModeCode2ListIndex( _
            '       aQuantModeCode, quantitationModesObject)
            ' 
            '     ''Read-off in the control. An more independent way would be to fill in 
            '     ''control from a internal table that this function use directly.
            '     'Dim collec As System.Windows.Forms.ComboBox.ObjectCollection = _
            '     '  cbxQuantMode.Items()
            '     'Dim toReturn As String = DirectCast(collec.Item(cIndex), String)
            ' 
            '     Dim qStrings As ArrayList = _
            '       frmOptions.quantStrings(anApplication)
            '     toReturn = DirectCast(qStrings.Item(cIndex), String)
            ' End If

            Return toReturn
        End Function 'quantModeString


        'Changed PM_REFACTOR 2007-11-19
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub addCalibrationInformationForAll( _
          ByRef anInCalibration As SDUPrecalibrator, _
          ByRef anInOutSB As StringBuilder)

            'Changed PM_PERFILE_RECALIBRATION 2007-11-16
            Dim tag As Integer = SDUPrecalibrator.ALL_TAGCODE

            Dim slope As Double
            Dim offset As Double
            'Note: for now only for ***all*** raw files. Missing
            '      is constants for every raw file.
            anInCalibration.getLinearCalibrationConstants( _
              slope, offset, tag)

            anInOutSB.Append("Calibration constants, ")
            anInOutSB.Append("for all raw files.")
            anInOutSB.Append(vbTab)
            anInOutSB.Append("For recalibration domain XYZ")
            anInOutSB.Append(vbTab)
            anInOutSB.Append(vbCrLf)

            anInOutSB.Append("A: ")
            anInOutSB.Append(vbTab)
            anInOutSB.Append(slope.ToString("0.000000000"))
            anInOutSB.Append(vbCrLf)
            anInOutSB.Append("B: ")
            anInOutSB.Append(vbTab)
            anInOutSB.Append(offset.ToString("0.000000000"))
            anInOutSB.Append(vbCrLf)

        End Sub 'addCalibrationInformationForAll


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        '  This function is coupled to function peptideTableHeaders().
        '  Parameter aProt: const ref.
        '
        Public Shared Function FormatAppHeader( _
          ByRef anInCalibration As SDUPrecalibrator, _
          ByVal aQuantModeCode As Integer, _
          ByRef anApplication As quantApplication, _
          ByVal aDishes As Integer) _
          As String

            'Changed PM_REFACTOR 2007-10-29
            'Old:
            '  ByVal aSlope As Double, ByVal anOffset As Double

            Dim toReturnBuf As StringBuilder = New StringBuilder(4000)

            'Changed PM_REFACTOR 2005-03-07.
            'Old. Delete at any time.
            ' Dim toReturn As String = _
            '   "Calibration constants," & vbCrLf & _
            '   "A: " & vbTab & aSlope & vbCrLf & _
            '   "B: " & vbTab & anOffset & vbCrLf
            If True Then

                'Changed PM_MARKER_EXPORT_ALL_RECALIB_CONSTANTS 2007-11-16.
                'Perhaps make it an option to export information about
                'raw files: tag, calib constants, count (for the exported 
                'peptides).

                'Changed PM_REFACTOR 2007-11-19
                addCalibrationInformationForAll(anInCalibration, toReturnBuf)

                'Changed PM_EXPORT_LINESPACER 2007-11-19
                toReturnBuf.Append(vbCrLf)
            End If

            If True Then
                'Changed PM_EXPORT_HEADER 2006-11-17
                'toReturnBuf.Append("Mode: ")
                toReturnBuf.Append("Mode:")
                toReturnBuf.Append(vbTab)

                Dim qModStr As String = _
                  quantApplication.quantModeString(aQuantModeCode, anApplication)
                toReturnBuf.Append(qModStr)
                toReturnBuf.Append(vbCrLf)
            End If

            If True Then
                'Changed PM_EXPORT_HEADER 2006-11-17
                toReturnBuf.Append("Dishes:")
                toReturnBuf.Append(vbTab)
                toReturnBuf.Append(aDishes)
                toReturnBuf.Append(vbCrLf)
            End If

            'Changed PM_REFACTOR 2005-03-07
            'Later:
            'Dim quantModeStr As String = _
            '  "Mode: " & _
            '  frmOptions.quantModeString( _
            '    mOptions.quantModeCode, _
            '    mApplication)

            toReturnBuf.Append(vbCrLf)
            Return toReturnBuf.ToString
        End Function 'FormatAppHeader


        'Changed PM_WEAKLY_TYPED_SPECTRUMCLASSIFICATION 2006-02-15
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function getClassifierObject() _
          As spectrumClassifier

            'Lazy instantiation. It also ensures we have only one instance of that
            'class.

            If mSpectrumClassifier Is Nothing Then
                mSpectrumClassifier = New spectrumClassifier

                'Contains init. But later we should load an XML file and pass
                'the content to some shared helper functions
                'in spectrumClassifier, etc.

                If True Then
                    Dim defaultClassifications As _
                      spectrumClassificationDefinitionsStructure
                    defaultClassifications.classificationList2 = _
                      Nothing 'Keep compiler happy.
                    defaultClassifications.someExtraInfo = _
                      Nothing 'Keep compiler happy.

                    spectrumClassifier.defaultClassifications( _
                      defaultClassifications)

                    'Changed PM_WEAKLY_TYPED_SPECTRUMCLASSIFICATION 2006-02-15
                    'Dim defaultObj As Object = CType(defaultClassifications, Object)
                    'Dim loaded As Object
                    'Try
                    '    'Note: this will work for both versions of the options 
                    '    '      struct because we have both defined. However 
                    '    '      the cast below will fail for the old version....
                    '    Dim fileNameFullPath As String = _
                    '      MSQuantCommon2.fullPathToFileInApplicationFolder( _
                    '        "xxxxxpectrumClassification.xml")
                    '
                    '    'Note: will save the default object if the XML does not exist.
                    '    loaded = MSQuantCommon2.PIL_LoadObject( _
                    '      fileNameFullPath, defaultObj, 1200)
                    '
                    'Catch exceptionObject As Exception
                    '    'This can happen because of versioning. E.g. an old options file.
                    '    Dim errMsg1 As String = _
                    '      "Error: " & exceptionObject.ToString & ControlChars.NewLine
                    '    Dim errMsg2 As String = _
                    '      "Message: " & exceptionObject.Message & ControlChars.NewLine
                    '    Dim errMsg3 As String = ""
                    '    If Not exceptionObject.InnerException Is Nothing Then
                    '        errMsg3 = _
                    '            "Extra info: " & _
                    '            exceptionObject.InnerException.Message & _
                    '            ControlChars.NewLine
                    '    End If
                    '    Dim errMsg As String = errMsg1 & errMsg2 & errMsg3
                    '    MsgBox(errMsg)
                    '    Exit Function
                    'End Try
                    'mSpectrumClassifier.setClassificationInfo( _
                    '  DirectCast(loaded, spectrumClassificationDefinitionsStructure))

                    'Note:
                    '  XML file is accessed on demand, not before the first
                    '  access; e.g. at tooltip parsing time for Finnigan.

                    'Will set mSpectrumClassificationDefinitions.
                    Me.appLoadSpectrumClassificationDefinitions( _
                      MSQconstants.NEW_SPECCLASSIFICATION_FILENAME, _
                      defaultClassifications)

                    mSpectrumClassifier.setClassificationInfo( _
                      mSpectrumClassificationDefinitions)
                End If
            End If

            Return mSpectrumClassifier
        End Function 'getClassifierObject


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function getXICwindowObject() As XICwindow
            Return mXICwindow
        End Function


        'Helper function to display message to the user that a feature
        'is currently only supported for Finnigan files.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Function isFinnegan( _
          ByVal aRawfileMode As rawFileModeEnum) _
          As Boolean

            Dim toReturn As Boolean = True

            If aRawfileMode <> rawFileModeEnum.enumFinnegan Then
                toReturn = False

                MsgBox("Sorry, this feature is currently only supported " & _
                  "for Finnigan data files (.raw).")
            End If

            Return toReturn
        End Function


        'Changed PM_REFACTOR 2005-10-26
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub findOrderByRawFile( _
          ByRef anInPeptideIDs As List(Of visibleAndPeptideTableIndexStruct), _
          ByRef anInProtein As ProteinHitStructure, _
          ByRef anOutOrderTokens() As visibleAndPeptideTableIndexStruct _
          )
            'Old first parameter:
            '  ByRef anInPeptideTokens() As Integer

            'Prepare for MS3 scoring in raw file order. This is to save
            'the overhead of shifting between raw files and to reduce
            'resource exhaustion problems (leaks).
            Dim quantifyInOrder As Boolean = True 'True: one raw file at a time.

            Dim lastIndex As Integer = anInPeptideIDs.Count() - 1
            ReDim anOutOrderTokens(lastIndex)

            'Dim MS3ScoringOrderIndexes(lastIndex) As visibleAndPeptideTableIndexStruct
            If True Then
                Dim pept2 As PeptideHitStructure = _
                  helper.blankPeptide() 'Keep compiler happy.

                Dim i As Integer
                For i = 0 To lastIndex

                    'Changed PM_REFACTOR 2006-03-16
                    'Dim idx As Integer = anInPeptideIndexes(i)
                    'pept = DirectCast(anInProtein.pepts(idx), _
                    '         PeptideHitStructure)

                    'Changed PM_REFACTOR 2008-04-30
                    Dim peptideID As visibleAndPeptideTableIndexStruct = _
                      anInPeptideIDs(i)

                    Dim token As Integer = peptideID.peptToken
                    anInProtein.peptides.peptideByToken( _
                      token, pept2)

                    Dim curNewItem As visibleAndPeptideTableIndexStruct
                    curNewItem.peptToken = -1

                    If pept2.AASequence <> _
                      peptideConstants.SEQUENCE_BADPEPTIDE Then

                        Dim peptToken2 As Integer = token

                        'It should not be necessary to get the peptide once more (?).
                        'Dim thePept As PeptideHitStructure = _
                        '  DirectCast(anInProtein.pepts(peptDataIdx), _
                        '    PeptideHitStructure)


                        'Changed PM_REFACTOR 2008-04-30. Would only work for ***all*** 
                        '  peptides included...
                        'curNewItem.visibleIndex = i
                        curNewItem.visibleIndex = peptideID.visibleIndex

                        curNewItem.peptToken = peptToken2

                        'curNewItem.fileID = thePept.rawFileID
                        curNewItem.fileID = pept2.rawFileID
                    Else
                        'ZZZZZ peptide. Ignore it...
                        Dim peter0 As Integer = 0
                    End If
                    anOutOrderTokens(i) = curNewItem
                Next
                If quantifyInOrder Then

                    'Note: will sort on 2 of the fields (not the token);
                    '        .fileID as primary key,
                    '        .visibleIndex as secondary key.

                    'Changed PM_VS2005_SERIOUS 2006-06-15
                    'anOutOrderTokens.Sort( _
                    '  anOutOrderTokens, New SortByRawFileComparer)
                    Array.Sort( _
                      anOutOrderTokens, New SortByRawFileComparer)
                End If
            End If
        End Sub 'findOrderByRawFile


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub appLoadSpectrumClassificationDefinitions( _
          ByVal aFileName3 As String, _
          ByVal anInDefaultClassifications As _
            spectrumClassificationDefinitionsStructure _
          )

            'Note: only reason for this function is to have a storage place for 
            '      the result - storage place in the MSQuant application object.

            MSQuantCommon2.loadSpectrumClassificationDefinitions2( _
              aFileName3, _
              mSpectrumClassificationDefinitions, _
              anInDefaultClassifications, _
              quantApplication.versionString_withDate())
        End Sub 'appLoadSpectrumClassificationDefinitions


        'Changed PM_LCPEAKDETECTION_OPTIONS 2006-06-21. Phased out.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub old_loadCorrSettings(ByVal aFileName5 As String, _
          ByRef anOutCorrelationSettings As correlationSettingsStructure)

            'Note: the settings file "MascotParserCorrelationSettings.xml" is not
            '      created in this function if it does not exist. Instead it
            '      is created the first time the dialog for the correlation settings 
            '      is opened and closed for the first time.

            'Changed PM_OPTIONSFILES_ONLYINBIN 2004-01-28
            Dim fileNameFullPath As String = _
              MSQuantCommon2.fullPathToFileInApplicationFolder(aFileName5)
            mCorrelationSettingsFileName_FullPath = fileNameFullPath
            Trace.Assert( _
                MSQuantCommon2.isFullPathFileName( _
                  mCorrelationSettingsFileName_FullPath), _
              "PIL ASSERT. Options file is not a full path name: " & _
              mCorrelationSettingsFileName_FullPath)

            defaultCorrSettings(mCorrSettings)

            Dim fileDidNotExist As Boolean = True
            Dim defaultXML As String = _
              "<SOAP-ENV:Envelope" & ControlChars.NewLine & _
              "    xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""                 " & ControlChars.NewLine & _
              "    xmlns:xsd=""http://www.w3.org/2001/XMLSchema""                          " & ControlChars.NewLine & _
              "    xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/""            " & ControlChars.NewLine & _
              "    xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/""            " & ControlChars.NewLine & _
              "    xmlns:clr=""http://schemas.microsoft.com/soap/encoding/clr/1.0""        " & ControlChars.NewLine & _
              "    SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">   " & ControlChars.NewLine & _
              "  <SOAP-ENV:Body>                                                           " & ControlChars.NewLine & _
              "    <a1:correlationSettingsStructure                                        " & ControlChars.NewLine & _
              "        id=""ref-1""                                                        " & ControlChars.NewLine & _
              "        xmlns:a1=""http://schemas.microsoft.com/clr/nsassem/massSpectrometryBase/Mascot%20Parser%2C%20Version%3D1.0.1419.18653%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"">  " & ControlChars.NewLine & _
              "      <doNotInsertNewPeptides>true</doNotInsertNewPeptides>  " & ControlChars.NewLine & _
              "    </a1:correlationSettingsStructure>                       " & ControlChars.NewLine & _
              "  </SOAP-ENV:Body>                                           " & ControlChars.NewLine & _
              "</SOAP-ENV:Envelope>                                         " & ControlChars.NewLine

            Dim NSSpec As String = _
              "http://schemas.microsoft.com/clr/nsassem/massSpectrometryBase/Mascot%20Parser%2C%20Version%3D1.0.1419.18653%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"
            Try
                Dim dummyFileDidNotExist As Boolean

                'From old_loadCorrSettings().
                Dim struHandle As System.Xml.XmlNode = _
                  MSQuantCommon2.optionsFileLoad( _
                    fileNameFullPath, "correlationSettingsStructure", 700, _
                    defaultXML, NSSpec, mCorrelationSettingsDOM, _
                    mCorrelationSettingsNsManager, _
                    dummyFileDidNotExist)

                fileDidNotExist = struHandle.SelectSingleNode( _
                  "doNotInsertNewPeptides", mCorrelationSettingsNsManager) Is Nothing

                MSQuantCommon2.extractBooleanFromXmlNode( _
                  struHandle, mCorrelationSettingsNsManager, "doNotInsertNewPeptides", _
                  mCorrSettings.doNotInsertNewPeptides)

                'Changed PM_LC_TIMERANGE 2003-12-17
                MSQuantCommon2.extractBooleanFromXmlNode( _
                  struHandle, mCorrelationSettingsNsManager, "insertPeptidesInLCTimeRange", _
                  mCorrSettings.insertPeptidesInLCTimeRange)
                MSQuantCommon2.extractDoubleFromXmlNode(struHandle, mCorrelationSettingsNsManager, "startLCtimeForInsertion_Secs", _
                  mCorrSettings.startLCtimeForInsertion_Secs)
                MSQuantCommon2.extractDoubleFromXmlNode(struHandle, mCorrelationSettingsNsManager, "endLCtimeForInsertion_Secs", _
                  mCorrSettings.endLCtimeForInsertion_Secs)

                'Changed PM_LCPEAK_WINDOW_USERDEFINED 2003-12-18
                MSQuantCommon2.extractDoubleFromXmlNode( _
                  struHandle, mCorrelationSettingsNsManager, "leftLCwindowSecs", _
                  mCorrSettings.leftLCwindowSecs)
                MSQuantCommon2.extractDoubleFromXmlNode( _
                  struHandle, mCorrelationSettingsNsManager, "rightLCwindowSecs", _
                  mCorrSettings.rightLCwindowSecs)


            Catch e2 As Exception
                MsgBox("Could load settings from options file " & fileNameFullPath & _
                  ". Using default values instead." & ControlChars.NewLine & ControlChars.NewLine & _
                  "Some details, exception: " & e2.Message & "..........")

                'Use some file name that does not exist to force loading default.
                'Should we change optionsFileLoad to have a parameter to force-load?
                Dim dummyFileDidNotExist As Boolean

                'From old_loadCorrSettings().
                Dim struHandle2 As System.Xml.XmlNode = _
                  MSQuantCommon2.optionsFileLoad( _
                    "xyz921.xml", "correlationSettingsStructure", 1200, _
                    defaultXML, NSSpec, mCorrelationSettingsDOM, mCorrelationSettingsNsManager, _
                    dummyFileDidNotExist)
                fileDidNotExist = True
            End Try

            If fileDidNotExist Then
                'If file did not exist:
                'Persist the default instead such that the configuration
                'file is always created if it does not exist.
                old_PersistCorrSettings()
            Else
                Dim peter9 As Integer = 9
            End If

            anOutCorrelationSettings = mCorrSettings
        End Sub 'old_loadCorrSettings


        'Changed PM_LCPEAKDETECTION_OPTIONS 2006-06-21. Phased out.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Shared Sub PersistCorrSettings( _
          ByRef anInPersist_fileNameFullPath As String, _
          ByRef anInCorrelationSettings As correlationSettingsStructure _
          )

            'Changed PM_XMLCOMMENTS_LINEBREAK 2008-02-08
            Dim ssb As StringBuilder = New StringBuilder(100)

            Dim sfX As XmlTextWriter = _
              MSQuantCommon2.newStandardXMLout( _
                anInPersist_fileNameFullPath, Nothing, Nothing, _
                quantApplication.versionString_withDate())

            SDUP_emptyCommentLine(sfX)
            SDUPcomment(sfX, _
              "Changed: 2006-06-21 PM  Initial version...", ssb)
            SDUPcomment(sfX, _
              "Changed: 2007-05-03 PM  New standard comment header.", ssb)
            SDUPcomment(sfX, _
              "Changed: 2007-xx-xx PM", ssb)
            SDUP_emptyCommentLine(sfX)

            sfX.WriteStartElement("correlationAndLCpeaksDetectionSettings")

            sfX.WriteElementString( _
              "doNotInsertNewPeptides", Nothing, _
              anInCorrelationSettings.doNotInsertNewPeptides.ToString)

            sfX.WriteElementString( _
              "insertPeptidesInLCTimeRange", Nothing, _
              anInCorrelationSettings.insertPeptidesInLCTimeRange.ToString)

            sfX.WriteElementString( _
              "startLCtimeForInsertion_Secs", Nothing, _
              anInCorrelationSettings.startLCtimeForInsertion_Secs.ToString)

            sfX.WriteElementString( _
              "endLCtimeForInsertion_Secs", Nothing, _
              anInCorrelationSettings.endLCtimeForInsertion_Secs.ToString)

            sfX.WriteElementString( _
              "leftLCwindowSecs", Nothing, _
              anInCorrelationSettings.leftLCwindowSecs.ToString)
            sfX.WriteElementString( _
              "rightLCwindowSecs", Nothing, _
              anInCorrelationSettings.rightLCwindowSecs.ToString)

            sfX.WriteElementString( _
              "SILACdishForLCpeakDetection", Nothing, _
              anInCorrelationSettings.SILACdishForLCpeakDetection.ToString)

            sfX.WriteElementString( _
              "useHighestLCprofileForLCpeakDetection", Nothing, _
              anInCorrelationSettings.useHighestLCprofileForLCpeakDetection.ToString)

            sfX.WriteEndElement()
            SDUP_emptyCommentLine(sfX)
            SDUP_emptyCommentLine(sfX)

            sfX.Flush()
            sfX.Close()
        End Sub 'PersistCorrSettings


        'Changed PM_LCPEAKDETECTION_OPTIONS 2006-06-21. Phased out.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub loadCorrSettings( _
          ByVal aFileName5 As String, _
          ByRef anOutCorrelationSettings As correlationSettingsStructure)

            Dim fileNameFullPath As String = _
              MSQuantCommon2.fullPathToFileInApplicationFolder(aFileName5)

            mCorrelationSettingsFileName_FullPath = fileNameFullPath
            Trace.Assert(MSQuantCommon2.isFullPathFileName( _
              mCorrelationSettingsFileName_FullPath), _
              "PIL ASSERT. Options file is not a full path name: " & _
              mCorrelationSettingsFileName_FullPath)

            defaultCorrSettings(mCorrSettings)

            Dim fileDidNotExist4 As Boolean = Not File.Exists(fileNameFullPath)

            Try
                If fileDidNotExist4 Then
                    'If file did not exist:
                    'Persist the default instead such that the configuration
                    'file is always created if it does not exist.
                    PersistCorrSettings(aFileName5, mCorrSettings)
                Else
                    Dim dummyFileDidNotExist As Boolean

                    'From loadCorrSettings().
                    Dim struHandle As System.Xml.XmlNode = _
                      MSQuantCommon2.optionsFileLoad( _
                        fileNameFullPath, "/", 500, _
                        "", "", mCorrelationSettingsDOM, _
                        mCorrelationSettingsNsManager, _
                        dummyFileDidNotExist)

                    Dim struc2 As XmlNode = _
                      struHandle.SelectSingleNode( _
                         "//correlationAndLCpeaksDetectionSettings" _
                        )

                    MSQuantCommon2.extractBooleanFromXmlNode( _
                      struc2, mCorrelationSettingsNsManager, _
                      "doNotInsertNewPeptides", _
                      mCorrSettings.doNotInsertNewPeptides)
                    MSQuantCommon2.extractBooleanFromXmlNode( _
                      struc2, mCorrelationSettingsNsManager, _
                      "insertPeptidesInLCTimeRange", _
                      mCorrSettings.insertPeptidesInLCTimeRange)
                    MSQuantCommon2.extractDoubleFromXmlNode( _
                      struc2, mCorrelationSettingsNsManager, _
                      "startLCtimeForInsertion_Secs", _
                      mCorrSettings.startLCtimeForInsertion_Secs)
                    MSQuantCommon2.extractDoubleFromXmlNode( _
                      struc2, mCorrelationSettingsNsManager, _
                      "endLCtimeForInsertion_Secs", _
                      mCorrSettings.endLCtimeForInsertion_Secs)
                    MSQuantCommon2.extractDoubleFromXmlNode( _
                      struc2, mCorrelationSettingsNsManager, _
                      "leftLCwindowSecs", _
                      mCorrSettings.leftLCwindowSecs)
                    MSQuantCommon2.extractDoubleFromXmlNode( _
                      struc2, mCorrelationSettingsNsManager, _
                      "rightLCwindowSecs", _
                      mCorrSettings.rightLCwindowSecs)

                    'Changed PM_LCPEAKDETECTION_OPTIONS 2006-06-21
                    MSQuantCommon2.extractIntegerFromXmlNode( _
                      struc2, mCorrelationSettingsNsManager, _
                      "SILACdishForLCpeakDetection", _
                      mCorrSettings.SILACdishForLCpeakDetection)
                    MSQuantCommon2.extractBooleanFromXmlNode( _
                      struc2, mCorrelationSettingsNsManager, _
                      "useHighestLCprofileForLCpeakDetection", _
                      mCorrSettings.useHighestLCprofileForLCpeakDetection)
                End If

            Catch exceptionObject As Exception
                MSQuantCommon2.displayStandardExceptionInfo( _
                  exceptionObject, _
                  "Could not open correlation settings file " & aFileName5)
                Exit Sub
            End Try

            anOutCorrelationSettings = mCorrSettings 'Needed.
        End Sub 'loadCorrSettings


        'Changed PM_REFACTOR 2006-10-25. Moved to here from MascotResultParser.vb
        'Should be moved to a more appropriate place.
        '
        'Changed PM_LOWSCORING_PEPTIDES_IN_QUANTITATIONWINDOW 2005-12-12
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Shared Sub sortPeptidesBySequenceAndByScore( _
          ByRef aInProteins As List(Of ProteinHitStructure), _
          ByRef anInPeptideFilterSpecification As peptideFilterStructure)

            'Old:
            '  ByRef aProteins As ArrayList

            Dim parsProt As ProteinHitStructure
            Dim lastIndex As Integer = aInProteins.Count - 1
            Dim i As Integer
            For i = 0 To lastIndex
                parsProt = aInProteins(i)

                parsProt.peptides.setDefaultSortOrder( _
                  peptideSortOrderEnum.enumSequenceThenScore)

                'Changed PM_PEPTIDE_FILTER 2006-03-20
                parsProt.peptides.setPermanentPeptideFilter( _
                  anInPeptideFilterSpecification)

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

                Dim peptideCount As Integer = _
                  parsProt.peptides.peptideCount(token)

                parsProt.effectivePeptideCount = peptideCount

                aInProteins(i) = parsProt 'Write-back
            Next 'Through proteins.
        End Sub 'sortPeptidesBySequence2


        'Changed PM_REFACTOR 2006-10-25. Moved to here from MascotResultParser.vb
        'Should be moved to a more appropriate place.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '*    Helper function                                                       *
        '****************************************************************************
        Public Shared Sub postProteinParsing( _
          ByRef anInRetentionTimeCorrelator As retentionTimeCorrelator, _
          ByRef anInRawFiles() As massSpectrometryBase.fileSpecStructure, _
          ByVal aDoNotInsertNewPeptides As Boolean, _
          ByRef anInOutProteinList As List(Of ProteinHitStructure), _
          ByRef anInMultipleRawFilesHandling As MultipleRawFilesHandling, _
          ByVal anInsertPeptidesInLCTimeRange As Boolean, _
          ByVal aStartLCtimeForInsertion_Secs As Double, _
          ByVal endLCtimeForInsertion_Secs As Double, _
          ByRef anInPeptideFilterSpecification As peptideFilterStructure, _
          ByRef anInOutApp As quantApplication _
          )

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

            'We are not done yet - new peptides remain to be inserted.
            anInRetentionTimeCorrelator.ParsingCompleted(anInRawFiles)

            'not not !!!
            If Not aDoNotInsertNewPeptides Then
                'Insert new peptides found during the correlation process.
                'Type is peptideToBeAddedInfoStruct.

                'Dim peptidesToBeAdded As ArrayList = _
                Dim peptidesToBeAdded2 As List(Of peptideToBeAddedInfoStruct) = _
                  anInRetentionTimeCorrelator.peptidesToBeAdded()

                'Wiff combined files????

                'Changed PM_RETCORR_ANYTIME 2006-10-25
                ''Changed PM_INSERTED_QUERYNUMBER 2003-10-29
                ''Dim queryNumber As Integer = 20000
                'Dim queryNumber As Integer = -20000  Now in application.

                'Changed PM_FRAGMENTS_FOR_INSERTED 2004-11-24.
                'Outer loop: one raw file at a time
                Dim lastIndex2 As Integer = anInRawFiles.Length - 1
                Dim i As Integer
                For i = 0 To lastIndex2
                    Dim curTag As Integer = anInRawFiles(i).tag2

                    Dim lastIndex As Integer = peptidesToBeAdded2.Count - 1
                    Dim j As Integer
                    For j = 0 To lastIndex

                        'Note: this is for inserted peptides/retention time correlation.
                        Dim curPeptToBeAdded As _
                          massSpectrometryBase.peptideToBeAddedInfoStruct = _
                            peptidesToBeAdded2(j)

                        'Changed PM_FRAGMENTS_FOR_INSERTED 2004-11-25
                        Dim rawFileRefNum As Integer = _
                          curPeptToBeAdded.PDBA_rawFileID

                        If rawFileRefNum = curTag Then

                            'Changed PM_UNNECESSARY_CODE_INSERTING_PEPTIDES 2007-01-08. Moved up 
                            '  here; decision on wether to add peptide or not. This will save
                            '  unnessary operations.

                            'Changed PM_RETT_CORR_BUG 2008-03-05. Postpone
                            '  this call to after the insertion time filter
                            '  has been applied.
                            ''Find nearest MS-MS spectrum and adjust stored
                            ''retention time slightly.
                            'Dim foundMSMS As Boolean
                            'Dim retentionTimeWithinFile As Boolean
                            'Dim retSecs As Double = _
                            '  anInMultipleRawFilesHandling.retentionTimeForNearestMSMSspectrum( _
                            '     curPeptToBeAdded.PDBA_rawFileID, _
                            '     curPeptToBeAdded.calibratedRetentionTimeSecs, _
                            '     180 * 60, 180 * 60, 1999.9, foundMSMS, _
                            '     retentionTimeWithinFile)

                            'Changed PM_LC_TIMERANGE 2003-12-17
                            Dim doInsertPeptide As Boolean = True
                            Dim retSecs2 As Double = -44444.444 'Invalid value.

                            If True Then 'Insert or not.

                                Dim retentionTimeWithinFile2 As Boolean = True
                                If anInsertPeptidesInLCTimeRange Then

                                    'Changed PM_RETT_CORR_BUG 2008-03-05. Bug!!!!,
                                    '  ***Seconds*** multiplied by 60!!!.
                                    ''Changed PM_REFACTOR 2007-01-08. Preparation
                                    ''  for PM_UNNECESSARY_CODE_INSERTING_PEPTIDES.
                                    ''Dim peptideLCtimeSecs As Double = _
                                    ''  60.0 * newPept.MSMSretentionTimeMinutes
                                    'Dim peptideLCtimeSecs As Double = 60.0 * retSecs
                                    Dim peptideLCtimeSecs2 As Double = _
                                      curPeptToBeAdded.calibratedRetentionTimeSecs
                                    '  
                                    If peptideLCtimeSecs2 < _
                                         aStartLCtimeForInsertion_Secs Or _
                                       peptideLCtimeSecs2 > _
                                         endLCtimeForInsertion_Secs Then

                                        'What about statistics????? Should we use LC time window
                                        'earlier.
                                        doInsertPeptide = False
                                    Else
                                        Dim peter2 As Integer = 2

                                    End If
                                End If

                                'Changed PM_CORR_TROUBLE 2008-03-06
                                If doInsertPeptide Then
                                    Dim approxRetT As Double = _
                                      curPeptToBeAdded.calibratedRetentionTimeSecs

                                    If approxRetT > 8324.78 And approxRetT < 8324.79 Then
                                        Dim peter2 As Integer = 2
                                    End If

                                    'Changed PM_RETT_CORR_BUG 2008-03-05
                                    'Only now call retentionTimeForNearestMSMSspectrum().
                                    'It this way we can work-around an error
                                    'by setting the insertion range.
                                    Dim foundMSMS As Boolean
                                    retSecs2 = _
                                      anInMultipleRawFilesHandling.retentionTimeForNearestMSMSspectrum( _
                                         curPeptToBeAdded.PDBA_rawFileID, _
                                         approxRetT, _
                                         180 * 60, 180 * 60, 1999.9, _
                                         foundMSMS, _
                                         retentionTimeWithinFile2)
                                    'Within file checked below.

                                End If

                                'Changed PM_FRAGMENTS_FOR_INSERTED 2004-11-25
                                If Not retentionTimeWithinFile2 Then
                                    doInsertPeptide = False
                                Else
                                    Dim peter9 As Integer = 9
                                End If

                            End If

                            If doInsertPeptide Then
                                Dim proteinIndex As Integer = _
                                  curPeptToBeAdded.proteinIndex

                                Dim prot As ProteinHitStructure = _
                                  anInOutProteinList(proteinIndex)

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

                                'Changed PM_RETT_CORR_BUG 2008-03-05
                                Trace.Assert(retSecs2 >= 0.0, _
                                  "PIL ASSERT. retSecs2 is undefined: " & _
                                  retSecs2 & ".")

                                newPept.MSMSretentionTimeMinutes = retSecs2 / 60.0

                                newPept.rawFileID = _
                                  curPeptToBeAdded.PDBA_rawFileID 'Moved up here.

                                'Note: we don't inherit this number from the copy 
                                '   peptide as it. But it should probably be set 
                                '   more appropriately for Analyst such that the 
                                '   experiment number correspond to what is
                                '   found above.
                                newPept.experimentNumber = 1

                                'Changed PM_INSERTEDPEPTIDES_LCWINDOW_TROUBLE 2004-01-26
                                'newPept.retentionTimeStartMinutes = _
                                '  newPept.MSMSretentionTimeMinutes - 60.0 / 60.0
                                'newPept.retentionTimeEndMinutes = _
                                '  -(newPept.MSMSretentionTimeMinutes + 1.5 * 60.0 / 60.0) 'Negative value is
                                newPept.retentionTimeStartMinutes = _
                                  newPept.MSMSretentionTimeMinutes

                                newPept.retentionTimeEndMinutes = 0.0

                                'Changed PM_PEPT_RAWFILE_PATH 2003-11-05
                                newPept.rawFileFullPath = _
                                  rawDataFileHandling.getFullRawFilePath( _
                                    anInRawFiles, curPeptToBeAdded.PDBA_rawFileID)

                                newPept.MascotScore = _
                                  PILpeptides.FIXED_SCORE_FOR_INSERTED_PEPTIDES '99

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

                                'Changed PM_RETCORR_ANYTIME 2006-10-25
                                'newPept.queryNumber = queryNumber
                                newPept.queryNumber = anInOutApp.getUniqueNumber()

                                newPept.checkboxChecked = True
                                newPept.MascotColour = _
                                  mascotColourEnum.enumLightRed
                                newPept.verified = True 'Overwritten below !?

                                'Note: this is for inserted peptides/retention time correlation.
                                If True Then
                                    newPept.AASequence = curPeptToBeAdded.pepSequence

                                    'Changed PM_SHORT_EXPORT 2005-12-01
                                    newPept.leftFlankAA = _
                                      curPeptToBeAdded.PDBA_leftFlankAA
                                    newPept.rightFlankAA = _
                                      curPeptToBeAdded.PDBA_rightFlankAA

                                    newPept.measuredMCR = curPeptToBeAdded.measuredMCR
                                    newPept.measuredMass = curPeptToBeAdded.measuredMass
                                    newPept.MascotCalculatedMass = _
                                      curPeptToBeAdded.calculatedMass
                                    newPept.charge = curPeptToBeAdded.charge

                                    'Changed PM_BADPEAKREASON_BUG 2003-09-26
                                    newPept.goodMSpeak = curPeptToBeAdded.goodMSpeak
                                    newPept.badPeakReason = _
                                      curPeptToBeAdded.badPeakReason

                                    'Changed PM_GENERALISED_QUANT_MODE_OLDMODHITMARKER 2003-12-08
                                    ''Changed PM_CORR_MODS_FOR_INSERTED 2003-10-03
                                    'newPept.modHit = curPeptToBeAdded.modHit

                                    'Changed PM_CORR_CHECKEDINHERIT_FOR_INSERTED 2003-10-08
                                    newPept.verified = curPeptToBeAdded.peptVerified

                                    'Changed PM_INHERIT_MODS_FOR_INSERTED 2004-11-23
                                    newPept.modHits2 = curPeptToBeAdded.modHits4

                                    'Changed PM_FAST_SERIALISATION_BUG_SAVE_INSERTED_PEPTIDES 2007-01-08
                                    newPept.uncalibratedSILACmasses2 = curPeptToBeAdded.uncalibratedSILACmasses4

                                    'Changed PM_FAST_SERIALISATION_BUG_LOAD_INSERTED_PEPTIDES 2007-01-08
                                    newPept.version = curPeptToBeAdded.version2
                                End If 'Note: this is for inserted peptides/retention time correlation.

                                'And finally, adding the new peptide...
                                prot.peptides.addPeptide(newPept)
                                anInOutProteinList(proteinIndex) = prot 'Write-back.
                            Else
                                Dim peter29 As Integer = 29
                            End If
                        Else
                            Dim peter41 As Integer = 41
                        End If
                    Next 'j, innner loop
                Next 'i, outer loop, trough raw files
            Else
                anInRetentionTimeCorrelator.PeptidesNotActuallyInserted()
            End If

            quantApplication.sortPeptidesBySequenceAndByScore( _
              anInOutProteinList, anInPeptideFilterSpecification)

            'Changed PM_CORR_CONTINUE_AND_REPORT 2004-02-16
            Dim corrResult As corrResultStruct = _
              anInRetentionTimeCorrelator.correlationResult()
            If Not corrResult.correlationSuccesful Then

                'Correlation is only used for insertion of new peptides
                'so we only warn in that case.
                If Not aDoNotInsertNewPeptides Then
                    MsgBox( _
                      "Warning: no or very few peptides were inserted even though " & _
                        "insertion was enabled in Tools/Correlation settings. " & _
                      "Reason: correlation failed for " & corrResult.failureCount & _
                      " file correlation pairs (out of " & _
                      corrResult.totalCount & "). " & _
                      "Please review the correlation report and plot the retention " & _
                        "times pairs in question..... " & ControlChars.NewLine & _
                      ControlChars.NewLine & _
                      "Details: " & corrResult.reportStr _
                    )
                Else
                    Dim peter9 As Integer = 9
                End If
            Else
                Dim peter10 As Integer = 10
            End If
        End Sub 'postProteinParsing


        'Changed PM_RETCORR_ANYTIME 2006-10-25
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function getUniqueNumber() As Integer
            Dim toReturn As Integer = mUniqueNumber
            mUniqueNumber -= 1
            Return toReturn
        End Function 'getUniqueNumber


        'Changed PM_REFACTOR 2006-11-27
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Function extractRange( _
          ByRef anFullCommandLine As String, _
          ByRef anOptionName As String, _
          ByRef anOutProteinStart As Integer, _
          ByRef anOutProteinEnd As Integer _
          ) _
          As Boolean
            'True: parameters OK.

            Dim toReturn As Boolean = True

            Dim paramStr As String = _
              MSQuantCommon2.extractCommandParameters( _
                anOptionName, anFullCommandLine)

            'Changed PM_CMD_MS3_AND_PTM 2006-11-27
            'Dim startProtein As Integer = 1
            'Dim endProtein As Integer = 99999
            anOutProteinStart = -1
            anOutProteinEnd = -1

            If paramStr.Length > 0 Then
                Dim items As String() = Split(paramStr, "-")
                Dim startStr As String = items(0)

                If IsNumeric(startStr) Then
                    anOutProteinStart = CInt(startStr)

                    If items.Length = 2 Then
                        Dim endStr As String = items(1)

                        If IsNumeric(endStr) Then
                            anOutProteinEnd = CInt(endStr)
                        Else
                            MsgBox(ERRMSGPREFIX1 & _
                              " Second parameter for option """ & _
                              anOptionName & _
                              """, " & endStr & ", is not numeric. " & _
                              anFullCommandLine)
                            toReturn = False
                        End If
                    Else
                        MsgBox( _
                          ERRMSGPREFIX1 & _
                          " Too many parameters, " & items.Length() & _
                          ", for option """ & anOptionName & _
                          """, " & paramStr & ". " & _
                          anFullCommandLine)
                        toReturn = False
                    End If
                Else
                    MsgBox(ERRMSGPREFIX1 & _
                      " First parameter for option """ & anOptionName & _
                      """, " & startStr & ", is not numeric." & _
                      anFullCommandLine)
                    toReturn = False
                End If
            Else
                Dim peter6 As Integer = 6 'Not specified.
            End If

            Return toReturn
        End Function 'extractRange


        'Changed PM_COMMANDLINE 2006-11-14
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function setCommands(ByRef anInCommandStr As String) _
        As Boolean

            'Later: what if not all (required) parameters are specified??

            Dim toReturn As Boolean = True

            Const QUANT_RANGE As String = "quant"

            Const PTM_RANGE As String = "PTM"
            Const MS3RANGE As String = "MS3"

            Dim cmdLineStr As String = _
              "Command line was: " & anInCommandStr

            Dim binPath As String = _
              MSQuantCommon2.extractCommandParameters("bin", anInCommandStr)
            If binPath.Length() = 0 Then
                toReturn = False
            End If
            mAutomationInfo.binPath = binPath

            If toReturn Then 'Specification of binary is required
                'Changed PM_REFACTOR 2006-11-27
                Dim res1 As Boolean = _
                  Me.extractRange( _
                    anInCommandStr, QUANT_RANGE, _
                    mAutomationInfo.quantProteinsStart, _
                    mAutomationInfo.quantProteinsEnd)

                Dim res2 As Boolean = _
                  Me.extractRange( _
                    anInCommandStr, PTM_RANGE, _
                    mAutomationInfo.PTMscoreProteinsStart, _
                    mAutomationInfo.PTMscoreProteinsEnd)

                Dim res3 As Boolean = _
                  Me.extractRange( _
                    anInCommandStr, MS3RANGE, _
                    mAutomationInfo.ms3scoreProteinsStart, _
                    mAutomationInfo.ms3scoreProteinsEnd)

                toReturn = res1 And res2 And res3
            End If

            Dim maxPeptidesStr As String = _
              MSQuantCommon2.extractCommandParameters("maxPep", anInCommandStr)
            mAutomationInfo.maxPeptides = 999999 'Default if not
            '  specified.
            If maxPeptidesStr.Length > 0 Then
                'Later: more error handling - e.g. is it numeric.
                mAutomationInfo.maxPeptides = CInt(maxPeptidesStr)
            Else
                Dim peter3 As Integer = 3 'Not specified.
            End If

            Return toReturn
        End Function 'setCommands


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function getAutomationInfo() As automationInfoStructure
            Return mAutomationInfo
        End Function 'getAutomationInfo


        'Changed PM_COMMANDLINE 2006-11-15
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub quantifiedAnotherPeptide()
            mQuantifiedPeptideCount += 1
        End Sub 'quantifiedAnotherPeptide


        'Changed PM_COMMANDLINE 2006-11-15
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function getQuantifiedPeptideCount() _
          As Integer

            Return mQuantifiedPeptideCount
        End Function 'getQuantifiedPeptideCount


        'Changed PM_PARSESPEED_INTERNAL 2006-11-28
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub startStopWatch()
            mStopWatch_Ticks1 = Environment.TickCount
            mStopWatch_Mem1 = System.GC.GetTotalMemory(False)
        End Sub 'startStopWatch


        'Changed PM_PARSESPEED_INTERNAL 2006-11-28
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function stopStopWatch(ByRef aOutMemoryDiff_MB As Double) _
        As Double

            Dim ticks2 As Integer = Environment.TickCount
            mStopWatch_LastTimed = (ticks2 - mStopWatch_Ticks1) / 1000.0

            Dim afterBytes As Long = System.GC.GetTotalMemory(False)
            mStopWatch_LastMemDiff_MB = _
              (CDbl(afterBytes - mStopWatch_Mem1)) / 1024 / 1024

            aOutMemoryDiff_MB = mStopWatch_LastMemDiff_MB
            Return mStopWatch_LastTimed
        End Function 'startStopWatch


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub userSelectFolder( _
          ByVal anInDialogTitle As String, ByRef aInOutFolderName As String)

            'Note: in case the user cancels
            'Future: set dialog up such that it shows the passed
            '        in folder (if it exists).

            'Use of .NET 1.1's FolderBrowserDialog
            Dim folderBrowserDialog1 As FolderBrowserDialog = _
              New FolderBrowserDialog()
            folderBrowserDialog1.Description = anInDialogTitle
            folderBrowserDialog1.ShowNewFolderButton = False
            ' Default to the Desktop folder.
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Desktop

            Dim result As DialogResult = folderBrowserDialog1.ShowDialog()
            If (result = Windows.Forms.DialogResult.OK) Then
                Dim folder2 As String = folderBrowserDialog1.SelectedPath
                aInOutFolderName = folder2
            End If
        End Sub 'userSelectFolder


        'Changed PM_VERSION_INFO 2007-04-19
        'Note: keep versionString_dateOnly(), versionString()
        '      and versionString_withDate() at the bottom of
        '      this file; for easier navigation...
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Function versionString_withDate() _
          As String

            'Note: we could cache the return string as it is a constant...

            Dim toReturn As String = _
              quantApplication.versionString() & _
              ", " & _
              quantApplication.versionString_dateOnly()

            Return toReturn
        End Function 'versionString_withDate


        'Changed PM_REFACTOR 2008-05-05. Moved from frmProteinList.vb
        ''Changed PM_EXPORTS_ON_SELECTION 2005-03-01
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Function xxFormatTextPeptides2( _
          ByVal aInProteinAndPeptidesFilter2 As proteinAndPeptidesFilterStructure2, _
          ByRef aProteinsSubset_dataStructureIndices2 As List(Of Integer), _
          ByRef aProteinList2 As List(Of ProteinHitStructure), _
          ByRef anInCalibration As SDUPrecalibrator, _
          ByVal aQuantModeCode As Integer, _
          ByRef anApp As quantApplication, _
          ByVal anInOptions As OptionsStruct2, _
          ByRef anInPeptideTokens As List(Of Integer)) _
          As String

            'Old:
            '  ByRef aProteinsSubset_dataStructureIndices As ArrayList
            '  ByRef aProteinList As ArrayList
            '  ByVal aRecalibSlope As Double, _
            '  ByVal aRecalibOffset As Double, _

            'Changed PM_SPECTRAEXPORT_GENERALISED 2008-05-06
            If Not anInPeptideTokens Is Nothing Then
                Trace.Assert(aProteinList2.Count = 1, _
                  "PIL ASSERT. Peptide selection is only valid for a single protein.")
            End If

            Dim sb As System.Text.StringBuilder = _
              New System.Text.StringBuilder(20)
            Dim len As Integer = aProteinsSubset_dataStructureIndices2.Count
            If len > 0 Then
                'aProteinList: real type of items is ProteinHitStructure

                'Changed PM_PROTEINEXPORT_EXCEPTION 2006-11-08
                Dim dishes As Integer = anApp.getDishes(aQuantModeCode)

                Dim header1 As String = _
                  quantApplication.FormatAppHeader( _
                    anInCalibration, aQuantModeCode, anApp, dishes)

                Dim settings As miscSettingsStructure2Struct = _
                  anApp.getMiscSettings()

                'This one is separate as it is repeated for every
                'protein if protein information has been selected by the user.
                'Dim peptideHeaderSB As StringBuilder = 
                Dim peptideHeaderSB As StringBuilder = _
                  New StringBuilder(3000) 'What is a good size??
                quantApplication.peptideTableHeaderWithAheader( _
                  "", settings.option1, _
                  anApp, aQuantModeCode, peptideHeaderSB)

                'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-27
                'Assume export... (for peptide filter)
                Dim peptideFilter As peptideFilterStructure = _
                  anInOptions.peptideFilters(peptideFilterEnum.enumExport2)

                'Parameters.
                Dim includeProteins As Boolean = _
                  aInProteinAndPeptidesFilter2.includeProteinInformation2

                'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-27
                'Dim includePeptides As Boolean = _
                '  aInProteinAndPeptidesFilter.includeAllPeptides Or _
                '  aInProteinAndPeptidesFilter.includeQuantifiedPeptides Or _
                '  aInProteinAndPeptidesFilter.includeVerifiedPeptides
                '
                'Dim includeQuantifiedPeptides As Boolean = _
                '  aInProteinAndPeptidesFilter.includeQuantifiedPeptides
                'Dim includeVerifiedPeptides As Boolean = _
                '  aInProteinAndPeptidesFilter.includeVerifiedPeptides
                Dim includePeptides2 As Boolean = _
                  aInProteinAndPeptidesFilter2.includePeptides

                'Changed PM_SPECTRAEXPORT_GENERALISED 2008-05-05
                Dim includeSpectra As Boolean = _
                  aInProteinAndPeptidesFilter2.includeSpectra

                'Moved down here, just before first use...
                sb.Capacity = 32768 'We need something better - an
                '  estimator of final size.

                'Recalibration constants and other things that appear only once.
                'Possible future items:
                '  1. raw and Mascot result file name
                '  2.
                sb.Append(header1)

                Dim lastIndex As Integer = len - 1
                Dim i As Integer
                For i = 0 To lastIndex 'Protein loop.
                    Dim proteinIndex As Integer = _
                      aProteinsSubset_dataStructureIndices2(i)

                    Dim someProt As ProteinHitStructure = aProteinList2(proteinIndex)

                    If includeProteins Then
                        If i = 0 Then
                            'sb.Append(proteinHeaderStr)
                            quantApplication.addProteinTableHeaders(dishes, sb)
                        End If
                        quantApplication.addProteinLine(someProt, sb, dishes)
                    End If

                    If includePeptides2 Then
                        If i = 0 Or includeProteins Then
                            sb.Append(peptideHeaderSB)
                        End If

                        'Changed PM_PEPTIDE_FILTER 2006-03-20. No need for
                        'conditional as the loop will just run zero times
                        'if the (effective) number of peptides is zero.
                        ''Changed PM_REFACTOR 2006-03-15
                        ''Dim peptides As Integer = someProt.pepts.Count
                        'Dim peptides As Integer = someProt.peptides.peptideCount()
                        'If peptides > 0 Then 'Needed??
                        '    sb.Append( _
                        '      quantApplication.NakedPeptideTable( _
                        '        someProt, _
                        '        includeQuantifiedPeptides, includeVerifiedPeptides, _
                        '        anApp) _
                        '      )
                        'End If

                        'In this function we output protein and peptides. We assume
                        'it is called from some exporting function.


                        'Changed PM_SPECTRAEXPORT_GENERALISED 2008-05-05. Add
                        '  parameter includeSpectra...

                        quantApplication.NakedPeptideTable3( _
                            someProt, _
                            anApp, _
                            aQuantModeCode, _
                            peptideFilter, _
                            includeSpectra, _
                            sb, _
                            anInPeptideTokens)
                    End If
                Next i 'Through proteins

                'What about filter for quantified peptides??? Present dialog?
                'Dialog:
                '  Peptide filter:
                '    1. Include quantified
                '    2. Include verified
                '  Other
                '    1. Include protein headers
                '    2. Include peptide information
            End If 'Non-empty selection

            Return sb.ToString
        End Function 'xxFormatTextPeptides2


        'Changed PM_REFACTOR 2003-03-11
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        'This (utility) function could be anywhere - it is not
        'specific to quantitation at all.
        Public Shared Function sec2minuteString(ByVal aSeconds As Double) _
          As String

            Dim minutes As Integer = CInt(Fix(aSeconds / 60))
            '  Fix truncates to lower integer
            Dim secs As Integer = CInt(aSeconds - minutes * 60)
            Dim timeStr As String = minutes.ToString & ":"
            If secs < 10 Then
                timeStr &= "0" & secs
            Else
                timeStr &= secs
            End If
            Return timeStr
        End Function 'sec2minuteString()


        'Changed PM_REFACTOR 2008-05-05. Moved from QuantWindow.vb and made to 
        'accept StringBuilder input parameter to add text to.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        'Input: const ref
        'Formats text representing the list of spectra associated with a peptide.
        Private Shared Sub CalSpectrumTableSaveStr2( _
          ByRef aPept As PeptideHitStructure, _
          ByRef anInOutSB As System.Text.StringBuilder)

            'Changed PM_REFACTOR 2006-10-12
            'Dim listHeader As String = _
            '  "Peptide sequence: " & vbTab & aPept.AASequence
            'listHeader &= vbCrLf & vbCrLf
            'listHeader &= _
            '  "Used for quantitation" & vbTab & _
            '  "Retention time" & vbTab & _
            '  "I(w.t.)" & vbTab & _
            '  "High ratio" & vbTab & _
            '  "Even higher ratio" & vbTab & _
            '  vbCrLf
            'Dim toReturn As String = listHeader

            'Dim resSB As StringBuilder = New StringBuilder(2000)

            'Changed PM_SPECTRAEXPORT_GENERALISED 2008-05-05. Now in peptide line...
            'If True Then
            '    anInOutSB.Append("Peptide sequence: ")
            '    anInOutSB.Append(ControlChars.Tab)
            '    anInOutSB.Append(aPept.AASequence)
            '    anInOutSB.Append(PILInputOutput.LINEEND)
            '    anInOutSB.Append(PILInputOutput.LINEEND)
            'End If


            anInOutSB.Append("Used for quantitation")
            anInOutSB.Append(ControlChars.Tab)
            anInOutSB.Append("Retention time [min]")
            anInOutSB.Append(ControlChars.Tab)
            anInOutSB.Append("Retention time [secs]")
            anInOutSB.Append(ControlChars.Tab)
            anInOutSB.Append("Cycle")
            anInOutSB.Append(ControlChars.Tab)
            'Changed PM_REFACTOR 2006-10-12. Now below.
            'anInOutSB.Append("I(w.t.)")
            'anInOutSB.Append("High ratio")
            'anInOutSB.Append("Even higher ratio")

            'Changed PM_QUANTEXPORT_CRASH 2008-02-13
            Dim lastIndex2 As Integer = -1
            If Not aPept.spectra Is Nothing Then
                lastIndex2 = aPept.spectra.Count - 1
            End If

            Dim idx As Integer
            For idx = 0 To lastIndex2
                Dim curSpec As SpecQuantStructure = aPept.spectra(idx)

                Dim dishes As Integer = curSpec.dishInfo.Count

                If idx = 0 Then
                    Dim lastIndex As Integer = dishes - 1
                    Dim j As Integer
                    For j = 0 To lastIndex Step 1
                        anInOutSB.Append("A")
                        anInOutSB.Append(j + 1)
                        anInOutSB.Append(ControlChars.Tab)

                        anInOutSB.Append("A")
                        anInOutSB.Append(j + 1)
                        anInOutSB.Append("/A1")
                        anInOutSB.Append(ControlChars.Tab)

                        anInOutSB.Append("I")
                        anInOutSB.Append(j + 1)
                        anInOutSB.Append(ControlChars.Tab)

                        anInOutSB.Append("I")
                        anInOutSB.Append(j + 1)
                        anInOutSB.Append("/I1")
                        anInOutSB.Append(ControlChars.Tab)

                    Next j
                    anInOutSB.Append(PILInputOutput.LINEEND)
                End If

                Dim curRetentionTime_Secs As Double = curSpec.retT 'Unit: seconds
                Dim retTimeStr As String = sec2minuteString(curRetentionTime_Secs)

                Dim ufq As String = "FALSE" 'What does ufq mean??: Used For Quantitation
                If curSpec.useForQuant_WT Then 'lvSpectra.Items(idx).Checked Then
                    ufq = "TRUE"
                End If

                'toReturn &= _
                '  ufq & vbTab & _
                '  retTimeStr & vbTab & _
                '  curSpec.intensityWT & vbTab & _
                '  curSpec.ratioHigherToBase & vbTab & _
                '  curSpec.ratioEvenHigherToBase & vbTab
                anInOutSB.Append(ufq)
                anInOutSB.Append(ControlChars.Tab)
                anInOutSB.Append(retTimeStr)
                anInOutSB.Append(ControlChars.Tab)
                anInOutSB.Append(curRetentionTime_Secs.ToString("0.0"))
                anInOutSB.Append(ControlChars.Tab)
                anInOutSB.Append(curSpec.cycle)
                anInOutSB.Append(ControlChars.Tab)

                If True Then
                    Dim lastIndex As Integer = dishes - 1
                    Dim j As Integer
                    For j = 0 To lastIndex Step 1
                        Dim someDish As shortFormSILACinfoStructure = _
                          curSpec.dishInfo(j)

                        anInOutSB.Append(someDish.MSpeakArea2.ToString("0.00"))
                        anInOutSB.Append(ControlChars.Tab)

                        anInOutSB.Append(someDish.MSpeakAreaRatioToBase.ToString("0.000"))
                        anInOutSB.Append(ControlChars.Tab)

                        anInOutSB.Append(someDish.intensity4.ToString("0.0"))
                        anInOutSB.Append(ControlChars.Tab)

                        anInOutSB.Append(someDish.intensityRatioToBase3.ToString("0.000"))
                        anInOutSB.Append(ControlChars.Tab)
                    Next j
                End If

                'toReturn &= vbCrLf
                anInOutSB.Append(PILInputOutput.LINEEND)
            Next


            'Changed PM_SPECTRAEXPORT_GENERALISED 2008-05-06
            anInOutSB.Append(PILInputOutput.LINEEND) 'Empty line at the end
            '  of the spectrum list table so the following protein or
            '  peptide line is clear to recognise


            'Changed PM_REFACTOR 2008-05-05. Before transformation to more
            '  memory efficient...
            'Dim toReturn As String = anInOutSB.ToString()
            'Return toReturn
        End Sub 'CalSpectrumTableSaveStr()


        'Changed PM_SPECTRAEXPORT_GENERALISED 2008-05-05. Moved content from 
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Shared Sub addSpectraText( _
          ByRef anInPept As PeptideHitStructure, _
          ByRef anInOutSB As System.Text.StringBuilder _
          )
            CalSpectrumTableSaveStr2(anInPept, anInOutSB)
        End Sub 'addSpectraText


        'Changed PM_REFACTOR 2007-03-22. Now separate function for 
        '  one peptide line.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Shared Sub addPeptideLine( _
          ByRef anInPept As PeptideHitStructure, _
          ByRef aProt As ProteinHitStructure, _
          ByRef anInProtStr As String, _
          ByVal anInternalIndex As Integer, _
          ByVal aDishes As Integer, _
          ByRef anInOutSB As System.Text.StringBuilder, _
          ByRef anInOutScratchSB As System.Text.StringBuilder, _
          ByRef anInQuantitationModesObject As QuantitationModes_moreGeneral, _
          ByVal aIncludeSpectraInformation As Boolean _
          )
            'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-27
            'Old parameters - now all on client side using a peptide filter.
            '  ByVal anIncludeall As Boolean, _
            '  ByVal aIncludeQuantified As Boolean, _
            '  ByVal aIncludeVerified As Boolean, _

            '  Does boxing happen with ByRef for anInPept?

            'Changed PM_DEEPER_BAD_VALUE 2007-03-13. This is more
            'to conveniently support the inherited values bug than
            'change the value par se.
            ''Changed PM_REFACTOR 2006-10-12
            'Const BADVAL As Double = -7.7
            Const BADVAL As Double = -777.777

            'Changed PM_REFACTOR 2007-08-26
            'Dim quantified As Boolean = False
            'If Not anInPept.LCprofilesProperties Is Nothing Then
            '    Dim effectiveIndex As Integer = -1
            '    Dim count As Integer = anInPept.LCprofilesProperties.Count()
            '    If count >= 2 Then
            '        effectiveIndex = 1 'Second dish/heavy isotope.
            '    Else
            '        'Changed PM_EXPORT_BUG_QUANTIFIED_NO_ISOTOPE 2007-01-08
            '        If count = 1 Then
            '            'No isotope.
            '            effectiveIndex = 0
            '        Else
            '            'This should never happen...
            '            Trace.Assert( _
            '              False, "Stop!", _
            '              "PIL ASSERT. " & _
            '              "Internal/development assert for stopping execution......")
            '        End If
            '    End If

            '    Dim dish1props As LCprofilesPropertiesStructure = _
            '      anInPept.LCprofilesProperties(effectiveIndex)
            '    quantified = _
            '      dish1props.averageOfRatios2 > 0.00000001 AndAlso _
            '      anInPept.useForQuantitation
            'Else
            '    Dim peter9 As Integer = 9 'Has not been quantified....
            'End If

            'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-27. Not needed
            '  anymore...
            '
            ' Dim quantified As Boolean = _
            '   PILpeptides.isQuantified(anInPept)
            ' 
            ' Dim include As Boolean = False
            ' 
            ' If True Then 'Scope limiter....
            '     If anIncludeall Then
            '         include = True
            '     Else
            '         If aIncludeQuantified AndAlso quantified Then
            '             include = True
            '         Else
            '             Dim peter22 As Integer = 22 'For breakpoints....
            '         End If
            '         If aIncludeVerified AndAlso anInPept.verified Then
            '             include = True
            '         Else
            '             Dim peter21 As Integer = 21 'For breakpoints....
            '         End If
            '     End If
            ' End If
            Dim include As Boolean = True

            If include Then
                Dim PTMscore As Double 'Highest score in the selected
                '  combinations.
                'Test!!

                Trace.Assert(Not anInOutScratchSB Is Nothing, _
                  "PIL ASSERT. <message>.")

                Dim oldLen As Integer = anInOutScratchSB.Length

                anInOutScratchSB.Length = 0 'Reuse...
                PTMscorer.formatSomeCombinations( _
                  anInPept.AASequence, anInPept.PTMs2, _
                  True, anInQuantitationModesObject, _
                  anInOutScratchSB, _
                  PTMscore)

                'Changed PM_EXPORT_QUANTIFIED 2003-03-13
                anInOutSB.Append(anInProtStr)  'Prefix each peptide line with
                '    the protein information. Redundant, but useful for
                '    post(-processing).

                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.AASequence)
                anInOutSB.Append(vbTab)

                'Changed PM_EXCELEXPORT 2003-03-12
                anInOutSB.Append(anInPept.measuredMCR)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.measuredMass)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.charge)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.MascotScore)
                anInOutSB.Append(vbTab)

                Dim val1 As Double = BADVAL
                anInOutSB.Append(val1) 'Sum of datapoints, counts * secs.
                anInOutSB.Append(vbTab)

                Dim val2 As Double = BADVAL
                anInOutSB.Append(val2) 'XIC
                anInOutSB.Append(vbTab)

                Dim val3 As Double = BADVAL
                anInOutSB.Append(val3)
                anInOutSB.Append(vbTab)

                Dim val4 As Double = BADVAL
                anInOutSB.Append(val4)
                anInOutSB.Append(vbTab)

                'Changed PM_XIC 2003-03-07
                anInOutSB.Append(anInPept.retentionTimeCentroid_secs) 'x centroid
                '  of LC peak. Unit: seconds.
                anInOutSB.Append(vbTab)

                'Changed PM_LCPEAK_WIDTH 2003-03-15
                anInOutSB.Append(anInPept.estimatedLCPeakWidth)
                anInOutSB.Append(vbTab)

                'Changed PM_LC_PEAKDETECTION 2003-03-20
                anInOutSB.Append(anInPept.MSMSretentionTimeMinutes * 60.0)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.LCpeakDetectionTimeCentroidSeconds)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.LCMaxTimeSeconds)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.LCMaxIntensity)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.MascotCalculatedMass)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.calibratedMeasuredMCR)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.calibratedMeasuredMass)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.neutralMScentroidForLCMax)
                anInOutSB.Append(vbTab)

                addBooleanString(Not anInPept.goodMSpeak, anInOutSB) 'Note: inverted.
                anInOutSB.Append(vbTab)

                'Changed PM_STRING_CLEANUP 2004-12-14
                anInOutSB.Append( _
                  PILInputOutput.emptyForNothing(anInPept.badPeakReason))
                anInOutSB.Append(vbTab)

                Dim val5 As Double = BADVAL
                anInOutSB.Append(val5)
                anInOutSB.Append(vbTab)

                Dim val6 As Double = BADVAL
                anInOutSB.Append(val6)
                anInOutSB.Append(vbTab)

                Dim val7 As Double = BADVAL
                anInOutSB.Append(val7)
                anInOutSB.Append(vbTab)

                'Changed PM_EDWIN_ALLPEPTIDES_EXPORT 2003-04-16
                anInOutSB.Append(anInPept.rank)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.firstDeltaScore)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(aProt.resultFilePath2)
                anInOutSB.Append(vbTab)

                'Changed PM_MODS_IN_EXPORT 2003-04-16
                anInOutSB.Append( _
                  MascotResultParser.formatMods( _
                    anInPept, anInQuantitationModesObject))
                anInOutSB.Append(vbTab)

                'Changed PM_MORE_IN_PEPTIDEEXPORT 2003-04-16
                anInOutSB.Append(aProt.hitNumber)
                anInOutSB.Append(vbTab)

                Dim val8 As Double = BADVAL
                anInOutSB.Append(val8)
                anInOutSB.Append(vbTab)

                Dim val9 As Double = BADVAL
                anInOutSB.Append(val9)
                anInOutSB.Append(vbTab)

                'Changed PM_PEPT_RAWFILE_PATH 2003-11-05
                anInOutSB.Append(anInPept.rawFileFullPath)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(vbTab) 'Empty column - was seq2, etc.

                'Changed PM_MAXWT_USEDFORQUANT 2003-10-01
                anInOutSB.Append(anInPept.usedForQuantitation_maxWTintensity)
                anInOutSB.Append(vbTab)

                'Changed PM_NOMODS_MASS 2003-10-08
                anInOutSB.Append(anInPept.calculatedMassNoMods)
                anInOutSB.Append(vbTab)

                'Changed PM_STRING_CLEANUP 2004-12-14
                'Changed PM_EXPORT_SEQ_WITHMODS 2003-10-08
                anInOutSB.Append( _
                  PILInputOutput.emptyForNothing(anInPept.AASequencePlusMods))
                anInOutSB.Append(vbTab)

                'Changed PM_FINNEGAN_PPM_ERROR 2003-10-24
                anInOutSB.Append(anInPept.uncalibratedMSCentroidMass)
                anInOutSB.Append(vbTab)

                addBooleanString(anInPept.verified, anInOutSB)
                anInOutSB.Append(vbTab)

                'Changed PM_FINNEGAN_PPM_ERROR 2003-10-28
                anInOutSB.Append(anInPept.calibratedMSCentroidMass)
                anInOutSB.Append(vbTab)

                Dim val10 As Double = BADVAL
                anInOutSB.Append(val10)
                anInOutSB.Append(vbTab)

                Dim val11 As Double = BADVAL
                anInOutSB.Append(val11)
                anInOutSB.Append(vbTab)

                'Changed PM_MS3INTEGRATION 2004-06-02
                anInOutSB.Append(anInPept.MascotScorePlusMS3Score)
                anInOutSB.Append(vbTab)

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


                'Changed PM_MARKER_APPENDFORMATSTRINGBUILDER 2008-01-25. Opportunity 
                '  to use AppendFormat() instead for increased memory 
                '  efficiency/performance.

                Dim val12 As Double = BADVAL
                anInOutSB.Append(val12.ToString("F6"))
                anInOutSB.Append(vbTab)

                'Changed PM_EXPORT_SPECTRUMNUBMER_AND_RT 2004-08-02
                anInOutSB.Append(anInPept.retentionTimeStartMinutes * 60.0)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(anInPept.spectrumNumber)
                anInOutSB.Append(vbTab)

                addBooleanString(anInPept.checkboxChecked, anInOutSB)
                anInOutSB.Append(vbTab)

                'Changed PM_EXTRA_EXPORT 2004-11-23
                anInOutSB.Append(anInPept.queryNumber)
                anInOutSB.Append(vbTab)

                anInOutSB.Append(PTMscore)
                anInOutSB.Append(vbTab)

                'Changed PM_PRECURSOR_INTENSITY 2005-09-08
                anInOutSB.Append(anInPept.precursorIntensity)
                anInOutSB.Append(vbTab)

                Dim highestScore As Double
                PTMscorer.formatSomeCombinations( _
                  anInPept.AASequence, anInPept.PTMs2, False, _
                  anInQuantitationModesObject, _
                  anInOutSB, highestScore)
                Dim peter1 As Integer = 1
                anInOutSB.Append(vbTab)

                anInOutSB.Append("SPACER")
                anInOutSB.Append(vbTab)

                'Changed PM_SHORT_EXPORT 2005-12-01
                Trace.Assert(anInPept.leftFlankAA <> 0, _
                  "PIL ASSERT. leftFlankAA is 0 for peptide " & _
                  anInPept.AASequence & _
                  ". Excel does not like that.")
                Trace.Assert(anInPept.rightFlankAA <> 0, _
                  "PIL ASSERT. rightFlankAA is 0 for peptide " & _
                  anInPept.AASequence & _
                  ". Excel does not like that.")

                'Changed PM_STANDARDS_COMPLIANCE 2005-10-20
                anInOutSB.Append(ChrW(anInPept.leftFlankAA))
                anInOutSB.Append(vbTab)
                anInOutSB.Append(ChrW(anInPept.rightFlankAA))
                anInOutSB.Append(vbTab)

                'Changed PM_QS11_TROUBLE 2005-10-21
                anInOutSB.Append(anInPept.experimentNumber)
                anInOutSB.Append(vbTab)

                'Changed PM_EXPORT_INTERNAL 2005-10-21
                anInOutSB.Append(anInternalIndex)
                anInOutSB.Append(vbTab)

                'Changed PM_EXPORT_DERIVED_MASS_ERRORS 2005-12-01
                'Derived information for mass errors, for convenience.
                If True Then
                    'Changed PM_REFACTOR 2007-09-02
                    ' Dim charge As Integer = anInPept.charge
                    ' Dim ppmf As Double = 1000000.0
                    '
                    ' Dim uncalibMCR As Double = anInPept.measuredMCR
                    ' Dim calibMCR As Double = anInPept.calibratedMeasuredMCR
                    '
                    ' Dim uncalibMass As Double = _
                    '   (uncalibMCR - PROTON_MASS) * charge
                    ' Dim calibMass As Double = _
                    '   (calibMCR - PROTON_MASS) * charge
                    '
                    ' Dim theoMass As Double = anInPept.MascotCalculatedMass
                    ' Dim theoMCR As Double = theoMass / charge + PROTON_MASS
                    '
                    ' Dim uncalibMCRError As Double = uncalibMCR - theoMCR
                    ' Dim calibMCRError As Double = calibMCR - theoMCR
                    '
                    ' Dim uncalibMCRRelativeError As Double = _
                    '   ppmf * uncalibMCRError / theoMCR
                    ' Dim calibMCRRelativeError As Double = _
                    '   ppmf * calibMCRError / theoMCR
                    '
                    ' Dim uncalibMassError As Double = uncalibMass - theoMass
                    ' Dim calibMassError As Double = calibMass - theoMass
                    '
                    ' Dim uncalibMassRelativeError As Double = _
                    '   ppmf * uncalibMassError / theoMass
                    ' Dim calibMassRelativeError As Double = _
                    '   ppmf * calibMassError / theoMass
                    Dim merr As massErrorStructure = helper.massErrors(anInPept)

                    anInOutSB.Append(merr.uncalibMCRError)
                    anInOutSB.Append(vbTab)
                    anInOutSB.Append(merr.uncalibMCRRelativeError)
                    anInOutSB.Append(vbTab)
                    anInOutSB.Append(Math.Abs(merr.uncalibMCRRelativeError))
                    anInOutSB.Append(vbTab)

                    anInOutSB.Append(merr.calibMCRError)
                    anInOutSB.Append(vbTab)
                    anInOutSB.Append(merr.calibMCRRelativeError)
                    anInOutSB.Append(vbTab)
                    anInOutSB.Append(Math.Abs(merr.calibMCRRelativeError))
                    anInOutSB.Append(vbTab)

                    anInOutSB.Append(merr.uncalibMassError)
                    anInOutSB.Append(vbTab)
                    anInOutSB.Append(merr.uncalibMassRelativeError)
                    anInOutSB.Append(vbTab)
                    anInOutSB.Append(Math.Abs(merr.uncalibMassRelativeError))
                    anInOutSB.Append(vbTab)

                    anInOutSB.Append(merr.calibMassError)
                    anInOutSB.Append(vbTab)
                    anInOutSB.Append(merr.calibMassRelativeError)
                    anInOutSB.Append(vbTab)
                    anInOutSB.Append(Math.Abs(merr.calibMassRelativeError))
                    anInOutSB.Append(vbTab)
                End If

                'Changed PM_PHOSPHO_SCORING_USERSEL 2006-01-04
                If True Then
                    anInOutSB.Append(anInOutScratchSB)

                    anInOutSB.Append(vbTab)

                    anInOutSB.Append("SPACER")
                    anInOutSB.Append(vbTab)
                End If

                'Changed PM_PROTEINRATIO_FOR_EACH_RAWFILE 2006-02-27
                If True Then 'More protein information, quantitation result
                    'for current raw file.

                    Dim fileID As Integer = anInPept.rawFileID
                    Dim lastIndex As Integer = aDishes - 1

                    Dim oneDish As oneDishResultStructure
                    oneDish.n = 0

                    Dim rawfileQres As protSILACresultStructure

                    'Changed PM_INHERITED_QUANTVALUES_IN_EXPORT 2007-03-13. No
                    '  longer needed. Deleted at any time.
                    'rawfileQuantResult.averageRatioToBase = 0.0
                    'rawfileQuantResult.inv_averageRatioToBase = 0.0
                    'rawfileQuantResult.inv_stdDevAverageRatioToBase = 0.0
                    'rawfileQuantResult.stdDevAverageRatioToBase = 0.0

                    'Changed PM_STATISTICS_N 2007-02-23
                    ''Changed PM_STATISTICS_N 2007-01-11
                    'One value - protein value for the raw file that
                    'the current peptide belongs to.
                    Dim Nstat As Integer = -1 'Not yet!!!
                    anInOutSB.Append(Nstat)
                    anInOutSB.Append(vbTab)

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

                        'Changed PM_INHERITED_QUANTVALUES_IN_EXPORT 2007-03-13
                        'Reset at every iteration. Otherwise
                        'non-quantified peptides may inherit values from
                        'quantified peptides (in the output).
                        rawfileQres.averageRatioToBase = BADVAL
                        rawfileQres.inv_averageRatioToBase = BADVAL
                        rawfileQres.inv_stdDevAverageRatioToBase = BADVAL
                        rawfileQres.stdDevAverageRatioToBase = BADVAL

                        If Not aProt.quantResults3 Is Nothing Then

                            Dim qCount As Integer = _
                              aProt.quantResults3.Count
                            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

                            oneDish = _
                              aProt.quantResults3(dish)
                            n = oneDish.n
                            rawfileQres = _
                                MSQuantCommon.getProteinQuantValues( _
                                  dish, _
                                  fileID, _
                                  aProt.quantResults3)
                        Else
                            Dim peter2 As Integer = 2 'Not quantified....
                        End If

                        anInOutSB.Append( _
                          rawfileQres.averageRatioToBase.ToString("0.00"))
                        anInOutSB.Append(vbTab)

                        anInOutSB.Append( _
                          rawfileQres.stdDevAverageRatioToBase.ToString( _
                            "0.00"))
                        anInOutSB.Append(vbTab)
                    Next dish

                    anInOutSB.Append(n) 'Is this the correct number??????? Isn't it
                    '  for all raw files?.
                    anInOutSB.Append(vbTab)
                End If

                'Changed PM_PEPTIDE_POSITION 2006-06-22
                If True Then
                    anInOutSB.Append(anInPept.startPositionInProtein)
                    anInOutSB.Append(vbTab)

                    anInOutSB.Append(anInPept.endPositionInProtein)
                    anInOutSB.Append(vbTab)

                    anInOutSB.Append("SPACER")
                    anInOutSB.Append(vbTab)
                End If

                'Changed PM_REFACTOR 2006-10-16
                If True Then
                    Dim someProp As LCprofilesPropertiesStructure

                    'Changed PM_INHERITED_QUANTVALUES_IN_EXPORT 2007-03-13
                    '  No longer needed. Delete at any time.
                    'someProp.averageOfRatios2 = 0.0
                    'someProp.ratioStDev = 999.99
                    'someProp.totalLCSignal = 0.0
                    'someProp.totalLCPeakArea = 0.0

                    'Changed PM_STATISTICS_N 2007-02-23
                    ''Changed PM_STATISTICS_N 2007-01-11 
                    Dim N As Integer = -1 'Not yet!!!
                    anInOutSB.Append(N) 'Number of spectra used for computing
                    '  the average and standard deviation.
                    anInOutSB.Append(vbTab)

                    Dim lastIndex2 As Integer = aDishes - 1
                    Dim dish As Integer
                    For dish = 0 To lastIndex2

                        'Changed PM_INHERITED_QUANTVALUES_IN_EXPORT 2007-03-13
                        'Reset at every iteration. Otherwise
                        'non-quantified peptides may inherit values from
                        'quantified peptides (in this output).
                        '
                        'Defaults if peptide has not been quantified.
                        'Changed PM_DEEPER_BAD_VALUE 2007-03-13
                        'someProp.averageOfRatios2 = 0.0
                        'someProp.ratioStDev = 999.99
                        'someProp.totalLCSignal = 0.0
                        'someProp.totalLCPeakArea = 0.0
                        someProp.averageOfRatios2 = BADVAL
                        someProp.ratioStDev = BADVAL
                        someProp.totalLCSignal = BADVAL
                        someProp.totalLCPeakArea = BADVAL

                        'Changed PM_INHERITED_QUANTVALUES_IN_EXPORT 2007-03-13
                        'Primary bug: this was missing!:
                        someProp.ratioOfXICs = BADVAL

                        If Not anInPept.LCprofilesProperties Is Nothing Then
                            someProp = _
                              anInPept.LCprofilesProperties(dish)
                        Else
                            Dim peter8 As Integer = 8 'Not quantified.
                        End If

                        'Changed PM_EXPORT_DECIMALS 2007-03-12
                        ''Changed PM_LIMIT_EXPORT 2006-11-08
                        ''anInOutSB.Append(someProp.averageOfRatios2)
                        'anInOutSB.Append(someProp.averageOfRatios2.ToString("0.00"))
                        anInOutSB.Append( _
                          someProp.averageOfRatios2.ToString("0.000"))
                        anInOutSB.Append(vbTab)

                        'Changed PM_LIMIT_EXPORT 2006-11-08
                        'anInOutSB.Append(someProp.ratioStDev)
                        anInOutSB.Append(someProp.ratioStDev.ToString("0.00"))
                        anInOutSB.Append(vbTab)

                        'Changed PM_EXPORT_DECIMALS 2007-03-12
                        ''Changed PM_NO_RATIO_OF_INTENSITY_SUMS 2006-11-08
                        ''We don't export the computed value anymore.
                        ''anInOutSB.Append(someProp.ratioOfItensities)
                        ''Changed PM_LIMIT_EXPORT 2006-11-08
                        ''anInOutSB.Append(someProp.ratioOfXICs)
                        'anInOutSB.Append(someProp.ratioOfXICs.ToString("0.00"))
                        anInOutSB.Append(someProp.ratioOfXICs.ToString("0.000"))
                        anInOutSB.Append(vbTab)

                        anInOutSB.Append(someProp.totalLCPeakArea) 'Alias XIC.
                        anInOutSB.Append(vbTab)

                        anInOutSB.Append(someProp.totalLCSignal)
                        anInOutSB.Append(vbTab)
                    Next dish
                End If

                'Changed PM_EXPORT_USED_IN_PROTEINQUANT 2007-07-30
                addBooleanString(anInPept.useForQuantitation, anInOutSB)
                anInOutSB.Append(vbTab)

                'Changed PM_EXPORT_PTMCOMBS 2007-08-03
                Dim combs As Integer = 0
                If Not anInPept.PTMs2 Is Nothing Then
                    combs = anInPept.PTMs2.Count()
                End If
                anInOutSB.Append(combs)
                anInOutSB.Append(vbTab)

                'Changed PM_EXPORT_RAWFILEID 2007-11-19
                anInOutSB.Append(anInPept.rawFileID)
                anInOutSB.Append(vbTab)


                'Changed PM_SEQUENCE_COVERAGE 2008-04-16
                anInOutSB.Append(aProt.sequenceCoverage.ToString("0.00"))
                anInOutSB.Append(vbTab)

                anInOutSB.Append(vbTab)
                anInOutSB.Append(vbTab)
                anInOutSB.Append(ControlChars.NewLine)

                'Changed PM_SPECTRAEXPORT_GENERALISED 2008-05-05
                If aIncludeSpectraInformation Then
                    If Not anInPept.spectra Is Nothing Then
                        quantApplication.addSpectraText(anInPept, anInOutSB)
                    Else
                        'Don't output anything if peptide has not been quantified.
                    End If
                End If
            End If 'Include peptide.
        End Sub 'addPeptideLine


        'Changed PM_REFACTOR 2003-04-16
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        '  This function is coupled to function peptideTableHeaders().
        '  Parameter aProt: const ref.
        '
        Public Shared Sub NakedPeptideTable3( _
          ByRef anInProt As ProteinHitStructure, _
          ByRef anApp As quantApplication, _
          ByVal aQuantModeCode As Integer, _
          ByVal anInPeptideFilter2 As peptideFilterStructure, _
          ByVal aIncludeSpectraInformation As Boolean, _
          ByRef anInOutSB As System.Text.StringBuilder, _
          ByRef anInPeptideTokens As List(Of Integer) _
          )
            'Changed PM_REFACTOR 2007-03-22
            'Old return type: String

            'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-27
            'Old parameters:
            '  ByVal aIncludeQuantified As Boolean, _
            '  ByVal aIncludeVerified As Boolean, _

            'Changed PM_REFACTOR 2008-05-05. Changed to more memory efficient version...
            'Dim strSB As System.Text.StringBuilder = _
            '  New System.Text.StringBuilder(24000)

            Dim scratchSB As StringBuilder = New StringBuilder(500)

            Dim MascotResultFilePath As String = anInProt.resultFilePath2
            Dim proteinHitNumber As Integer = anInProt.hitNumber

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

            Dim settings As miscSettingsStructure2Struct = _
              anApp.getMiscSettings()

            'Dim shhv As Boolean = settings.option1 = 1
            Dim shhv As Boolean = True

            'Changed PM_REFACTOR 2006-10-16
            Dim dishes As Integer = anApp.getDishes(aQuantModeCode)

            'Derived from protein.
            Dim protStr As String = _
              proteinInformation_PrefixForPeptideLine(anInProt, dishes)

            'Changed PM_EXPORT_IMPORTEDACC 2007-03-22
            ''Changed PM_ACCESSIONNUMBER_IMPORT 2003-03-26
            'Dim accToUse As String = aProt.accNum

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

            Dim pept3 As PeptideHitStructure = _
              helper.blankPeptide() 'Keep compiler happy.
            Dim internalIndex As Integer = 0

            If anInPeptideTokens Is Nothing Then
                'This means all peptides should b
                'considered (subject to any peptide filter).

                'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-26
                ''Changed PM_REFACTOR 2006-03-15
                'Dim pepIter As peptideListIterator = _
                '  New peptideListIterator(aProt.peptides)
                Dim pepIter As peptideListIterator = _
                  New peptideListIterator( _
                    anInProt.peptides, anInPeptideFilter2)

                While Not pepIter.nextPeptide(pept3)

                    quantApplication.addPeptideLine( _
                      pept3, _
                      anInProt, _
                      protStr, _
                      internalIndex, _
                      dishes, _
                      anInOutSB, _
                      scratchSB, _
                      quantitationModesObject, _
                      aIncludeSpectraInformation)
                    internalIndex += 1
                End While 'Through peptides.
            Else
                'Subset of peptides specified from the outside, e.g. by
                'the user.

                Dim someToken As Integer
                For Each someToken In anInPeptideTokens

                    'Note: it is assumed that the client has applied the
                    '      peptide filter - the list of tokens only includes
                    '      those within the filter.
                    anInProt.peptides.peptideByToken(someToken, pept3)

                    quantApplication.addPeptideLine( _
                      pept3, _
                      anInProt, _
                      protStr, _
                      internalIndex, _
                      dishes, _
                      anInOutSB, _
                      scratchSB, _
                      quantitationModesObject, _
                      aIncludeSpectraInformation)

                    internalIndex += 1
                Next 'Through anInPeptideTokens
            End If

            'Changed PM_REFACTOR 2008-05-05. Changed to more memory efficient version...
            ''Changed PM_REFACTOR 2007-03-22
            ''Return strSB.ToString
            'Return strSB
        End Sub 'NakedPeptideTable()


        'Changed PM_REFACTOR 2008-05-05. Changed to more memory efficient version...
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        '  Parameter aProt: const ref.
        Public Shared Sub peptideTableWithHeader3( _
          ByRef anInCalibration As SDUPrecalibrator, _
          ByRef aProt As ProteinHitStructure, _
          ByVal aQuantModeCode As Integer, _
          ByRef anApp As quantApplication, _
          ByVal aPeptideFilter2 As peptideFilterStructure, _
          ByVal aIncludeSpectraInformation As Boolean, _
          ByRef anInOutSB As System.Text.StringBuilder, _
          ByRef anInPeptideTokens As List(Of Integer) _
          )

            'Changed PM_PEPTIDEFILTER_GENERALISED 2007-08-27. New: aPeptideFilter.

            'Old parameters:
            '  ByRef aRawFilesMap() As massSpectrometryBase.fileSpecStruct, _
            '
            '  ByVal aIncludeQuantified As Boolean, _
            '  ByVal aIncludeVerified As Boolean, _
            '
            '  'Changed PM_REFACTOR 2007-10-30
            '    ByVal aSlope As Double, ByVal anOffset As Double

            'Changed PM_PROTEINEXPORT_EXCEPTION 2006-11-08
            Dim dishes As Integer = anApp.getDishes(aQuantModeCode)

            Dim header As String = _
              quantApplication.FormatAppHeader( _
                anInCalibration, aQuantModeCode, anApp, _
                dishes)

            'Changed PM_REFACTOR 2005-03-07. No longer needed. Delete at any time.
            ''Changed PM_QUANTMODESTR_DISPLAY 2003-09-29
            'Dim prefix As String = ""
            'If aQuantModeStr <> "" Then
            '    prefix = aQuantModeStr & vbCrLf & vbCrLf
            'End If

            'Changed PM_REFACTOR 2008-05-05. Changed to more memory efficient version...
            'Dim sb As System.Text.StringBuilder = _
            '  New System.Text.StringBuilder(32768)

            'Dim str As String = header & proteinString(aProt) & vbCrLf
            'str &= peptideTableHeaders(str)
            'str &= NakedPeptideTable(aProt, aOnlyIncludeQuantified, anApp)
            anInOutSB.Append(header)

            'Changed PM_PROTEINEXPORT_EXCEPTION 2006-11-08. Extra parameter.
            quantApplication.addProteinLine(aProt, anInOutSB, dishes)

            anInOutSB.Append(vbCrLf)

            Dim settings As miscSettingsStructure2Struct = _
              anApp.getMiscSettings()

            'Changed PM_REFACTOR 2008-05-05. Changed to more memory efficient version...
            peptideTableHeaderWithAheader( _
              "", settings.option1, _
              anApp, aQuantModeCode, anInOutSB)

            NakedPeptideTable3( _
              aProt, _
              anApp, _
              aQuantModeCode, _
              aPeptideFilter2, _
              aIncludeSpectraInformation, _
              anInOutSB, _
              anInPeptideTokens)
            'Test that this works.

            'Changed PM_REFACTOR 2008-05-05. Changed to more memory
            '  efficient version...
            'Return sb.ToString()
        End Sub 'PeptideTableWithHeader()


        'Changed PM_GENERALISED_IONSERIES 2008-05-12
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function getIonSeriesDefinitions() _
          As PILgeneralisedIonSeries

            If mIonSeriesDefinitions Is Nothing Then 'Lazy instantiation.
                mIonSeriesDefinitions = _
                  New PILgeneralisedIonSeries(mQuantitationModes_new)
            End If
            Return mIonSeriesDefinitions
        End Function 'getIonSeriesDefinitions()


        'Changed PM_ION_SERIES_DISPLAYOPTION 2008-05-26
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Sub setShowOnlyMatchedIons(ByVal aNewSettting As Boolean)
            mShowOnlyMatchedIons = aNewSettting
        End Sub 'setShowOnlyMatchedIons


        'Changed PM_ION_SERIES_DISPLAYOPTION 2008-05-26
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Function getShowOnlyMatchedIons() _
          As Boolean

            Return mShowOnlyMatchedIons
        End Function 'getShowOnlyMatchedIons


        'Changed PM_VERSION_INFO 2007-04-19
        'Note: keep versionString_dateOnly(), versionString()
        '      and versionString_withDate() at the bottom of
        '      this file; for easier navigation...
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Function versionString_dateOnly() _
          As String

            Dim toReturn As String = "2008-05-27"
            Return toReturn
        End Function 'versionString_dateOnly


        'Changed PM_VERSION_INFO 2007-04-19
        'Note: keep versionString_dateOnly(), versionString()
        '      and versionString_withDate() at the bottom of
        '      this file; for easier navigation...
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '*                                                                          *
        '*    Centralised place for version information. There may be a             *
        '*    standard .NET function for this, but even then we will                *
        '*    use this function to hide.                                            *
        '*                                                                          *
        '****************************************************************************
        Public Shared Function versionString() _
          As String

            Dim toReturn As String = "1.4.3b3"

            Return toReturn
        End Function 'versionString


    End Class 'quantApplication


End Namespace 'MSQuant


    

    

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