Source code for MSQuant: FindLCpeaks.vb, MSQuant/msquant/src/main/massbase/FindLCpeaks.vb.

Table of contents page.

Home page for MSQuant.


'To move to below:

'Notes: 1. platform/GUI independent.
'       2. rename to something with Quantifier?

'It uses another class to actually find peaks - the other class is also
'used for finding other kinds of peak, e.g. MS peak.
'
'This class specialises in finding the correct LC peaks, using various rules.
'Rules include:
'   1. the MS peptide precursor mass accurarcy found from the MS spectrum 
'      for the best (or several) spectra for an LC peak is used to select 
'      which LC peak in a time range to use.
'   2. the ratio between the absolute hight and the back 
'      ground for an LC peak must be over a certain 
'      threshold. This will exclude weak peaks that are close 
'      to background (or are just random local minina on the 
'      slopes of a larger peak), but close to a measured or 
'      predicted retention time. Score for selection will be 
'      low, but proportional to XYZ
'   3. 

' Also holds/cache information from the process to find the LC profile
'to avoid repeating the quantitation


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

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

Option Strict On
Option Explicit On 

Imports System.IO

'Changed PM_SUPERCHARGE 2003-11-03
'Imports Mascot_Parser.SDUPutility
Imports SDUPutility

Imports massSpectrometryBase

Imports massSpectrometryBase.quantitation

Imports MolecularSharedStructures



'****************************************************************************
'd$ <summary>
'd$   Purpose: Namespace for lower layers of mass spectrometric
'd$            applications: raw data file handling, descriptive statistics,
'd$            fragment masses, digestion, file associations, etc.
'd$   <see cref="T:VBXMLDoc.CVBXMLDoc" />.
'd$   <isUnitTest></isUnitTest>
'd$   <applicationname>test_rawDataFileHandling</applicationname>
'd$   <author>Peter Mortensen</author>
'd$   <seealso>http://www.cebi.sdu.dk/</seealso>
'd$   <codetype>PLATFORM independent</codetype>
'd$ </summary>
Namespace massSpectrometryBase

    Public Class FindLCpeaks

        Private mChunkerLCPeakFind As SDUPchunker

        Private mPept As PeptideHitStructure
        Private mRawDataFileHandling As rawDataFileHandling 'Requires
        '  importing namespace massSpectrometryBase.

        Private mStartCycle As Integer

        Private mNextMScycle As Integer
        Private mClassificationForNextMScycle As _
          SpectrumClassificationStructure

        'Changed PM_REFACTOR 2006-03-15
        ''Input from client, saved for use in chunk
        Private mProt As ProteinHitStructure
        'Dim mCurrPepIdx As Integer
        'Dim mCurrPeptide As peptideListIterator
        Private mCurrPeptideToken As Integer

        'Changed PM_REFACTOR 2007-10-30
        'Private mA As Double
        'Private mB As Double
        Private mRecalibrator As SDUPrecalibrator

        Private mDeltaMass As Double
        Private mFixBackground As Double

        'Changed PM_GENERALISED_QUANT_MODE 2003-12-08
        'Dim mQuantMode As quantModeEnum
        'Dim mQuantModeCode As Integer
        Private mQuantModeClassification As QuantModeClassificationStruct

        'Outputs
        'Dim mOutLCMaxIndex As Integer   not used....
        Private mLCwindowStartCycle As Integer
        Private mLCwindowEndCycle As Integer

        'Changed PM_TYPESAFE 2006-11-01
        'Private mLCPeakCandidates As ArrayList 'Type is LCPeakInfoStructure
        Private mLCPeakCandidates As Generic.List(Of LCPeakInfoStructure)

        Private mDumpFileCounter As Integer = 0 'Test only
        Private mStr As String 'Test only

        'Changed PM_LCPROFILE_DUMP 2003-11-16
        'Currently it is the lower profile....
        Private mLCProfileProperties As dataPointsInfoStructure2

        'Changed PM_MSTYPES_FOR_QUANT_OPTION 2004-09-13
        Private mMSTypes As QuantMSTypesEnum

        'Changed PM_LCPROFILE_ALSO_WHEN_NO_RATIO 2004-07-17
        Public Const IDENTICAL_ZERO_INTENSITY_THRESHOLD As Double = 0.001

        'Changed PM_REFACTOR 2004-06-22. Now folded into
        ''Changed PM_LCPROFILE_DUMP 2003-11-16
        'Private Structure LCProfileDescriptorStructure
        '    Dim maxSigal As signalStructure

        'End Structure 'LCProfileDescriptor

        'Changed PM_LCPEAKDETECTION_OPTIONS 2006-06-20
        Private mLCpeakParameters As correlationSettingsStructure

        'Changed PM_DISPLAY_FULL_RETT_RANGE 2006-11-06
        'These XX are used for adding the last point in the LC profile
        'anyway, even if it would have been filtered out.
        '
        'Must be here as members - the last MS spectrum may
        '  have been encountered in the previous call to this function.
        Private mLastQuantResult As Generic.List(Of quantResultStructure)
        Private mLastCycle As Integer = -1
        Private mLastSomeTime As Double = -7777.7777
        Private mLastMSsubType As spectrumSubTypeEnum


        'Is this the right place???
        'Changed PM_TRIPLE_LYSINE 2003-11-26
        Public Structure multModCounterStructure
            Dim totalPeptides As Integer
            Dim peptidesWithModificationForQuantMode As Integer
            Dim nonMatchingAAsToModificationCountFromMascot As Integer

            'Changed PM_QUANTGENERAL_PREPARATION 2006-07-17
            Dim sampleQueryNumberForNonMatchingAAs As Integer
        End Structure 'multModCounterStructure


        '****************************************************************************
        '*  SUBROUTINE NAME:   New                                                  *
        'd$ <summary>Constructor</summary>
        Public Sub New()
            MyBase.New() 'Is this necessary? Yes!

            'InitializeComponent()    Is this necessary??

            'Changed PM_DISPLAY_FULL_RETT_RANGE 2006-11-06
            mLastQuantResult = Nothing
            mLastCycle = -1
            mLastSomeTime = -7777.7777
            mLastMSsubType = spectrumSubTypeEnum.enumST_DoesNotApply
        End Sub 'New()


        '****************************************************************************
        '*  SUBROUTINE NAME:   initLCPeakFind                                       *
        'd$ <summary>
        'd$   Purpose: Entry point for clients to drive LC profiling to an
        'd$            end (for a single peptide). It exists because finding 
        'd$            a single LC profile can take a long time (on the
        'd$            order of 10 seconds).
        'd$            To complete LC profiling must be called until this function
        'd$            returns false. Between each call clients may display
        'd$            progress information, etc.
        'd$ 
        'd$   <see cref="T:VBXMLDoc.CVBXMLDoc" />.
        'd$ </summary>
        Public Sub initLCPeakFind( _
          ByVal aStartCycle As Integer, ByVal anEndCycle As Integer, _
          ByRef anOutPept As PeptideHitStructure, _
          ByRef aRawDataFileHandling As rawDataFileHandling, _
          ByRef aInProt As ProteinHitStructure, _
          ByVal aPeptideToken As Integer, _
          ByRef anInCalibration As SDUPrecalibrator, _
          ByVal aDeltaMass As Double, _
          ByVal aFixBackground As Double, _
          ByVal aQuantModeClassification As QuantModeClassificationStruct, _
          ByVal anInMSTypes As QuantMSTypesEnum, _
          ByVal anInLCpeakParameters As correlationSettingsStructure, _
          ByVal anInDishes As Integer _
          )

            'Changed PM_REFACTOR 2006-03-15
            'ByRef aInProt As ProteinHitStructure,
            'ByVal aPepIndex As Integer, _
            '
            '  'Changed PM_REFACTOR 2007-10-30
            '    ByVal anA As Double, ByVal aB As Double

            'Here: perhaps some reset of our internal cached information from .
            '      last use. In fact that is the 3 profiles stored 
            '      in mPept. They are probably already reset(?) - below!.

            mPept = anOutPept 'Note: a copy...
            mRawDataFileHandling = aRawDataFileHandling

            'Changed PM_REFACTOR 2006-03-15
            mProt = aInProt

            'mCurrPepIdx = aPepIndex
            'Trace.Assert(Not aCurPept Is Nothing, _
            '  "PIL ASSERT. Current peptide is Nothing....")
            'mCurrPeptide = aCurPept
            mCurrPeptideToken = aPeptideToken

            'Changed PM_REFACTOR 2007-10-30
            'mA = anA
            'mB = aB
            mRecalibrator = anInCalibration


            mDeltaMass = aDeltaMass
            mFixBackground = aFixBackground

            'Changed PM_GENERALISED_QUANT_MODE 2003-12-08
            'mQuantMode = aQuantMode
            mQuantModeClassification = aQuantModeClassification

            mMSTypes = anInMSTypes

            'Changed PM_LCPEAKDETECTION_OPTIONS 2006-06-20
            mLCpeakParameters = anInLCpeakParameters

            If True Then
                'Changed PM_QUANT_ASSERT_FOR_MS3DATA 2005-09-21
                'Dim theCycle As Integer = _
                '   mRawDataFileHandling.spectrumNumberForMSspectrum( _
                '     aStartCycle, mClassificationForNextMScycle)
                Dim cycle As Integer = _
                   mRawDataFileHandling.spectrumNumberForMSspectrum_ForceTrueMSspectrum( _
                     aStartCycle, mClassificationForNextMScycle, False)

                mStartCycle = cycle
                mNextMScycle = cycle

                Dim timeSliceSecs As Double = 2.0
                timeSliceSecs = 0.8
                mChunkerLCPeakFind = New SDUPchunker(timeSliceSecs)
                mChunkerLCPeakFind.Init(cycle, anEndCycle, True)
            End If

            'LC peak detection
            'We may unneccesary repeat computations that only need to be done once.
            'Changed PM_REFACTOR 2006-10-12
            ' If mPept.lowerLCpeakProfile Is Nothing Then
            '     mPept.lowerLCpeakProfile = New ArrayList
            ' End If
            ' If mPept.higherLCpeakProfile Is Nothing Then
            '     mPept.higherLCpeakProfile = New ArrayList
            ' End If
            ' If mPept.evenHigherLCpeakProfile Is Nothing Then
            '     mPept.evenHigherLCpeakProfile = New ArrayList
            ' End If
            If mPept.LCpeakProfiles Is Nothing Then
                mPept.LCpeakProfiles = New Generic.List(Of _
                            Generic.List(Of massSpectrometryBase.signalStructure))
            End If
            If mPept.LCpeakProfiles.Count = 0 Then
                Dim n As Integer
                For n = 1 To anInDishes
                    mPept.LCpeakProfiles.Add( _
                      New Generic.List( _
                        Of massSpectrometryBase.signalStructure))
                Next n
            End If

            'Changed PM_REFACTOR 2006-10-12
            ''Changed PM_REFACTOR 2003-04-11
            ''Needed because we may need to force an update when
            ''the user selects a new range for the LC peak, even
            ''if we have alread done the quantitation.
            'mPept.lowerLCpeakProfile.Clear()
            'mPept.higherLCpeakProfile.Clear()
            'mPept.evenHigherLCpeakProfile.Clear()
            Dim lastIndex As Integer = anInDishes - 1
            Dim j As Integer
            For j = 0 To lastIndex
                mPept.LCpeakProfiles(j).Clear()
            Next j
        End Sub 'initLCPeakFind


        'Changed PM_REFACTOR 2006-11-05
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Sub addToLCprofiles( _
          ByVal aRetentionTimeSecs As Double, _
          ByVal aCycle As Integer, _
          ByVal aMSsubType As spectrumSubTypeEnum, _
          ByRef aQuantResult As Generic.List(Of quantResultStructure), _
          ByVal aQuantOffset As Double)

            'Changed PM_REFACTOR 2006-11-05
            '  Avoid adding invalid points with a signal of
            '  zero. This can happen when there are no
            '  datapoints in the mass ranges that are
            '  used (number of mass ranges depends on
            '  the quantitation mode).
            '  DISABLED with True.....

            'Changed PM_CODEMARKER 2006-11-30
            'asdadasdadasd() 'Add ASSERT. And check at Insert time (even
            'open time) that the number of dishes correspond - at least even
            'quantitation has taken place. 

            Dim dishesInPeptide As Integer = mPept.LCpeakProfiles.Count()
            Dim dishesForCurrentQuantResult As Integer = aQuantResult.Count()


            'Changed PM_MB3_DISHCOUNT_PROBLEM 2007-10-12
            Trace.Assert(dishesInPeptide = dishesForCurrentQuantResult, _
              "PIL ASSERT. Dishes in peptide, " & _
              dishesInPeptide & _
              ", is not the same as the number of dishes for the quantitation result. " & _
              dishesForCurrentQuantResult & _
              ". Probable reason: the number of dishes for the current quantitation " & _
              "mode is not the same as it was when the parse was saved to a MB3 file.")

            Dim dish As Integer = 0
            Dim someQuantResult As quantResultStructure
            For Each someQuantResult In aQuantResult 'E.g. 3 times
                '  for triple encoding.

                'Changed PM_REFACTOR_BUG 2006-11-05
                'If someItem.intensity < _
                '  IDENTICAL_ZERO_INTENSITY_THRESHOLD Then

                '    someItem.intensity = _
                '      IDENTICAL_ZERO_INTENSITY_THRESHOLD
                'End If
                If someQuantResult.intensity5 < _
                  IDENTICAL_ZERO_INTENSITY_THRESHOLD Then

                    someQuantResult.intensity5 = _
                      IDENTICAL_ZERO_INTENSITY_THRESHOLD
                End If

                If someQuantResult.MSpeakArea3 < _
                  IDENTICAL_ZERO_INTENSITY_THRESHOLD Then

                    someQuantResult.MSpeakArea3 = _
                      IDENTICAL_ZERO_INTENSITY_THRESHOLD
                End If

                Dim LCpoint As signalStructure
                LCpoint.Xsig = aRetentionTimeSecs
                LCpoint.Ysig = someQuantResult.MSpeakArea3
                LCpoint.tagValue = someQuantResult.calibratedNeutralMass
                LCpoint.tagValue2 = aCycle

                'Changed PM_QUANT_AUTO_CENTERING 2006-11-13
                Trace.Assert( _
                  someQuantResult.offsetMCR8 = aQuantOffset, _
                  "PIL ASSERT. Quantitation offsets are inconsistent: " & _
                  someQuantResult.offsetMCR8 & " Th versus " & _
                  aQuantOffset & " Th.") 'Somewhat risky to equality
                '  for these double (?).
                '
                LCpoint.tagValue3 = aQuantOffset 'Same offset for all dishes...
                'Do we really need aQuantOffset?

                LCpoint.quantResult = someQuantResult
                LCpoint.MStype = aMSsubType

                mPept.LCpeakProfiles(dish).Add(LCpoint)

                dish += 1
            Next 'Through quantResult

        End Sub 'addToLCprofiles


        '****************************************************************************
        '*  SUBROUTINE NAME:   doChunkLCPeakFind                                    *
        'd$ <summary>
        'd$   Purpose: Entry point for clients to drive LC profiling to an
        'd$            end. It exists because finding a single LC profile can take a
        'd$            long time (on the order of 10 seconds).
        'd$            To complete LC profiling must be called until this function
        'd$            returns false. Between each call clients may display
        'd$            progress information, etc.
        'd$ 
        'd$   <see cref="T:VBXMLDoc.CVBXMLDoc" />.
        'd$ </summary>
        Public Function doChunkLCPeakFind() As Boolean

            'Changed PM_RET_RANGE_ASSERT 2006-11-05
            Dim keepFirstAndLastPoint As Boolean = True 'True for new behavior.

            'Changed PM_REFACTOR 2006-10-03
            Dim uncalibratedSILACmasses As Generic.List(Of Double) = _
              mPept.uncalibratedSILACmasses2

            'Note: also exits if at the end of the count range.
            While Not mChunkerLCPeakFind.timeIsUp()

                Dim cycle As Integer = mChunkerLCPeakFind.currentNumber()

                'Note: for Finnegan spectra this condition is
                '      often false (that's why it is there!).
                If cycle = mNextMScycle Then

                    'Save a copy...
                    Dim spectrumClassification As SpectrumClassificationStructure = _
                      mClassificationForNextMScycle

                    'mNextMScycle is used in later iterations of the loop, not
                    'in this if part.

                    'What if it is close to the end of the file?. 
                    'Answer: it actually checks for the end of file,
                    'increasing the return value. The while loop
                    'we are in here will terminate before we get to
                    'here after this happens.
                    mNextMScycle = mRawDataFileHandling.nextMSspectrum( _
                      cycle, mClassificationForNextMScycle)

                    'Changed PM_REFACTOR 2003-10-14. We should not need
                    'to display spectra when finding the LC profile, at least not 
                    'every one. But we may want to display some progress information
                    'such that the application does not appear dead.
                    ''Changed PM_REFACTOR 2003-04-01. Note: there will be
                    ''an extra ZoomToArgDoublet()..
                    'Dim someTime As Single = SetAndDisplaySpectrum(theCycle)
                    Dim dummy4 As SpectrumClassificationStructure
                    dummy4.dataSourceName = Nothing 'Keep compiler happy.

                    Dim someTime As Double = _
                      mRawDataFileHandling.newSpectrumBySpectrumNumber( _
                        cycle, dummy4)

                    'Changed PM_REFACTOR 2006-10-05
                    ''Calculate the intensities and masses of all peaks.
                    'Dim lowerQuantResult As quantResultStructure
                    'Dim higherQuantResult As quantResultStructure
                    'Dim evenHigherQuantResult As quantResultStructure
                    Dim quantResult As Generic.List(Of quantResultStructure) = _
                      Nothing

                    Dim validResult As Boolean
                    Dim quantMCRoffset As Double
                    '  mProt, mCurrPeptideToken, _
                    CalcParametersForCurrentMS( _
                      mPept.rawFileID, _
                      mRecalibrator, _
                      mDeltaMass, _
                      mRawDataFileHandling, _
                      mFixBackground, _
                      mQuantModeClassification, _
                      quantResult, _
                      validResult, _
                      mPept.charge, _
                      uncalibratedSILACmasses, _
                      quantMCRoffset)
                    'mProt, mCurrPepIdx, _

                    'Changed PM_REFACTOR 2006-10-01
                    'Now (partly) on the client side. Not very clean, but
                    'hopefully it will be cleaned up later when we 
                    'are done with the refactoring.
                    'Changed PM_NEGATIVE_RETENTION_TIMES 2003-10-16
                    If mPept.MSMSretentionTimeMinutes * 60 < 10.0 Then
                        'If a predicted retention time was 
                        'negative then it was flagged during 
                        'correlation through this field with 
                        'a small positive value - 10.0 s in 
                        'the test above.

                        validResult = False 'Flag to caller that the quantitation 
                        'result should be regarded as zero.
                    End If

                    'Changed PM_REFACTOR 2006-10-05. Old. Delete at any time.
                    ' 'Changed PM_MEMORYPROBLEM 2006-08-30
                    ' 'Compute it here to avoid changing signature or semantics
                    ' 'of CalcParametersForCurrentMS2(). And because we effectively
                    ' 'only call the function from here.
                    ' '
                    ' 'What about even higher isotope for double encoding??
                    ' Dim anyNonZero As Boolean = _
                    '   lowerQuantResult.validResult Or _
                    '   higherQuantResult.validResult Or _
                    '   evenHigherQuantResult.validResult
                    ' If anyNonZero Then
                    '     Dim peter2 As Integer = 2
                    ' Else
                    '     Dim peter3 As Integer = 3
                    ' End If
                    ' If validResult = anyNonZero Then
                    '     Dim peter4 As Integer = 4
                    ' Else
                    '     Dim peter5 As Integer = 5
                    ' End If
                    ' 
                    ' 'Changed PM_MEMORYPROBLEM 2006-08-30
                    ' 'If True Or vResult Then
                    ' 'If vResult Then
                    ' If anyNonZero Then
                    ' 
                    '     '  Avoid adding invalid points with a signal of
                    '     '  zero. This can happen when there are no
                    '     '  datapoints in the mass ranges that are
                    '     '  used (number of mass ranges depends on
                    '     '  the quantitation mode).
                    '     '  DISABLED with True.....
                    '     Dim LCpoint As signalStructure
                    ' 
                    '     'Changed PM_LCPROFILE_ALSO_WHEN_NO_RATIO 2004-07-17
                    '     If False Then
                    '         If Not validResult Then
                    '             'Avoid problems with signal of 0. Is this 
                    '             'the right way to do it?
                    '             lowerQuantResult.intensity = _
                    '               IDENTICAL_ZERO_INTENSITY_THRESHOLD
                    '             higherQuantResult.intensity = _
                    '               IDENTICAL_ZERO_INTENSITY_THRESHOLD
                    '             evenHigherQuantResult.intensity = _
                    '               IDENTICAL_ZERO_INTENSITY_THRESHOLD
                    '         End If
                    '     Else
                    '         If lowerQuantResult.intensity < _
                    '           IDENTICAL_ZERO_INTENSITY_THRESHOLD Then
                    ' 
                    '             lowerQuantResult.intensity = _
                    '               IDENTICAL_ZERO_INTENSITY_THRESHOLD
                    '         End If
                    '         If higherQuantResult.intensity < _
                    '           IDENTICAL_ZERO_INTENSITY_THRESHOLD Then
                    ' 
                    '             higherQuantResult.intensity = _
                    '               IDENTICAL_ZERO_INTENSITY_THRESHOLD
                    '         End If
                    '         If evenHigherQuantResult.intensity < _
                    '           IDENTICAL_ZERO_INTENSITY_THRESHOLD Then
                    ' 
                    '             evenHigherQuantResult.intensity = _
                    '               IDENTICAL_ZERO_INTENSITY_THRESHOLD
                    '         End If
                    '     End If
                    ' 
                    '     LCpoint.Xsig = someTime
                    ' 
                    '     'Changed PM_LCPEAK_LARGEVALUES 2006-08-08
                    '     'Changed PM_LCPEAK_YVALUE_MSPEAKAREA 2006-08-08
                    '     'LCpoint.Ysig = lowerQuantResult.intensity
                    '     LCpoint.Ysig = lowerQuantResult.peakArea
                    ' 
                    '     LCpoint.tagValue = lowerQuantResult.calibratedNeutralMass
                    '     LCpoint.tagValue2 = cycle
                    '     LCpoint.quantResult = lowerQuantResult
                    '     LCpoint.MStype = spectrumClassification.MSsubType
                    '     mPept.lowerLCpeakProfile.Add(LCpoint)
                    ' 
                    ' 
                    '     LCpoint.Xsig = someTime
                    ' 
                    '     'Changed PM_LCPEAK_YVALUE_MSPEAKAREA 2006-08-08
                    '     'LCpoint.Ysig = higherQuantResult.intensity
                    '     LCpoint.Ysig = higherQuantResult.peakArea
                    ' 
                    '     LCpoint.tagValue = higherQuantResult.calibratedNeutralMass
                    '     LCpoint.tagValue2 = cycle
                    '     LCpoint.quantResult = higherQuantResult
                    '     LCpoint.MStype = spectrumClassification.MSsubType
                    '     mPept.higherLCpeakProfile.Add(LCpoint)
                    ' 
                    '     LCpoint.Xsig = someTime
                    ' 
                    '     'Changed PM_LCPEAK_YVALUE_MSPEAKAREA 2006-08-08
                    '     'LCpoint.Ysig = evenHigherQuantResult.intensity
                    '     LCpoint.Ysig = evenHigherQuantResult.peakArea
                    ' 
                    '     LCpoint.tagValue = _
                    '       evenHigherQuantResult.calibratedNeutralMass
                    '     LCpoint.tagValue2 = cycle
                    '     LCpoint.quantResult = evenHigherQuantResult
                    '     LCpoint.MStype = spectrumClassification.MSsubType
                    '     mPept.evenHigherLCpeakProfile.Add(LCpoint)
                    ' Else
                    '     Dim peter72 As Integer = 72 'One or more SILAC dish
                    '     '  results was zero.
                    ' End If

                    'Changed PM_REFACTOR 2006-10-05
                    'So much simpler!
                    'Changed PM_MEMORYPROBLEM 2006-08-30
                    'Compute it here to avoid changing signature or semantics
                    'of CalcParametersForCurrentMS2(). And because we effectively
                    'only call the function from here.
                    Dim anyNonZero2 As Boolean = False
                    Dim someItem As quantResultStructure
                    For Each someItem In quantResult 'E.g. 3 times for triple encoding.
                        anyNonZero2 = anyNonZero2 Or someItem.validResult
                    Next 'Through quantResult

                    'Changed PM_DISPLAY_FULL_RETT_RANGE 2006-11-05
                    Dim LCprofileItems As Integer = _
                      mPept.LCpeakProfiles(0).Count()
                    Dim firstLCpoint As Boolean = _
                      LCprofileItems = 0

                    'Changed PM_RET_RANGE_ASSERT 2006-11-05
                    Dim includeAnyWay As Boolean = _
                      keepFirstAndLastPoint AndAlso firstLCpoint

                    Dim addIt As Boolean = anyNonZero2 Or includeAnyWay

                    'Changed PM_RET_RANGE_ASSERT 2006-11-05
                    'For performance: we only need to save things if we are
                    '  NOT going to accept it. It also assures we don't add
                    '  the same LC point two times...
                    If addIt Then
                        mLastQuantResult = Nothing 'Marker that the last LC
                        '  point was included...
                    Else
                        mLastQuantResult = quantResult

                        mLastCycle = cycle
                        mLastSomeTime = someTime
                        mLastMSsubType = spectrumClassification.MSsubType
                    End If

                    If addIt Then
                        'Changed PM_REFACTOR 2006-11-05
                        ' '  Avoid adding invalid points with a signal of
                        ' '  zero. This can happen when there are no
                        ' '  datapoints in the mass ranges that are
                        ' '  used (number of mass ranges depends on
                        ' '  the quantitation mode).
                        ' '  DISABLED with True.....
                        ' 
                        ' Dim dish As Integer = 0
                        ' Dim someQuantResult As quantResultStructure
                        ' For Each someQuantResult In quantResult 'E.g. 3 times
                        '     '  for triple encoding.
                        ' 
                        '     'Does this have any effect?
                        '     If someItem.intensity < _
                        '       IDENTICAL_ZERO_INTENSITY_THRESHOLD Then
                        ' 
                        '         someItem.intensity = _
                        '           IDENTICAL_ZERO_INTENSITY_THRESHOLD
                        '     End If
                        ' 
                        '     Dim LCpoint As signalStructure
                        '     LCpoint.Xsig = someTime
                        '     LCpoint.Ysig = someQuantResult.peakArea
                        '     LCpoint.tagValue = someQuantResult.calibratedNeutralMass
                        '     LCpoint.tagValue2 = cycle
                        '     LCpoint.quantResult = someQuantResult
                        '     LCpoint.MStype = spectrumClassification.MSsubType
                        ' 
                        '     'mPept.lowerLCpeakProfile.Add(LCpoint)
                        '     mPept.LCpeakProfiles(dish).Add(LCpoint)
                        ' 
                        '     dish += 1
                        ' Next 'Through quantResult
                        Me.addToLCprofiles( _
                          someTime, cycle, _
                          spectrumClassification.MSsubType, quantResult, quantMCRoffset)
                    End If 'Add it...
                End If 'Matching cycle
            End While

            Dim jobFinished As Boolean = mChunkerLCPeakFind.jobFinished()
            Dim toReturn As Boolean = Not jobFinished
            If jobFinished Then
                'Things to do when the LC profile has been
                'found (by quantifying, etc.)

                'Changed PM_RET_RANGE_ASSERT 2006-11-05
                'Changed PM_DISPLAY_FULL_RETT_RANGE 2006-11-06
                If Not mLastQuantResult Is Nothing Then
                    'The last LC point was not accepted - e.g. identical zero
                    'quantitation result. We are going to add it in order to 
                    'plot the whole retention time window, even if e.g. the 
                    'first and/or the last part is identical zero/absent.
                    Me.addToLCprofiles( _
                      mLastSomeTime, mLastCycle, _
                      mLastMSsubType, mLastQuantResult, 0.0)
                End If

                'Changed PM_REFACTOR 2006-10-12
                ''Changed PM_REFACTOR 2006-06-20
                'Dim LCprofileToUse As ArrayList = mPept.lowerLCpeakProfile
                ''  Default, old behaviour if the block below is not in effect.
                Dim LCprofileToUse As _
                  Generic.List(Of _
                    massSpectrometryBase.signalStructure) = _
                      mPept.LCpeakProfiles(0)

                'Changed PM_EMPTY_LCPROFILE_BUG 2006-10-18

                'Changed PM_EMPTY_LCPROFILE_BUG 2006-10-18
                Trace.Assert(LCprofileToUse.Count > 0, _
                  "PIL ASSERT. LC profile is empty.... [1]")

                'Changed PM_LCMAX_PROBLEM 2004-07-17
                'Must be done this early, otherwise the LC peaks 
                'and LC max may be incorrect.
                Dim outScanFilter As spectrumSubTypeEnum
                filterLCProfiles( _
                  mPept, outScanFilter, mMSTypes, LCprofileToUse, _
                  True)
                '  Note: MS type should be the same across all profiles so
                '        it does not matter which we pass. But we want to 
                '        generalise in any case.

                'Changed PM_REFACTOR 2006-10-12
                ' 'Changed PM_LCPEAKDETECTION_OPTIONS 2006-06-20
                ' 'Later: use field "useHighestLCprofileForLCpeakDetection".
                ' '
                ' If True Then
                '     Select Case mLCpeakParameters.SILACdishForLCpeakDetection
                '         Case 1
                '             LCprofileToUse = mPept.lowerLCpeakProfile
                '         Case 2
                '             LCprofileToUse = mPept.higherLCpeakProfile
                '         Case 3
                '             LCprofileToUse = mPept.evenHigherLCpeakProfile
                '         Case Else
                '             Trace.Assert(False, _
                '               "PIL ASSERT. Select Case never fall-through")
                '     End Select
                ' End If
                LCprofileToUse = _
                  mPept.LCpeakProfiles( _
                    mLCpeakParameters.SILACdishForLCpeakDetection - 1)

                'Changed PM_EMPTY_LCPROFILE_BUG 2006-10-18
                Trace.Assert(LCprofileToUse.Count > 0, _
                  "PIL ASSERT. LC profile is empty.... [2]")

                'LC profile now found. Find LC peaks and fill in
                'field in peptide.

                Dim baseStartCycle As Integer = mStartCycle 'What is
                '  the difference??
                Dim LCMaxIndex As Integer

                Dim pLen As Integer = LCprofileToUse.Count

                'We now have the LC profile with, hopefully, one or
                'more LC peaks in it.

                Dim outLCpeakTimeCentroid As Double
                Dim outLCpeakIntensity As Double
                Dim outLCPeakIndexStart As Integer
                Dim outLCPeakIndexEnd As Integer
                Dim outLCpeakWindowStart As Integer
                Dim outLCpeakWindowEnd As Integer

                'Changed PM_EXPORT_MAXLC 2003-03-26
                Dim outLCMaxTime As Double
                Dim outLCMaxIntensity As Double

                'If pLen = 0 Then
                If pLen = 0 Or pLen = 1 Then 'For now: avoid single point LC peaks.
                    'No signal. Synthesise a result...
                    Dim peter6 As Integer = 6 'Should we do anything special here?
                Else
                    'Changed PM_LCPROFILE_DUMP 2003-11-16
                    BSignal.findSignalProfileProperties( _
                      LCprofileToUse, mLCProfileProperties)

                    'Changed PM_TYPESAFE 2006-11-01
                    'mLCPeakCandidates = New ArrayList
                    mLCPeakCandidates = New Generic.List(Of LCPeakInfoStructure)

                    mStr = ""

                    'Changed PM_LCPEAK_MSMSEVENT 2004-02-02
                    Dim isExternalQuant As Boolean = isExternalQuantitation(mPept)
                    Dim isInserted As Boolean = isInsertedPeptide(mPept)
                    Dim considerMSMSevent As Boolean = Not isExternalQuant 'Note: will
                    'also apply to inserted peptides. Should it be like that?

                    Dim findPeaksMaxSearchLevel As Integer = 99
                    Dim actualDeepestSearchLevel As Integer
                    BSignal.findThePeaks( _
                      LCprofileToUse, _
                      0, _
                      LCprofileToUse.Count - 1, _
                      considerMSMSevent, _
                      mPept.MSMSretentionTimeMinutes, _
                      mLCProfileProperties.maximumSignal.Ysig, _
                      mLCPeakCandidates, _
                      mDumpFileCounter, _
                      mPept.AASequence, _
                      mPept.calibratedMeasuredMCR, _
                      mPept.MascotCalculatedMass, _
                      mPept.charge, _
                      mStr, _
                      999.9, _
                      1999.9, _
                      findPeaksMaxSearchLevel, _
                      actualDeepestSearchLevel, _
                      1000000.0, _
                      0.3)

                    If False Then
                        'Note: findTheLCPeaks() modifies mStr.
                        If mStr.Length > 0 Then
                            PILInputOutput.pushToFile( _
                              "C:\_LCpeakDump_" & _
                              mPept.AASequence & "_" & mPept.charge & _
                              "_" & mPept.rawFileID & ".txt", mStr)
                        End If
                    End If

                    Me.findBestLCpeak( _
                      outLCpeakTimeCentroid, _
                      outLCpeakWindowStart, outLCpeakWindowEnd, _
                      outLCMaxTime, outLCMaxIntensity, LCMaxIndex, _
                      considerMSMSevent, mPept.MSMSretentionTimeMinutes)

                    If False Then
                        'Dim dummy1 As Double
                        'First try to find an LC peak in the entire LC time window
                        'BSignal.findSignalPeak( _
                        '  LCprofileToUse, 0, LCprofileToUse.Count - 1, 999.9, _
                        '  outLCpeakTimeCentroid, outLCpeakIntensity, _
                        '  outLCPeakIndexStart, outLCPeakIndexEnd, _
                        '  outLCpeakWindowStart, outLCpeakWindowEnd, _
                        '  outLCMaxTime, outLCMaxIntensity, LCMaxIndex, dummy1)
                    End If

                    'Changed PM_IMPORT_TROUBLE 2003-03-26
                    'This can fire if e.g. quantify import does not set it. If it
                    'is not set then re-finding of the LC peak would almost always
                    'take place and this is definitely not what we want.
                    Trace.Assert(mPept.MSMSretentionTimeMinutes > 0.0, _
                      "PIL ASSERT: mPept.MSMSretentionTimeMinutes > 0.0")

                    Dim stDiffSecs As Double = _
                      outLCpeakTimeCentroid - _
                      mPept.MSMSretentionTimeMinutes * 60
                    Dim AbsStDiffSecs As Double = Math.Abs(stDiffSecs)

                    Const MAX_MSMSEVENT_TO_LCPEAKCENTROD_TIME As Double = 30.0
                    If False AndAlso _
                       AbsStDiffSecs > MAX_MSMSEVENT_TO_LCPEAKCENTROD_TIME Then

                        'If the LC peak is too far from the MS/MS retention time then
                        'there is something wrong. In most cases a second higher peak
                        'has been found.

                        'Now folded into findSignalPeak(). Delete when everything is honky-dory.
                        ' 'Find a local minimum, going to the left from the current
                        ' 'peak's left side. This will be the new end time for an LC peak find.
                        '
                        ' Dim newWindowEndIndex As Integer = outLCPeakIndexStart
                        ' Dim prevY As Double = 1.0E+20
                        ' Dim leftY As Double
                        ' Dim stopNow As Boolean = False
                        ' While Not stopNow And newWindowEndIndex > 0
                        '     Dim curY As Double = ...( _
                        '         LCprofileToUse(newWindowEndIndex), _
                        '         signalStructure).Ysig
                        '     If curY <= prevY Then
                        '         newWindowEndIndex -= 1
                        '     Else
                        '         stopNow = True
                        '     End If
                        '
                        '     prevY = curY
                        ' End While
                        ' newWindowEndIndex += 1 'Land at the minimum.

                        Dim newWindowEndIndex As Integer = outLCpeakWindowStart
                        If newWindowEndIndex >= 1 Then 'Require at least two points for
                            '  a lower peak to the left of the originally found.

                            Dim dummy2 As Double
                            'We have shrinked the time window from the right. Try again to find a peak...
                            BSignal.findSignalPeak( _
                              LCprofileToUse, 0, newWindowEndIndex, _
                              999.9, 1999.9, _
                              outLCpeakTimeCentroid, outLCpeakIntensity, _
                              outLCPeakIndexStart, outLCPeakIndexEnd, _
                              outLCpeakWindowStart, outLCpeakWindowEnd, _
                              outLCMaxTime, outLCMaxIntensity, LCMaxIndex, _
                              dummy2 _
                            )
                        Else
                            'Stick with the first LC peak find!
                            Dim peter2 As Integer = 2
                        End If

                        'Disabled. How should it be detected??
                        ' Trace.Assert(outLCpeakWindowStart > 0, "PIL ASSERT. Trouble finding the right LC peak....")
                        ' 'we probably got the
                        ' 'right one in the first place....
                    End If
                End If 'Signal OK

                mPept.LCpeakDetectionTimeCentroidSeconds = outLCpeakTimeCentroid
                mPept.LCMaxTimeSeconds = outLCMaxTime
                mPept.LCMaxIntensity = outLCMaxIntensity

                Dim centroidMassForMax As Double
                If pLen = 0 Then
                    centroidMassForMax = 17.7 '??  What should it be?
                Else
                    centroidMassForMax = _
                      LCprofileToUse(LCMaxIndex).tagValue
                End If

                mPept.neutralMScentroidForLCMax = centroidMassForMax

                'Changed PM_EMPTY_LCPROFILE_BUG 2006-10-18
                Trace.Assert(LCprofileToUse.Count > 0, _
                  "PIL ASSERT. LC profile is empty.... [3]")
                If LCprofileToUse.Count = 0 Then
                    Dim peter0 As Integer = 100
                End If

                'Changed PM_FINNEGAN_BAD_LCPEAK_WINDOW 2003-10-21
                Dim LCpeakWindowStartCycle As Integer = _
                  LCprofileToUse(outLCpeakWindowStart).tagValue2
                Dim LCpeakWindowEndCycle As Integer = _
                  LCprofileToUse(outLCpeakWindowEnd).tagValue2

                'mLCwindowStartCycle = mStartCycle + outLCpeakWindowStart
                'mLCwindowEndCycle = mStartCycle + outLCpeakWindowEnd
                mLCwindowStartCycle = LCpeakWindowStartCycle
                mLCwindowEndCycle = LCpeakWindowEndCycle

                'Changed PM_FINNEGAN_BAD_LCPEAK_WINDOW 2003-10-21
                ''Changed PM_MSQA 2003-03-31
                'Dim theMaxCycle As Integer = baseStartCycle + LCMaxIndex
                Dim maxCycle As Integer = _
                  LCprofileToUse(LCMaxIndex).tagValue2

                mPept.LCMaxCycle = maxCycle
                mPept.LCMaxIndex = LCMaxIndex
            Else
                Dim peter2 As Integer = 2 'Job not finished...
            End If 'job finished.

            Return toReturn
        End Function 'doChunkLCPeakFind


        'Changed PM_BETTER_LCPEAK_DETECTION 2003-10-16
        '****************************************************************************
        '*  SUBROUTINE NAME:   findBestLCpeak                                       *
        'd$ <summary>
        'd$   Purpose: Find a candidate list of LC peaks. This is done by
        'd$            subdiving the interval XYZ
        'd$ 
        'd$   <see cref="T:VBXMLDoc.CVBXMLDoc" />.
        'd$ </summary>
        Private Sub findBestLCpeak( _
          ByRef anOutSignalPeakXCentroid As Double, _
          ByRef anOutSignalPeakWindowStart As Integer, _
          ByRef anOutSignalPeakWindowEnd As Integer, _
          ByRef anOutSignalMaxX As Double, ByRef anOutSignalMaxY As Double, _
          ByRef anOutSignalMaxIndex As Integer, _
          ByVal aConsiderMSMSevent As Boolean, _
          ByVal aMSMSretentionTimeMinutes As Double)

            Const PEAK_TO_BACKGROUND_RATIO_THRESHOLD As Double = 3.0

            mLCPeakCandidates.Sort(New SortByRelError) 'Necessary because
            '  of the selection of successive best mass accuracy errors in
            '  the second loop below. If we didn't sort the result would
            '  depend on the order of peak candidates in mLCPeakCandidates.
            '  With the sort we will process the worst mass accuracy candidates
            '  first.

            Dim len As Integer = mLCPeakCandidates.Count
            Trace.Assert(len > 0, "PIL ASSERT. No LC peaks!.")

            Dim curLCpeakInfo As LCPeakInfoStructure

            Dim MSMSretentionTimeSecs As Double = 60.0 * aMSMSretentionTimeMinutes
            Dim minDiff As Double = 1000000000.0
            Dim indexForMinDiff As Integer = -1

            Dim foundIndex As Integer = 0
            Dim foundLCpeakToUse As Boolean = False

            'Find some properties of the list, like the highest peak.
            Dim maxPeakIntensity As Double = -1000000000.0
            Dim earlyFoundPeak As Boolean = False
            Dim index As Integer = 0
            If True Then
                For Each curLCpeakInfo In mLCPeakCandidates
                    Dim curIntensity As Double = curLCpeakInfo.maxIntensity
                    If curIntensity > maxPeakIntensity Then
                        maxPeakIntensity = curIntensity
                    End If

                    Dim diffToMSMS As Double = _
                      curLCpeakInfo.LCpeakTimeCentroid - MSMSretentionTimeSecs
                    Dim absDiff As Double = Math.Abs(diffToMSMS)
                    If absDiff < minDiff Then
                        minDiff = absDiff
                        indexForMinDiff = index
                    End If

                    If aConsiderMSMSevent Then
                        If curLCpeakInfo.MSMSeventInPeak Then
                            If curLCpeakInfo.peakToBackgroundRatio > _
                              PEAK_TO_BACKGROUND_RATIO_THRESHOLD Then
                                'Note: even though MS-MS event is in a peak it
                                '  must still be a good peak, sufficiently above
                                '  the background.

                                'Then we are done, we have already found the peak!
                                earlyFoundPeak = True
                                foundIndex = index
                            End If
                        End If
                    End If

                    index += 1
                Next
            End If

            If indexForMinDiff <> foundIndex Then
                Dim peter9 As Integer = 9
            End If

            'Changed PM_LCPEAK_MSMSEVENT 2004-02-02
            If earlyFoundPeak Then
                foundLCpeakToUse = True
                'foundIndex already set
            Else
                If aConsiderMSMSevent Then
                    'MSMS event time is somewhere outside our candidate
                    'peaks. Use the peak that is closesed to
                    'the MSMS event time.
                    foundLCpeakToUse = True
                    foundIndex = indexForMinDiff
                Else
                    'Else use the old rules: 
                    '  1. Peak to background ratio must be above 3
                    '  2. Best relative mass error

                    Dim bestRelError As Double = 1000000000.0
                    Dim foundIndex_BestRelError As Integer = 0
                    Dim curIndex As Integer = 0
                    For Each curLCpeakInfo In mLCPeakCandidates
                        Dim curRelError As Double = curLCpeakInfo.absRelError_PPM
                        Dim curIntensityRelativeToMaxPeak As Double = _
                          curLCpeakInfo.maxIntensity / maxPeakIntensity
                        If curRelError < bestRelError Then
                            bestRelError = curRelError
                            foundIndex_BestRelError = curIndex

                            If curLCpeakInfo.peakToBackgroundRatio > _
                              PEAK_TO_BACKGROUND_RATIO_THRESHOLD Then

                                If curIntensityRelativeToMaxPeak > 0.2 Then 'Require 
                                    '  peak to be at least 20 % of the most
                                    '  intense LC peak.
                                    foundLCpeakToUse = True
                                    foundIndex = curIndex

                                    If curIntensityRelativeToMaxPeak < 0.999 Then
                                        'This means the highest LC peak was NOT picked.
                                        Dim seq As String = mPept.AASequence
                                    End If
                                Else
                                    Dim peter12 As Integer = 12
                                End If
                            Else
                                Dim peter7 As Integer = 7
                            End If
                        End If
                        curIndex += 1
                    Next
                    If Not foundLCpeakToUse Then
                        foundIndex = foundIndex_BestRelError 'If no peak had a height
                        '  to background ratio greater than 3 then select the one with
                        '  the best relative error.
                    End If
                End If
            End If

            Dim LCPeakToUse As LCPeakInfoStructure = _
              mLCPeakCandidates(foundIndex)

            'Test
            If Not LCPeakToUse.MSMSeventInPeak Then
                Dim peter29 As Integer = 29
            End If

            anOutSignalPeakXCentroid = LCPeakToUse.LCpeakTimeCentroid
            anOutSignalPeakWindowStart = LCPeakToUse.LCpeakWindowStart
            anOutSignalPeakWindowEnd = LCPeakToUse.LCpeakWindowEnd
            anOutSignalMaxX = LCPeakToUse.LCMaxTime
            anOutSignalMaxY = LCPeakToUse.maxIntensity
            anOutSignalMaxIndex = LCPeakToUse.LCMaxIndex
        End Sub 'findBestLCpeak


        'Changed PM_REFACTOR 2004-07-17
        '****************************************************************************
        '*  SUBROUTINE NAME:   filterLCProfiles                                      *
        'd$ <summary>
        'd$   Purpose: In-place filtering of the 3 LC profiles.
        'd$ 
        'd$   <see cref="T:VBXMLDoc.CVBXMLDoc" />.
        'd$ </summary>
        Private Shared Sub filterLCProfiles( _
          ByRef anOutPept As PeptideHitStructure, _
          ByRef anOutScanFilter As spectrumSubTypeEnum, _
          ByVal anInMSTypes As QuantMSTypesEnum, _
          ByRef anLCprofileForMStype As _
            Generic.List(Of massSpectrometryBase.signalStructure), _
          ByVal aKeepFirstAndLastPoint As Boolean _
          )
            'Old:
            '  ByRef anLCprofileForMStype As ArrayList

            'Why is it called anOutPept??

            Dim zoomScanCount As Integer = 0
            Dim normalMSCount As Integer = 0
            Dim sPoint As signalStructure

            'Changed PM_REFACTOR 2006-06-20
            'For Each sPoint In anOutPept.lowerLCpeakProfile
            For Each sPoint In anLCprofileForMStype
                If sPoint.MStype = spectrumSubTypeEnum.enumIsZoomMS Then
                    zoomScanCount += 1
                Else
                    normalMSCount += 1
                End If
            Next

            Dim doFilter As Boolean = False
            Select Case anInMSTypes
                Case QuantMSTypesEnum.enumAllMStypes
                    anOutScanFilter = spectrumSubTypeEnum.enumST_DoesNotApply

                    'Default OK - include all
                Case QuantMSTypesEnum.enumMS_SIM
                    anOutScanFilter = spectrumSubTypeEnum.enumIsZoomMS
                    If normalMSCount > 0 Then
                        doFilter = True
                    End If

                Case QuantMSTypesEnum.enumMSFullScan
                    anOutScanFilter = spectrumSubTypeEnum.enumIsNormalMS
                    If zoomScanCount > 0 Then
                        doFilter = True
                    End If

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

            'Changed PM_MSTYPES_FOR_QUANT_OPTION 2004-09-13
            'anOutScanFilter = spectrumSubTypeEnum.eIsNormalMS
            'If zoomScanCount > 0 Then
            '    anOutScanFilter = spectrumSubTypeEnum.eIsZoomMS
            'End If

            'Changed PM_MSTYPES_FOR_QUANT_OPTION 2004-09-13
            If doFilter Then
                Trace.Assert(anInMSTypes <> QuantMSTypesEnum.enumAllMStypes, _
                  "PIL ASSERT. anInMSTypes <> QuantMSTypesEnum.enumAllMStypes.")

                'If zoomScanCount = 0 Or normalMSCount = 0 Then
                'If they are all of the same type then we don't have to do anything!.

                'Changed PM_REFACTOR 2006-10-13
                'Dim newLowerLCpeakProfile As ArrayList = New ArrayList
                'Dim newHigherLCpeakProfile As ArrayList = New ArrayList
                'Dim newEvenHigherLCpeakProfile As ArrayList = New ArrayList
                Dim dishes As Integer = anOutPept.LCpeakProfiles.Count
                Dim newProfiles As _
                  Generic.List(Of _
                    Generic.List(Of massSpectrometryBase.signalStructure)) = _
                      New Generic.List(Of _
                        Generic.List(Of massSpectrometryBase.signalStructure))
                Dim lastIndex As Integer = dishes - 1
                Dim j As Integer
                For j = 0 To lastIndex 'E.g. 3 times for triple encoding
                    'Add empty list, one for each SILAC dishes
                    newProfiles.Add( _
                      New Generic.List(Of massSpectrometryBase.signalStructure))
                Next j

                Dim sIndex As Integer = 0
                Dim insertIndex As Integer = 0 'Needed?

                Dim lastIndex3 As Integer = anLCprofileForMStype.Count() - 1

                'Changed PM_REFACTOR 2006-06-20
                'For Each sPoint In anOutPept.lowerLCpeakProfile
                For Each sPoint In anLCprofileForMStype

                    'Changed PM_RET_RANGE_ASSERT_JD 2006-11-09
                    Dim firstPoint As Boolean = sIndex = 0
                    Dim lastPoint As Boolean = sIndex = lastIndex3
                    Dim includeAnyway As Boolean = _
                      aKeepFirstAndLastPoint AndAlso (firstPoint Or lastPoint)

                    'If first and last point is kept: should we coerce
                    'the MS type to the one we filter for?
                    '
                    'Does it matter? - does field LCpeakProfiles contain 
                    'information about the MS type?
                    '
                    If sPoint.MStype = anOutScanFilter Or includeAnyway Then
                        'Note: we do not check for anInMSTypes=enumAllMStypes
                        'becase  ...???

                        'Changed PM_REFACTOR 2006-10-13
                        ' newLowerLCpeakProfile.Add(sPoint)
                        ' 'Changed PM_POSSIBLE_OLD_BUG 2006-10-13
                        ' 'Must have been a bug:
                        ' '  it assumes anLCprofileForMStype is the LC profile
                        ' '  for wild!!!!
                        ' 
                        ' Dim higherPoint As signalStructure = _
                        '   ...(anOutPept.higherLCpeakProfile(sIndex), signalStructure)
                        ' 
                        ' newHigherLCpeakProfile.Add(higherPoint)
                        ' 
                        ' Dim evenHigherPoint As signalStructure = _
                        '   ...(anOutPept.evenHigherLCpeakProfile(sIndex), signalStructure)
                        ' newEvenHigherLCpeakProfile.Add(evenHigherPoint)
                        Dim lastIndex2 As Integer = dishes - 1
                        Dim dish As Integer
                        For dish = 0 To lastIndex2
                            newProfiles(dish).Add( _
                              anOutPept.LCpeakProfiles(dish)(sIndex))
                        Next dish

                        insertIndex += 1
                    End If
                    sIndex += 1
                Next

                'For debugging only.
                If sIndex = insertIndex Then
                    Dim peter1 As Integer = 1 'Same size.
                Else
                    Dim peter2 As Integer = 2 'Not same size....
                End If

                'Replace the old LC profile. The old will be garbage collected.
                'Changed PM_REFACTOR 2006-10-13
                ' anOutPept.lowerLCpeakProfile = newLowerLCpeakProfile
                ' anOutPept.higherLCpeakProfile = newHigherLCpeakProfile
                ' anOutPept.evenHigherLCpeakProfile = newEvenHigherLCpeakProfile
                anOutPept.LCpeakProfiles = newProfiles

            Else
                Dim peter7 As Integer = 7
            End If
        End Sub 'filterLCProfiles


        '****************************************************************************
        '*  SUBROUTINE NAME:   GetLCprofileResult                                   *
        'd$ <summary>
        'd$   Purpose: Read out result of previous calls to doChunkLCPeakFind. It
        'd$            is assumed it returned false in the last call to it and only
        'd$            that one.
        'd$ 
        'd$   <see cref="T:VBXMLDoc.CVBXMLDoc" />.
        'd$ </summary>
        Public Sub GetLCprofileResult( _
          ByRef anOutPept As PeptideHitStructure, _
          ByRef aLCwindowStartCycle As Integer, _
          ByRef aLCwindowEndCycle As Integer, _
          ByRef anOutScanFilter As spectrumSubTypeEnum, _
          ByVal anInMSTypes As QuantMSTypesEnum _
          )

            anOutPept = mPept

            anOutScanFilter = spectrumSubTypeEnum.enumST_DoesNotApply 'If false
            '  below.

            'Changed PM_REFACTOR 2004-07-17
            'If True Then
            '    anOutPept.lowerLCpeakProfile = New ArrayList
            '    anOutPept.higherLCpeakProfile = New ArrayList
            '    anOutPept.evenHigherLCpeakProfile = New ArrayList
            '
            '    'Changed PM_MASCOT2_ZOOMSCAN_QUANT_FILTER 2004-03-16
            '    'For now we use this bottleneck to filter for zoom scan (if any)
            '    Dim zoomScanCount As Integer = 0
            '    Dim normalMSCount As Integer = 0
            '    Dim sPoint As signalStructure
            '    For Each sPoint In mPept.lowerLCpeakProfile
            '        If sPoint.MStype = spectrumSubTypeEnum.eIsZoomMS Then
            '            zoomScanCount += 1
            '        Else
            '            normalMSCount += 1
            '        End If
            '    Next
            '
            '    'If there are any zoom spectra use those in the LC profile and
            '    'for quantitation, otherwise use the normal MS spectra.
            '    anOutScanFilter = _
            '      spectrumSubTypeEnum.eIsNormalMS
            '    If zoomScanCount > 0 Then
            '        anOutScanFilter = spectrumSubTypeEnum.eIsZoomMS
            '    End If
            '
            '    Dim sIndex As Integer = 0
            '    For Each sPoint In mPept.lowerLCpeakProfile
            '        If sPoint.MStype = anOutScanFilter Then
            '            anOutPept.lowerLCpeakProfile.Add(sPoint)
            '
            '            Dim higherPoint As signalStructure = _
            '              ...(mPept.higherLCpeakProfile(sIndex), signalStructure)
            '            anOutPept.higherLCpeakProfile.Add(higherPoint)
            '
            '            Dim evenHigherPoint As signalStructure = _
            '              ...(mPept.evenHigherLCpeakProfile(sIndex), signalStructure)
            '            anOutPept.evenHigherLCpeakProfile.Add(evenHigherPoint)
            '        End If
            '        sIndex += 1
            '    Next
            'End If

            'Note: it does not matter which profile we use
            '      for this as all LC profiles have exactly
            '      the same pattern of MS spectrum types.
            'Changed PM_REFACTOR 2006-10-13
            'filterLCProfiles(anOutPept, anOutScanFilter, anInMSTypes, _
            '  anOutPept.lowerLCpeakProfile)
            filterLCProfiles( _
              anOutPept, anOutScanFilter, anInMSTypes, _
              anOutPept.LCpeakProfiles(0), _
              True)

            'Changed PM_REFACTOR 2006-10-13
            ' Dim len1 As Integer = anOutPept.lowerLCpeakProfile.Count
            ' Dim len2 As Integer = anOutPept.higherLCpeakProfile.Count
            ' Dim len3 As Integer = anOutPept.evenHigherLCpeakProfile.Count
            ' 
            ' Trace.Assert(len1 = len2, _
            '   "PIL ASSERT. Higher LC profile is not of the same length (" & len2 & _
            '   ") as the lower LC profile's (" & len1 & ").")
            ' 
            ' Trace.Assert(len1 = len3, _
            '   "PIL ASSERT. Even higher LC profile is not of the same length (" & len3 & _
            '   ") as the lower LC profile's (" & len1 & ").")
            Dim dishes As Integer = anOutPept.LCpeakProfiles.Count
            Trace.Assert(dishes < 15, "PIL ASSERT. <message>.") 'For now...
            Dim prevCount As Integer = -1
            Dim lastIndex As Integer = dishes - 1
            Dim j As Integer
            For j = 0 To lastIndex
                Dim count As Integer = anOutPept.LCpeakProfiles(j).Count

                If prevCount >= 0 Then
                    Trace.Assert(count = prevCount, _
                     "PIL ASSERT. LC profile " & (j + 1) & _
                     "is not of the same length (" & count & _
                      ") as LC profile " & j & " (" & prevCount & ").")
                End If
                prevCount = count
            Next j

            aLCwindowStartCycle = mLCwindowStartCycle
            aLCwindowEndCycle = mLCwindowEndCycle
        End Sub 'GetLCprofileResult


        'Changed PM_REFACTOR 2003-10-15. Moved from QuantWindow.vb.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub computeSILACmasses( _
            ByRef anInOutPept As PeptideHitStructure, _
            ByRef anOutUncalibratedSILACmasses As Generic.List(Of Double), _
            ByRef anOutCharge As Integer _
            )

            'Note: after the refactorings this function has almost become trivial;
            '      it just reads a field for each item in the peptide
            '      field "quantValues".
            '      Thus this function is a candidate to be eliminated. E.g. to
            '      be merge with coreLowerAndHigherMZ().

            'Old:
            '  ByVal anA As Double, ByVal aB As Double, _

            'Changed PM_REFACTOR 2006-10-03
            anOutUncalibratedSILACmasses = New Generic.List(Of Double)

            'Changed PM_REFACTOR 2006-10-03
            'Old:
            'ByRef aOutLowerMZuncalib As Double, _
            'ByRef aOutHigherMZuncalib As Double, _
            'ByRef aOutEvenHigherMZuncalib As Double, _

            'Changed PM_REFACTOR_MARKER 2006-10-03
            'Later: eliminate anOutCharge

            'ByRef anInOutPeptides As massSpectrometryBase.PILpeptides, _
            'ByVal anInPeptideToken As Integer, _

            'Changed PM_REFACTOR 2006-03-15
            'ByRef aInProt As ProteinHitStructure, _
            'ByVal aPepIndex As Integer, _

            'Changed PM_REFACTOR 2006-10-03
            ''Changed PM_GENERALISED_QUANTMODES_OBJECTEXCEPTION 2005-06-13
            'aOutLowerMZuncalib = -34.5
            'aOutLowerMZuncalib = -34.5
            'aOutEvenHigherMZuncalib = -34.5

            'Changed PM_REFACTOR 2006-10-03
            ''Changed PM_REFACTOR 2006-03-15
            ''Dim thePept As PeptideHitStructure = _
            ''  ...(aInProt.pepts(aPepIndex), _
            ''    PeptideHitStructure)
            ''aCurPeptide.currentPeptide(pept)
            'Dim pept As PeptideHitStructure = helper.blankPeptide() 'Keep compiler happy.
            'anInOutPeptides.peptideByToken(anInPeptideToken, pept)

            anOutCharge = anInOutPept.charge

            'Changed PM_REFACTOR 2006-10-03. No longer needed.
            'Dim update As Boolean = True
            'If Not anInOutPept.quantValues Is Nothing Then
            '    If anInOutPept.quantValues.Count > 0 Then
            '        If ...(anInOutPept.quantValues(0), _
            '          derivedQuantInfoStructure).calibratedMCR2 _
            '            > 0.0 Then
            '            update = False
            '        Else
            '            Dim peter3 As Integer = 3
            '        End If
            '    Else
            '        Dim peter2 As Integer = 2
            '    End If
            'Else
            '    Dim peter1 As Integer = 1
            'End If

            'Changed PM_EVENMORE_GENERALISED_QUANTMODES 2005-04-11
            'Adaption to existing.
            Dim someQuantValue As derivedQuantInfoStructure
            'Dim index As Integer = 0

            Dim lastMass As Double = -1.0E+20

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

                someQuantValue = anInOutPept.quantValues2(j)

                Dim MCRuncalib As Double = someQuantValue.MCRuncalib

                'Changed PM_REFACTOR 2006-10-03. No longer needed.
                ' 'Changed PM_REFACTOR 2006-10-03 
                ' someQuantValue.calibratedMCR2 = anA + aB * MCRuncalib
                ' 
                ' 'Update?
                ' If update Then
                '     anInOutPept.quantValues(j) = someQuantValue 'Write back...
                ' End If

                'Changed PM_REFACTOR 2006-10-03
                'If j = 0 Then
                '    'Changed PM_CALIB_VALUES_IN_UNCALIB_DATA 2006-03-20
                '    'aLowerMCR = someQuantValue.calibratedMCR
                '    aOutLowerMZuncalib = MCRuncalib
                'End If
                '
                'If j = 1 Then
                '    'Changed PM_CALIB_VALUES_IN_UNCALIB_DATA 2006-03-20
                '    'aHigherMCR = someQuantValue.calibratedMCR
                '    aOutHigherMZuncalib = MCRuncalib
                'End If
                '
                'If j = 2 Then
                '    'Changed PM_CALIB_VALUES_IN_UNCALIB_DATA 2006-03-20
                '    'aEvenHigherMCR = someQuantValue.calibratedMCR
                '    aOutEvenHigherMZuncalib = MCRuncalib
                'End If
                If MCRuncalib < lastMass Then
                    MCRuncalib = lastMass
                End If

                Trace.Assert(MCRuncalib > 40.0, _
                  "PIL ASSERT: MCRuncalib>40.0. Value: " & MCRuncalib)

                anOutUncalibratedSILACmasses.Add(MCRuncalib)
                lastMass = MCRuncalib
            Next

            'Changed PM_REFACTOR 2006-10-03. Now happens elsewhere...
            'If update Then
            '    'Changed PM_REFACTOR 2006-03-15
            '    'aInProt.pepts(aPepIndex) = thePept 'Write-back..
            '    'aCurPeptide.updateCurrentPeptide(pept)
            '    anInOutPeptides.updatePeptideByToken(aPeptideToken, pept)
            'End If

            'Changed PM_REFACTOR 2006-10-03. Now done in the loop above.
            'If aOutHigherMZuncalib < aOutLowerMZuncalib Then
            '    aOutHigherMZuncalib = aOutLowerMZuncalib
            'End If
            '
            'If aOutEvenHigherMZuncalib < aOutHigherMZuncalib Then
            '    aOutEvenHigherMZuncalib = aOutHigherMZuncalib
            'End If

            'Disabled for now, but it is used in retentionTimeCorrelator.vb
            '
            ' 'Changed PM_MORE_MEMORY_WORKAROUND 2004-09-07
            ' Trace.Assert(thePept.lowerMZuncalib > 0.0, _
            '   "PIL ASSERT. thePept.lowerMZuncalib is not set!")

            'Changed PM_REFACTOR 2006-10-03. Now done in the loop above.
            'Trace.Assert(aOutHigherMZuncalib > 40.0, _
            '  "PIL ASSERT: aHigherMCR>40.0. Value: " & aOutHigherMZuncalib)
        End Sub 'computeSILACmasses


        'Changed PM_REFACTOR 2003-10-15. Moved from QuantWindow.vb.
        'Usually used for computing properties for a particular monoisotopic
        'peak in a MS spectrum.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Private Shared Sub GetIntegratedPeakIntensityAtMass( _
          ByVal aRawFileRef As Integer, _
          ByVal aMCR As Double, _
          ByVal aDeltaMass As Double, _
          ByRef anInRawDataFileHandling As rawDataFileHandling, _
          ByVal aFixBackground As Double, _
 _
          ByRef anOutIntensity As Double, _
          ByRef anOutMass As Double, ByRef anOutMaxSignal As Double, _
          ByRef anOutPeakArea As Double, _
          ByRef anOutAnyResult As Boolean)

            'Changed PM_SEVERALWIFFS 2003-08-26
            Trace.Assert(aRawFileRef > 0, _
              "PIL ASSERT. Bad raw file ID, " & aRawFileRef & ".")

            'Changed PM_BUGDETECT 2003-04-10
            Trace.Assert(aMCR > 10.0, _
              "PIL ASSERT. aMZ > 10.0. In GetIntegratedPeakIntensityAtMass().")

            Dim startMass As Double = aMCR - aDeltaMass
            Dim endMass As Double = aMCR + aDeltaMass

            'Changed PM_SAVE_MEMORY 2006-11-13
            ''Changed PM_REFACTOR 2006-10-12
            ''Dim signal As ArrayList = New ArrayList
            'Dim signal As Generic.List(Of massSpectrometryBase.signalStructure) = _
            '  New Generic.List(Of massSpectrometryBase.signalStructure)
            Dim signal As Generic.List(Of massSpectrometryBase.signalStructure) = _
              Nothing

            Dim dataPointsInfo As dataPointsInfoStructure2

            'Changed PM_SEVERALWIFFS 2003-08-27
            'mRawDataFileHandling.DataPoints( _
            '  startMass, endMass, 883, signal, dataPointsInfo)
            anInRawDataFileHandling.DataPoints( _
              startMass, endMass, aRawFileRef, signal, dataPointsInfo)

            Dim sCount As Integer = signal.Count
            anOutAnyResult = sCount > 0

            Dim yMax As Double = dataPointsInfo.maximumSignal.Ysig
            Dim ySum As Double = 0.0
            Dim yOver50PercentSum As Double = 0.0
            Dim xySum As Double = 0.0
            Dim yArea As Double = 0.0
            If anOutAnyResult Then
                Trace.Assert(dataPointsInfo.maximumSignal.Ysig >= 0.0, _
                  "PIL ASSERT. dataPointsInfo.maxY >= 0.0. Value is " & _
                  dataPointsInfo.maximumSignal.Ysig & _
                  ". In GetIntegratedPeakIntensityAtMass().")

                Dim xVal As Double
                Dim yVal As Double
                Dim yOverBckGr As Double
                Dim yOver50Percent As Double

                Dim backGr As Double = aFixBackground
                Dim firstTime As Boolean = True
                Dim prevX As Double
                Dim prevY As Double

                Dim endIndex As Integer = sCount - 1
                Dim j As Integer
                For j = 0 To endIndex
                    Dim dataPoint As signalStructure = signal.Item(j)
                    xVal = dataPoint.Xsig
                    yVal = dataPoint.Ysig
                    yOverBckGr = Math.Max(yVal - backGr, 0)
                    ySum += yOverBckGr
                    'could use this to determine if peak shifts due to another
                    'peak appearing.
                    yOver50Percent = Math.Max((yVal - (0.5 * yMax)), 0)
                    yOver50PercentSum += yOver50Percent
                    xySum += yOver50Percent * xVal

                    'Changed PM_XIC 2003-03-09
                    'Actual computation of area under "peak curve" here
                    If firstTime Then
                        firstTime = False
                    Else
                        'Approximation is: piece-wise linear between the data points.
                        Dim peakArea As Double = _
                          0.5 * (xVal - prevX) * (prevY + yOverBckGr)
                        'yArea += yOverBckGr / 7 'Stub
                        yArea += peakArea
                    End If

                    prevX = xVal
                    prevY = yOverBckGr
                Next j

                'Changed PM_MEMORY_ALLOCATION 2004-08-02
                signal = Nothing
            Else
                Dim peter2 As Integer = 2 'No data points...
            End If

            anOutMaxSignal = yMax
            anOutIntensity = ySum

            'Trace.Assert(yOver50PercentSum > 0.0, _
            '  "PIL ASSERT. yOver50PercentSum > 0.0. In GetIntegratedPeakIntensityAtMass().")
            If yOver50PercentSum > 0.0 Then
                anOutMass = xySum / yOver50PercentSum
            Else
                anOutMass = aMCR 'Mass is undefined when there are no data 
                '            points, but we set it to the input value.
            End If

            'Changed PM_XIC 2003-03-09
            anOutPeakArea = yArea
        End Sub 'GetIntegratedPeakIntensityAtMass()


        'Changed PM_REFACTOR 2003-10-15. Moved from QuantWindow.vb.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '* Note: implicit parameters are mOptions, mA, mB,                          *
        '*       mProt (current peptide through mCurrPepIdx)                        *
        '****************************************************************************
        'Changed PM_REFACTOR 2003-04-09. Use of quantResultStructure instead of
        '  scalar arguments.
        Public Shared Sub CalcParametersForCurrentMS( _
          ByVal aRawFileRef As Integer, _
 _
          ByRef anInCalibration As SDUPrecalibrator, _
          ByVal aDeltaMass As Double, _
          ByRef anInRawDataFileHandling As rawDataFileHandling, _
          ByVal aFixBackground As Double, _
          ByVal aQuantModeClassification As QuantModeClassificationStruct, _
 _
          ByRef aQuantResult As Generic.List(Of quantResultStructure), _
          ByRef aValidResult As Boolean, _
          ByVal aCharge As Integer, _
          ByRef anInUnCalibratedSILACmasses2 As Generic.List(Of Double), _
          ByRef anOutOffsetMCR As Double _
            )

            'Changed PM_REFACTOR 2006-10-05
            'So much simpler!
            Dim validResult As Boolean = True


            Dim SILACnumber As Integer = 1
            Dim someQuantResult As quantResultStructure

            aQuantResult = New Generic.List(Of quantResultStructure)

            'Changed PM_QUANT_AUTO_CENTERING 2006-11-13
            Dim autoCenter As Boolean = True
            Dim offsetMCR As Double = 0.0 'Outside the loop: we only 
            '  find the center offset for wild type - the other
            '  SILAC dishes are shifted by the same value.
            Dim isWildDish As Boolean = True

            Dim MCRuncalibMass As Double
            'One iteration for each SILAC dish.
            For Each MCRuncalibMass In anInUnCalibratedSILACmasses2

                autoCenter = isWildDish 'Only find the offset for wild. The
                '  other dishes should be shifted by the same amount.

                'For breakpoints.
                If Not isWildDish Then
                    Dim peter2 As Integer = 2
                End If

                Dim iterations As Integer = 0
                Dim end2 As Boolean = False

                While Not end2
                    iterations += 1

                    'Normally 11 or below.
                    Select Case iterations
                        Case 1
                            Dim peter1 As Integer = 1
                        Case 2
                            Dim peter2 As Integer = 2
                        Case 3
                            Dim peter3 As Integer = 3
                        Case 4
                            Dim peter4 As Integer = 4
                        Case 5
                            Dim peter5 As Integer = 5
                        Case 6
                            Dim peter5 As Integer = 6
                        Case 7
                            Dim peter5 As Integer = 7
                        Case 8
                            Dim peter5 As Integer = 8
                        Case 9
                            Dim peter5 As Integer = 9
                        Case 10
                            Dim peter5 As Integer = 10
                        Case 11
                            Dim peter1 As Integer = 11
                        Case 12
                            Dim peter2 As Integer = 12
                        Case 13
                            Dim peter3 As Integer = 13
                        Case 14
                            Dim peter4 As Integer = 14
                        Case 15
                            Dim peter15 As Integer = 15
                        Case 16
                            Dim peter16 As Integer = 16
                        Case 17
                            Dim peter17 As Integer = 17
                        Case 18
                            Dim peter18 As Integer = 18
                        Case 19
                            Dim peter19 As Integer = 19
                        Case 20
                            Dim peter20 As Integer = 20
                        Case Else
                            Dim peter99 As Integer = 99
                    End Select

                    Dim centerMCR As Double = MCRuncalibMass + offsetMCR

                    GetIntegratedPeakIntensityAtMass( _
                      aRawFileRef, _
                      centerMCR, _
                      aDeltaMass, anInRawDataFileHandling, aFixBackground, _
                      someQuantResult.intensity5, _
                      someQuantResult.centroidMCR2, someQuantResult.maxSignal, _
                      someQuantResult.MSpeakArea3, someQuantResult.validResult)

                    'Changed PM_QUANT_AUTO_CENTERING 2006-11-12
                    Dim centroidDiffFromCenter As Double = _
                      someQuantResult.centroidMCR2 - centerMCR

                    'For breakpoints. Is identical zero if there
                    'are no datapoints...
                    '
                    'Or if the adjustment was so small that we use exactly
                    'the same datapoints...
                    '
                    If centroidDiffFromCenter <> 0.0 Then
                        Dim peter10 As Integer = 10 '
                    Else
                        If iterations > 1 Then
                            Dim peter2 As Integer = 2 'Same datapoints.
                        Else
                            Dim peter1 As Integer = 1 'No data points.
                        End If
                    End If

                    Dim relDiff As Double = centroidDiffFromCenter / aDeltaMass

                    '1.0 for a the border. 0.0 for centered
                    Dim absRelDiff As Double = Math.Abs(relDiff)

                    Dim centered As Boolean = absRelDiff < 0.05
                    If Not autoCenter Or centered Then
                        end2 = True
                    Else
                        'Guess that the found centroid will be close
                        'to the real peak center.
                        'This is not the case if the quant window did
                        'not cover the peak max, but at least we will
                        'get closer.
                        offsetMCR += centroidDiffFromCenter
                    End If
                End While 'Auto-centering of quant integration interval loop.

                'Changed PM_QUANT_ISOTOPES 2008-01-31
                Dim quantIsotopes As Boolean = True
                If quantIsotopes Then

                    Dim monoCenterMCR As Double = MCRuncalibMass + offsetMCR
                    Dim diff1 As Double = MSconstants.C12_C13_DIFF / aCharge
                    Dim centerMCRquant As Double = monoCenterMCR + diff1

                    'Also quantitate some isotopes. The number depends on some
                    'rules, e.g. for not coliding with the next SILAC dish's
                    'isotope cluster, including the pre-peak.

                    Dim isotopesToQuantify As Integer = 1 'For now: only the
                    '  first isotope.

                    If someQuantResult.MSpeakArea3 < 0.0000001 Then
                        isotopesToQuantify = 0 'Don't do it if there is no
                        '  signal for mono. Otherwise we could pick up some
                        '  peaks by chance.
                    Else
                        Dim peter2 As Integer = 2 'Some mono signal.
                    End If

                    'Double add for mono????
                    'For breakpoints.
                    If someQuantResult.MSpeakArea3 > 0.2 Then
                        Dim peter2 As Integer = 2
                    End If


                    'Note: as we have already added one "diff1" above the zero index is
                    '      for the first isotope (and the not monoisotopic peak).

                    Dim lastIndex As Integer = isotopesToQuantify - 1
                    Dim j As Integer
                    For j = 0 To lastIndex 'Perhaps replace with a ***while*** loop
                        '  if the number of isotopes depends on the quant
                        '  result (e.g. if result diviate too much from the expected
                        '  -theoretical value from either averagine or actual value
                        '  from current peptide).

                        Dim intensity5 As Double
                        Dim centroidMCR As Double
                        Dim maxSignal As Double
                        Dim MSpeakArea3 As Double
                        Dim validResult2 As Boolean

                        GetIntegratedPeakIntensityAtMass( _
                          aRawFileRef, _
                          centerMCRquant, _
                          aDeltaMass, anInRawDataFileHandling, aFixBackground, _
                          intensity5, _
                          centroidMCR, maxSignal, _
                          MSpeakArea3, validResult2)

                        'For breakpoints.
                        If maxSignal > 0.1 Then
                            Dim peter1 As Integer = 1
                        End If

                        someQuantResult.intensity5 += intensity5
                        'someQuantResult.centroidMZ  Ignore this, use the mono MCR.
                        '  We could perhaps make some sanity check? - with some
                        '  overlapping peak the centroid will be shifted from
                        '  the expected.
                        If maxSignal > someQuantResult.maxSignal Then
                            someQuantResult.maxSignal = maxSignal
                        End If
                        someQuantResult.MSpeakArea3 += MSpeakArea3

                        'Changed PM_QUANT_ASSERT_JH 2008-02-05
                        'someQuantResult.validResult = _
                        '  someQuantResult.validResult AndAlso validResult2
                        '
                        'Note: we don't let the definedness of isotopes influence
                        '      the overall definedness (this we chose only to come 
                        '      from the monoisotopic peak). 
                        '
                        '      This also prevents an assert in addToLCprofiles(), 
                        '      "... Quantitation offsets are inconsistent: ..."

                        centerMCRquant += diff1
                    Next j 'Through quantitation for a number of isotopes.

                    someQuantResult.isotopesQuantified2 = isotopesToQuantify
                End If

                validResult = validResult AndAlso someQuantResult.validResult

                Trace.Assert(someQuantResult.centroidMCR2 > 0.0, _
                  "PIL ASSERT. someQuantResult.centroidMCR2 > 0.0, SILAC dish " & _
                  SILACnumber & ". Value: " & _
                  someQuantResult.centroidMCR2)

                'Changed PM_PERFILE_RECALIBRATION 2007-11-16
                Dim tag As Integer = aRawFileRef 'Note: using
                '  calibration constants for current raw file. This is primarily what
                '  we want, but there is no option to .

                Dim calib2 As Double = _
                  anInCalibration.uncalib2calib(someQuantResult.centroidMCR2, tag)

                'Changed PM_REFACTOR 2008-05-20
                'Dim charge2 As Integer = aCharge
                'Dim np2 As Double = charge2 * MSconstants.PROTON_MASS
                'someQuantResult.calibratedNeutralMass = _
                '  charge2 * calib2 - np2
                someQuantResult.calibratedNeutralMass = _
                  PILmassCalc.chargeTransform(calib2, aCharge, 0)

                'Changed PM_QUANT_AUTO_CENTERING 2006-11-13
                someQuantResult.offsetMCR8 = offsetMCR 'Note: is currently 
                '  the same for all dishes (for a single MS spectrum); we
                '  find the shift for wild and use the same adjustment 
                '  for the other dishes.

                aQuantResult.Add(someQuantResult)

                SILACnumber += 1
                isWildDish = False
            Next 'Through aQuantResult

            anOutOffsetMCR = offsetMCR

        End Sub 'CalcParametersForCurrentMS


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Function coreLowerAndHigherMZ( _
          ByVal aMeasuredMCR As Double, _
          ByVal aSILACindex As Integer, _
          ByRef anInMassDiffs2 As Generic.List(Of Double), _
          ByVal aCharge As Integer) _
          As Generic.List(Of derivedQuantInfoStructure)

            'Changed PM_TYPESAFE 2006-11-06
            'Old:
            '  Return value
            '    As ArrayList
            '  ByRef anInMassDiffs As ArrayList

            'Is anInQuantMode needed?
            '            ByRef anInQuantMode As _
            '              generalisedQuantModeStructure, _
            '            ByVal anInMassDiffForUsedDish As Double, _

            'Dim toReturn As ArrayList = New ArrayList
            Dim toReturn2 As Generic.List(Of derivedQuantInfoStructure) = _
              New Generic.List(Of derivedQuantInfoStructure)

            'Trace.Assert( _
            '  anInMCRmassDiffs.Count = _
            '    anInQuantMode.dishes_StartingFromDish2.Count, _
            '  "PIL ASSERT. <message>.")

            If aSILACindex <> 0 Then
                Dim peter0 As Integer = 0
            End If

            'Changed PM_REFACTOR 2008-05-20
            'Dim measuredMass As Double = _
            '  (aMeasuredMCR - MSconstants.PROTON_MASS) * aCharge
            Dim measuredMass As Double = _
              PILmassCalc.chargeTransform(aMeasuredMCR, aCharge, 0)


            Dim massDiffForUsedDish As Double = anInMassDiffs2(aSILACindex)

            Dim someMassDiff As Double
            For Each someMassDiff In anInMassDiffs2

                If someMassDiff > 21.0 Then
                    Dim peter21 As Integer = 21
                End If

                'E.g. xyz
                Dim massOffset As Double = _
                  someMassDiff - massDiffForUsedDish

                Dim mass As Double = measuredMass + massOffset

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

                Dim MCRoffset As Double = MCR - aMeasuredMCR

                Dim someQuantVal As derivedQuantInfoStructure
                someQuantVal.MCRuncalib = MCR
                someQuantVal.MCRuncalibDiff = MCRoffset

                'Changed PM_REFACTOR 2006-10-03
                'someQuantVal.calibratedMCR = -10.0 'Not known at this time...

                toReturn2.Add(someQuantVal)
            Next
            Return toReturn2
        End Function 'coreLowerAndHigherMZ


        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        '  Argument aDifferentMods: a negative value encodes that the
        '                           highest mass modification has been used....
        '  Argument aMZ_Diff2:      if it is negative (not used):
        '                             then the quantitation mode is such that a simple
        '                             binary mass modification suffice.
        '                           if it is positive:
        '                             three masses must be checked (returned from this
        '                             function)
        Public Shared Sub coreLowerAndHigherMZ_old( _
          ByVal aMeasuredMCR As Double, ByVal aModCount As Integer, _
          ByVal aMZ_Diff1 As Double, ByVal aMZ_Diff2 As Double, _
          ByRef aLowerMCR As Double, ByRef aHigherMCR As Double, _
          ByRef aEvenHigherMCR As Double, _
          ByRef aDifferentMods As Integer)

            aEvenHigherMCR = -1.0E+29
            If aMZ_Diff2 < 0 Then 'Means that diff2 is not used.
                If aModCount = 0 Then
                    'No modification
                    aLowerMCR = aMeasuredMCR
                    aHigherMCR = aMeasuredMCR + aMZ_Diff1
                Else
                    'All R's are 6 Da heavier.
                    aLowerMCR = aMeasuredMCR - aMZ_Diff1
                    aHigherMCR = aMeasuredMCR
                    aDifferentMods = aDifferentMods + 1
                End If
            Else
                'Changed PM_TRIPLE_ENCODING 2003-04-07
                'We have three different scenarios. Mascot has identified:
                '  1. No modifications
                '  2. The middle mass modification
                '  3. The high mass modification

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

                'About 4.0 Da for ArgC13 triple encoding
                Dim midHighDiff As Double = aMZ_Diff2 - aMZ_Diff1

                If aModCount < 0 Then
                    'Highest mass modification is the base, e.g. ArgC13, +10 Da.

                    aLowerMCR = aMeasuredMCR - aMZ_Diff2
                    aHigherMCR = aMeasuredMCR - midHighDiff
                    aEvenHigherMCR = aMeasuredMCR
                Else
                    If aModCount = 0 Then
                        'No modification
                        aLowerMCR = aMeasuredMCR
                        aHigherMCR = aMeasuredMCR + aMZ_Diff1
                        aEvenHigherMCR = aMeasuredMCR + aMZ_Diff2
                    Else
                        'The middle modification is the base
                        aLowerMCR = aMeasuredMCR - aMZ_Diff1
                        aHigherMCR = aMeasuredMCR
                        aEvenHigherMCR = aMeasuredMCR + midHighDiff

                        '??
                        aDifferentMods = aDifferentMods + 1
                    End If
                End If
            End If
        End Sub 'coreLowerAndHigherMZ_old()


        'Changed PM_QUANTGENERAL_PREPARATION 2006-07-14. Not used.
        ' 'Changed PM_SEQUENCE_DEPENDENT_QUANTMASSDIFF 2004-07-07
        ' '****************************************************************************
        ' '*    <placeholder for header>                                              *
        ' '****************************************************************************
        ' Public Shared Sub addMassDiffItem( _
        '   ByRef anOutDiffList As ArrayList, _
        '   ByVal anAA As String, ByVal aMassDiff As Double)
        ' 
        '     Dim AAmassDiff As AAmassDiffStructure
        '     AAmassDiff.AA = anAA
        '     AAmassDiff.diffFromBase = aMassDiff
        ' 
        '     anOutDiffList.Add(AAmassDiff)
        ' End Sub 'addMassDiffItem


        'Changed PM_GENERALISED_QUANT_MODE 2003-12-08
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '*  aInPepModList: type is quantModCount                                    *
        '*                                                                          *
        '*                                                                          *
        '****************************************************************************
        Private Shared Function findCountForModification( _
          ByRef aInPepModList2 As Generic.List(Of modificationCountStruct), _
          ByVal aQuantModificationID As Integer) _
          As Integer

            'Old:
            '  ByRef aInPepModList As ArrayList

            Dim toReturn As Integer = 0 'This is the default if the list is
            '  empty, Nothing or does not contain the modification searched for.

            Dim quantModCountItem As modificationCountStruct

            If aInPepModList2 Is Nothing Then
                Dim peter9 As Integer = 9
            Else
                For Each quantModCountItem In aInPepModList2
                    If quantModCountItem.quantModificationID = aQuantModificationID Then
                        toReturn = quantModCountItem.count3
                        Exit For
                    End If
                Next
            End If

            'Changed PM_GENERALISED_QUANT_MODE 2003-12-09
            Trace.Assert(toReturn >= 0, _
              "PIL ASSERT. Negative return value in findCountForModification.")

            Return toReturn
        End Function 'findCountForModification


        'Changed PM_REFACTOR 2004-07-07
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Function countForAA( _
          ByRef anInSeq As String, ByRef anAAs As String, _
          ByVal aStartPos0 As Integer, ByVal anEndPos0 As Integer) _
          As Integer

            Dim toReturn As Integer = 0

            If True Then
                Dim lastIndex4 As Integer = anInSeq.Length - 1
                Trace.Assert(aStartPos0 >= 0 AndAlso aStartPos0 <= lastIndex4, _
                  "PIL ASSERT. In countForAA(); aStartPos0 is out of range: " & _
                  aStartPos0 & ".")
                Trace.Assert(anEndPos0 >= 0 AndAlso anEndPos0 <= lastIndex4, _
                  "PIL ASSERT. In countForAA(); anEndPos0 is out of range: " & _
                  aStartPos0 & ".")
            End If

            'Changed PM_QUANTGENERAL_PREPARATION 2006-07-14
            'Splitting in two: to keep same performance characteristics as
            'before for single letters, at the expense of some redundancy.
            If anAAs.Length = 1 Then
                Dim j As Integer

                'Changed PM_TERMMOD_IN_QUANTMODES 2008-04-01
                'Dim lastIndex As Integer = anInSeq.Length - 1
                'For j = 0 To lastIndex
                For j = aStartPos0 To anEndPos0

                    Dim ch As String = anInSeq.Chars(j)
                    If ch = anAAs Then
                        toReturn += 1
                    End If
                Next
            Else
                'New, for new quant generalisation. E.g. for N15 and
                'terminal modifications.
                'Allow more than one amino acid letter in anAA.

                Dim n As Integer

                Dim lastIndex3 As Integer = anAAs.Length - 1
                For n = 0 To lastIndex3

                    Dim someAA As String = anAAs(n)

                    Dim j As Integer

                    'Changed PM_TERMMOD_IN_QUANTMODES 2008-04-01
                    'Dim lastIndex As Integer = anInSeq.Length - 1
                    For j = aStartPos0 To anEndPos0
                        Dim ch As String = anInSeq.Chars(j)
                        If ch = someAA Then 'What if anAA is longer than one?????
                            toReturn += 1
                        End If
                    Next j
                Next n
            End If
            Return toReturn
        End Function 'countForAA


        'Changed PM_SEQUENCE_DEPENDENT_QUANTMASSDIFF 2004-07-07
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Sub findNeutralMassDifference( _
          ByRef anInPeptideSequence As String, _
          ByRef anInMassesList As _
            Generic.List(Of Generic.List(Of quantitation.AAsetStruct)), _
          ByRef anOutNeutralMassDifference As Double, _
          ByRef anOutAACount As Integer)
            'Old:
            '  ByRef anInDiffList As ArrayList, _

            anOutAACount = 0
            anOutNeutralMassDifference = 0.0

            Dim pepLen As Integer = anInPeptideSequence.Length()

            'Changed PM_QUANTGENERAL_PREPARATION 2006-07-14
            ' Dim lastIndex As Integer = anInDiffList.Count - 1
            ' Dim j As Integer
            ' For j = 0 To lastIndex
            ' 
            '     Dim curAAinfo As AAmassDiffStructure = _
            '       ...(anInDiffList(j), _
            '         AAmassDiffStructure)
            ' 
            '     Dim AAcount As Integer = _
            '       countForAA(anInPeptideSequence, curAAinfo.AA)
            '     Dim massDiff As Double = curAAinfo.diffFromBase * AAcount
            ' 
            '     anOutNeutralMassDifference += massDiff
            '     anOutAACount += AAcount
            ' Next j
            Dim someModItem As Generic.List(Of AAsetStruct)
            'Outer loop: for each modification
            For Each someModItem In anInMassesList

                Dim allPositions As Boolean
                Dim startPos0 As Integer = -1 'Flag for below.
                Dim endPos0 As Integer 'Just in case.

                'Inner loop: for each AA set (usually only one, but 4 for N15).
                Dim someAAset As AAsetStruct
                For Each someAAset In someModItem

                    'aasdasd() 'Convert INTERNAL_startPosition3,
                    '  INTERNAL_endPosition3 and sequence to zero based
                    '  indexes, as elsewhere. There are some helper functions.

                    If startPos0 = -1 Then '-1 is a flag - we only use the
                        '  first item in the someModItem list. It is the only
                        '  item for which the INTERNAL fields are defined.

                        Dim maxMods As Integer

                        PILpeptide.findPositionsEtc( _
                          someAAset.INTERNAL_startPosition3, _
                          someAAset.INTERNAL_endPosition3, pepLen, _
                          allPositions, startPos0, endPos0, maxMods)
                    Else
                        Dim peter2 As Integer = 2 'E.g. for N15
                    End If

                    'Changed PM_TERMMOD_IN_QUANTMODES 2008-04-01


                    Dim AAcount As Integer = _
                      countForAA(anInPeptideSequence, someAAset.AAs, startPos0, endPos0)



                    Dim massDiff As Double = someAAset.diffFromBase3 * AAcount

                    If someAAset.INTERNAL_endPosition3 = 1 Then
                        Dim peter1 As Integer = 1
                    End If

                    'Changed PM_TERMMOD_FRAGMENTMASS_TROUBLE_MARKER 2007-09-14
                    'What about peptide modification dependent masses, e.g.
                    'terminal modifications?????
                    'Using someAAset.INTERNAL_startPosition3 and
                    'someAAset.INTERNAL_endPosition3.

                    anOutNeutralMassDifference += massDiff
                    anOutAACount += AAcount
                Next
            Next
        End Sub 'findNeutralMassDifference


        'Changed PM_REFACTOR_INSERT_NATIVEPEPTIDE 2003-10-15
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '*                                                                          *
        '*    Note: despite the name preparePeptideForQuantitation() is also        *
        '*          called during parsing!!                                         *                                                                     *
        '*                                                                          *
        '*      anInQuantModeStruct: the quantitation mode that is used (e.g.       *
        '*        selected by the user).                                            *
        '*                                                                          *
        '*      anInQuantitationModes: access to the quantitation modes             *
        '*        that are defined (by an external file).                           *
        '*                                                                          *
        '****************************************************************************
        Public Shared Function preparePeptideForQuantitation( _
          ByRef anInOutPept As PeptideHitStructure, _
          ByRef anInQuantModeStruct As generalisedQuantModeStructure, _
          ByRef anInOutMultModCounter As multModCounterStructure, _
          ByRef anOutInvalidated As Boolean) _
          As PeptideHitStructure

            'ByRef anInOutPeptides As massSpectrometryBase.PILpeptides, _
            'ByRef anInPeptideToken As Integer, _
            '          ByVal anA As Double, ByVal aB As Double, _

            'Changed PM_EVENMORE_GENERALISED_QUANTMODES 2005-04-08
            'Old parameter:
            '          ByRef anInQuantValues As quantValuesStructure, _
            '          ByRef anInQuantitationModes As QuantitationModes_moreGeneral, _

            'Note: this function is also used during ***parsing*** of
            '      the Mascot result file!!

            Dim doInvalidatePeptide As Boolean = False

            anInOutPept.someAAsMatchingTheFilter = False

            anInOutPept.SILACdishIndex = 0

            'Changed PM_REFACTOR 2006-10-04. No! - we want to reuse previous
            '  results, if available.
            'anInOutPept.quantValues = Nothing   

            Dim massDiffs2 As Generic.List(Of Double) = New Generic.List(Of Double)
            massDiffs2.Add(0.0)
            Dim massDiffForUsedDish As Double = 0.0

            Dim modificationsForADish As Boolean = False

            Dim modsPresent As Integer = 0
            Dim AAcountForMatchingDish As Integer = 0

            Dim dishIndex As Integer = 0

            ' 'Changed PM_HYSTAG_IS_BACK 2005-06-23
            ' 'Probably not needed...
            ' If False Then
            '     Dim baseDish As dishSILACStructure
            '     Dim raisedBase As Boolean = False
            '     Dim baseMassOffset As Double = 0.0
            '     Dim baseDishIndex As Integer = anInQuantModeStruct.baseModification - 1 'Some check of negative value?
            '     If baseDishIndex <= 0 Then
            '         'Base dish is not represented in our data structures.
            '     Else
            '         baseDish = _
            '           ...(anInQuantModeStruct.dishes_StartingFromDish2( _
            '             baseDishIndex), _
            '               dishSILACStructure)
            '         raisedBase = True
            '         'Note: we can not compute BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
            '     End If
            ' End If

            Trace.Assert( _
              Not anInQuantModeStruct.dishes_StartingFromDish2 Is Nothing, _
              "PIL ASSERT. anInQuantModeStruct.dishes_StartingFromDish2 Is Nothing.")
            Dim someDish As dishSILACStructure
            For Each someDish In anInQuantModeStruct.dishes_StartingFromDish2

                Dim modsInThisDish As Boolean = False
                Dim dishModsPresent As Integer = 0

                Dim someModCode As Integer
                For Each someModCode In someDish.modificationsForSILAC
                    Dim count As Integer = _
                      FindLCpeaks.findCountForModification( _
                        anInOutPept.modHits2, someModCode)

                    If count > 0 Then
                        modsInThisDish = True
                    Else
                        Dim peter1 As Integer = 1
                    End If
                    dishModsPresent += count
                Next

                'Changed PM_GENERALISED_QUANTMODES_OBJECTEXCEPTION 2005-06-13. To
                '  detect this problem in the future...
                Dim INTERNALCount As Integer = 0
                If Not someDish.INTERNAL_modCodes Is Nothing Then
                    INTERNALCount = someDish.INTERNAL_modCodes.Count
                End If
                Dim dishCount As Integer = someDish.modificationsForSILAC.Count

                Trace.Assert(dishCount = INTERNALCount, _
                  "PIL ASSERT. Content of field INTERNAL_modCodes is inconsistent..... " & _
                  "Size of INTERNALCount: " & _
                  INTERNALCount & ". Expected value: " & dishCount & ".")
                modsPresent += dishModsPresent

                '  Modification from Mascot correspond to the number of amino acids
                '  for the given modification.
                Dim someMassDifference As Double = -10.0
                Dim someAAcount As Integer = 0
                FindLCpeaks.findNeutralMassDifference( _
                  anInOutPept.AASequence, someDish.INTERNAL_modCodes, _
                  someMassDifference, someAAcount)
                If someAAcount > 0 Then
                    anInOutPept.someAAsMatchingTheFilter = True
                Else
                    Dim peter0 As Integer = 0
                End If

                If modsInThisDish Then
                    If modificationsForADish Then
                        'This means that there are modifications for quantitation
                        'in this peptide that matches in more than one dish. In this 
                        'case we must reject the peptide....

                        doInvalidatePeptide = True
                    End If
                    modificationsForADish = True

                    'If all amino acids are modified according to the 
                    'current quantitation then this is also the number of
                    'affected amino acids.
                    anInOutPept.SILACdishIndex = dishIndex + 1
                    massDiffForUsedDish = someMassDifference
                End If

                'Dim liftedBase As Boolean = anInQuantModeStruct.baseModification > 0
                If dishModsPresent > 0 Then  'Second condition is only
                    'valid for when basemod is 1, e.g. HysTag. It is not valid
                    'for more complicated stuff... 

                    AAcountForMatchingDish = someAAcount

                    'For a particular dish the amino acids that can be modified
                    'should all be modified (unless none are modified).
                    'Dim unmodifiedForLifted As Boolean = liftedBase And someAAcount = 0
                    If someAAcount <> dishModsPresent Then
                        doInvalidatePeptide = True
                    End If
                End If
                massDiffs2.Add(someMassDifference)
                'Dim MCRdiff As Double = someMassDifference / anInOutPept.charge

                If someAAcount > 1 Then
                    If dishModsPresent > 0 Then
                        Dim peter10 As Integer = 10
                        If Not doInvalidatePeptide Then
                            Dim peter9 As Integer = 9
                        End If
                    End If
                End If

                dishIndex += 1
            Next 'For each SILAC dish (except the first one - special
            '  code to account for that...)

            anInOutMultModCounter.totalPeptides += 1
            If modsPresent > 0 Then
                anInOutMultModCounter.peptidesWithModificationForQuantMode += 1
                Dim matchingAAmodifiedCount As Boolean = _
                   modsPresent = AAcountForMatchingDish

                If modsPresent >= 2 Then
                    If modsPresent >= 3 Then
                        Dim peter3 As Integer = 3
                    End If
                End If

                If matchingAAmodifiedCount Then
                    'Nothing to do
                    Dim peter7 As Integer = 7
                Else
                    If Not _
                        anInQuantModeStruct.dishes_StartingFromDish2 Is Nothing AndAlso _
                      anInQuantModeStruct.dishes_StartingFromDish2.Count <> 0 Then
                        doInvalidatePeptide = True
                    Else
                        Dim peter80 As Integer = 80
                    End If
                End If
            End If

            If doInvalidatePeptide Then
                anInOutMultModCounter.nonMatchingAAsToModificationCountFromMascot += 1

                'Store the query number for the ***first*** we encounter. For 
                '  reporting.
                If anInOutMultModCounter.sampleQueryNumberForNonMatchingAAs <= 0 Then
                    anInOutMultModCounter.sampleQueryNumberForNonMatchingAAs = _
                      anInOutPept.queryNumber
                End If

                helper.invalidatePeptide(anInOutPept)
            Else

                'Compute generalised values, instead of: lowerMZuncalib, higherMZuncalib,
                '  evenHigherMZuncalib.
                'Stored in peptide field. The 3 fields are converted into a list.

                'coreLowerAndHigherMZ(anInOutPept.measuredMZ, modsPresent, _
                '  theMZ_Diff1, theMZ_Diff2, _
                '  lowerMZ, higherMZ, evenHigherMZ, _
                '  dummy)

                'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB

                'Changed PM_HYSTAG_IS_BACK 2005-06-23
                If True Then 'For HysTag, ICAT, etc.
                    'Check for index out of bounds (and fail silently by setting base mod to 0) ?
                    Dim idxBase As Integer = anInQuantModeStruct.baseModification
                    Dim massOffset As Double = massDiffs2(idxBase)

                    'To avoid this changing of the arraylist above we could start with
                    'a mass shift of 0.0 and then change it when we get to process the
                    'dish corresponding to ".baseModification"

                    Dim lastIndex As Integer = massDiffs2.Count - 1
                    Dim j As Integer
                    For j = 0 To lastIndex
                        Dim curVal As Double = massDiffs2(j)
                        Dim newVal As Double = 0.0
                        If j < idxBase Then
                            'Set above.
                        Else
                            newVal = curVal - massOffset
                        End If

                        'This is to avoid allocating more memory than
                        'necessary (and associated garbage collection trouble).
                        If newVal <> curVal Then
                            massDiffs2(j) = newVal
                        End If
                    Next j
                End If

                'Note: as long as we can't change 
                '      quantitation mode after the parse 
                '      there is no need to repeat the 
                '      operations below.

                If anInOutPept.quantValues2 Is Nothing Then
                    'What about recalibration?????????
                    'Is measuredMZ the right value to use?
                    'Will recalibration be applied later?
                    anInOutPept.quantValues2 = _
                      coreLowerAndHigherMZ( _
                        anInOutPept.measuredMCR, _
                        anInOutPept.SILACdishIndex, _
                        massDiffs2, anInOutPept.charge)
                    '  anInQuantModeStruct, 
                    '  massDiffForUsedDish, 

                    ' Put it into coreLowerAndHigherMZ above? (That function
                    ' is only called from one place.
                    '
                    ' Use new peptide field uncalibratedSILACmasses or
                    ' put into new field in the items of peptide
                    ' fields quantValues?

                    Dim charge99 As Integer
                    'Changed PM_REFACTOR 2006-10-01
                    computeSILACmasses( _
                      anInOutPept, _
                      anInOutPept.uncalibratedSILACmasses2, _
                      charge99)
                Else
                    Dim peter53 As Integer = 53 'Already done.
                End If
            End If

            If anInOutPept.modHits2 Is Nothing Then
                'No modifications indicated by Mascot. Use the start defaults.
            Else

            End If

            'Changed PM_MEMORYEFFICIENCY_PARSE 2007-02-19
            anOutInvalidated = doInvalidatePeptide

            Return anInOutPept
        End Function 'preparePeptideForQuantitation.
        '    Note: this function is also used during ***parsing*** of
        '          the Mascot result file!!


        'Changed PM_REFACTOR 2004-02-02
        'This function should probably be moved somewhere else, e.g. to
        'a place where there is knowledge about the fields in a peptide.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Function isExternalQuantitation( _
          ByRef aPept As PeptideHitStructure) _
          As Boolean

            Dim isExternal As Boolean = aPept.retentionTimeEndMinutes < -0.000001
            'Negative value is a flag that we should use an EXTERNALLY specified
            'LC time window.

            Return isExternal
        End Function 'isExternalQuantitation


        'Changed PM_REFACTOR 2004-02-02
        'This function should probably be moved somewhere else, e.g. to
        'a place where there is knowledge about the fields in a peptide.
        '****************************************************************************
        '*    <placeholder for header>                                              *
        '****************************************************************************
        Public Shared Function isInsertedPeptide( _
          ByRef aPept As PeptideHitStructure) _
          As Boolean

            'Changed PM_REFACTOR 2006-08-10
            Dim tol As Double = 0.01
            'Dim isInserted As Boolean = _
            '  aPept.MascotScore > 98.99 And aPept.MascotScore < 99.01
            Dim isInserted As Boolean = _
              utilityStatic.numbersClose( _
                aPept.MascotScore, _
                PILpeptides.FIXED_SCORE_FOR_INSERTED_PEPTIDES, _
                tol)

            If isInserted Then
                Dim peter8 As Integer = 8
            End If
            Return isInserted
        End Function 'isInsertedPeptide


        'Changed PM_REFACTOR 2006-10-03. Not needed anyway...
        ' '****************************************************************************
        ' '*    <placeholder for header>                                              *
        ' '****************************************************************************
        ' Public Shared Function calib3uncalib( _
        '     ByRef anInCalibratedMasses As Generic.List(Of Double), _
        '     ByVal anA As Double, ByVal aB As Double _
        '     ) _
        '     As Generic.List(Of Double)
        ' 
        '     Dim toReturn As Generic.List(Of Double) = New Generic.List(Of Double)
        '     toReturn.Capacity = anInCalibratedMasses.Count
        ' 
        '     Dim calibMass As Double
        '     For Each calibMass In anInCalibratedMasses
        '         Dim uncalibMass As Double = (calibMass - anA) / aB
        '         toReturn.Add(uncalibMass)
        '     Next
        '     Return toReturn
        ' End Function 'calib3uncalib

    End Class 'FindLCpeaks

End Namespace 'massSpectrometryBase


    

    

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