VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
  Persistable = 0  'NotPersistable
  DataBindingBehavior = 0  'vbNone
  DataSourceBehavior  = 0  'vbNone
  MTSTransactionMode  = 0  'NotAnMTSObject
END
Attribute VB_Name = "ProcessClass"
Attribute VB_GlobalNameSpace = True
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True
' Class:    ProcessClass
' Filename: AutoQuant.cls

' This file contains the "ProcessClass" object used by the "AutoQuant" Analyst
' script. Note that the name of the _class_ must be "ProcessClass" so that
' Analyst can find it, but the filename is not used by Analyst. This class
' must be part of a Visual Basic "ActiveX DLL" project and the DLL must be
' created using the "Make" item from VB's "File" menu. This resulting DLL
' is the 'script' which is specified from the Analyst's batch editor.

' This particular script takes advantage of the "SampleEnd" notification sent
' by Analyst to create a new results table after the first sample and to add
' all future samples to it. If the quantitation method is not specified in
' the batch editor (although it is recommended that the user do so), an
' "automatic" method which treats all ions as analytes (no internal standards)
' is used. This script also monitors any internal standard peaks: if a
' specified number of IS peaks are missing in consecutive samples it will
' abort the run.

Option Explicit

Dim m_analyst           As Analyst.Application      ' main application object
Dim m_quantDir          As QuantDirector            ' quantitation director
Dim m_resultsTable      As QuantRT                  ' new results table
Dim m_quantMethod       As QuantMethod              ' quant method used by table

Dim m_firstTime         As Boolean                  ' true until SampleEnd called once
Dim m_add               As Boolean                  ' true if we do processing
Dim m_watch             As Boolean                  ' true if we monitor IS
Dim m_numMisses         As Integer                  ' number of missed IS peaks in a row


' This subroutine is called by Analyst at the start of the batch.
Public Sub BatchStart()
    ' Initialise "simple" variables.
    m_firstTime = True
    m_add = False
    m_watch = False
    m_numMisses = 0
    
    ' Initialise these variables...
    Set m_analyst = GetObject(, "Analyst.Application")
    Set m_quantDir = m_analyst.Quantitate
End Sub

' This subroutine is called by Analyst at the end of the batch.
Public Sub BatchEnd()
    ' De-initialize these variables
    Set m_quantMethod = Nothing
    Set m_resultsTable = Nothing
    Set m_quantDir = Nothing
    Set m_analyst = Nothing
End Sub

' This subroutine is called by Analyst at the start of each sample. It's not used and
' could be removed.
Public Sub SampleStart(filename As String, sampleIndex As Integer)
End Sub

' This subroutine is called by Analyst at the end of each sample. "filename" is the
' name of the file containing the sample which has just been acquired and "sampleIndex"
' is the position of the sample in that file.
Public Sub SampleEnd(filename As String, sampleIndex As Integer)
    Dim fwfc            As New FMANWiffFileControl          ' used to get "fwf"
    Dim fwf             As FMANWiffFile                     ' data file object
    Dim batchInfo       As ISampleServer                    ' sample information
    Dim theIntegrator   As New QuantIntegration             ' used to integrate
    Dim analytePeaks    As QuantPeakList                    ' integrated analyte peaks
    Dim isPeaks         As QuantPeakList                    ' integrated IS peaks
    Dim noPeak          As Boolean                          ' true if IS peak not found
    Dim numIS           As Integer                          ' number of IS peaks
    Dim i               As Integer                          ' loop counter
    
    ' If this is the first time SampleEnd() has been called, do initialisation.
    If m_firstTime Then Call DoFirstSample(filename, sampleIndex)
    
    ' Add sample to our results table if needed.
    If m_add Then
        Call m_resultsTable.AddSample(filename, sampleIndex, "Added by script")
    End If
    
    ' If we're monitoring IS peak areas, do so.
    If m_watch Then
        ' Get sample information.
        Set fwf = fwfc.GetWiffFileObject(filename, sampleIndex)
        Set batchInfo = fwf.GetDABSObject(sampleIndex)
    
        ' Skip over "double blank" and "solvent" sample types completely.
        If batchInfo.Type <> 4 And batchInfo.Type <> 5 Then
            ' Calculate areas of ALL peaks in this sample.
            Call theIntegrator.IntegrateAllUsingMethod(filename, sampleIndex, m_quantMethod, analytePeaks, isPeaks)
            
            ' Determine whether or not at least one IS peak is missing from this sample.
            noPeak = False
            numIS = isPeaks.NumPeaks
            For i = 1 To numIS
                If isPeaks.PeakType(i) = INTEGRATION_NO_PEAK Then
                    noPeak = True
                    Exit For
                End If
            Next i
            
            ' Adjust the "number of consecutive missed integrations" variable.
            If noPeak Then
                m_numMisses = m_numMisses + 1
            Else
                m_numMisses = 0
            End If
            
            ' If there are too many consecutive missed integrations, warn the user and abort the run.
            If m_numMisses >= 3 Then
                m_add = False       ' set these so we do no future processing
                m_watch = False
                
                Dim queueDir As QMDirector
                Dim queueMan As QueueManager
                
                ' Get queue manager (from queue director) and get it to stop queue.
                Set queueDir = m_analyst.Queue
                Set queueMan = queueDir.GetIUnknownQMan(False)
                queueMan.StopQueue
                Set queueMan = Nothing
                Set queueDir = Nothing
                
                MsgBox ("IS Peak not found for" + Str(m_numMisses) + " consecutive samples: Aborting run.")
            End If
        End If
        
        Set analytePeaks = Nothing
        Set isPeaks = Nothing
        Set batchInfo = Nothing
        Set fwf = Nothing
    End If
    
    Set fwfc = Nothing
    Set theIntegrator = Nothing
End Sub

' DoFirstSample
'
' This subroutine initialises this object based on the provided sample. It will:
' (1) create a new "automatic" method if a method was not specified in the
' batch; (2) create a new results table and (3) set "m_watch" true to monitor
' internal standard areas if needed.
'
'   filename:       [in]  name of data file
'   sampleIndex:    [in]  index of sample in file
'
'
Sub DoFirstSample(filename As String, sampleIndex As Integer)
    Dim fwfc            As New FMANWiffFileControl          ' used to get "fwf"
    Dim fwf             As FMANWiffFile                     ' data file object
    Dim batchInfo       As ISampleServer                    ' sample information
    Dim methodName      As String                           ' name of quant method
    Dim contents        As IRTContents                      ' used to get quant method object
    
    m_firstTime = False     ' prevent this subroutine being called again
        
    ' Get method name...
    Set fwf = fwfc.GetWiffFileObject(filename, sampleIndex)
    Set batchInfo = fwf.GetDABSObject(sampleIndex)
    methodName = batchInfo.ProcessMethod
    
    ' Create an automatic method if no method was specified.
    If methodName = "" Or StrComp(methodName, "none", 1) = 0 Then
        methodName = CreateAutoMethod(filename, sampleIndex)
    End If
    
    ' Create results table.
    m_analyst.Mode = ntQuantitate
    Call m_quantDir.NewTable(methodName, "")    ' use "Default" settings
    Set m_resultsTable = m_analyst.ActiveControl
    
    ' Determine whether or not to monitor IS areas.
    Set contents = m_resultsTable
    Set m_quantMethod = contents.GetGlobalQuanMethod
    If m_quantMethod.NumISPeaks > 0 Then m_watch = True
    
    m_add = True    ' we DO want to add future samples to table
    
    Set contents = Nothing
    Set batchInfo = Nothing
    Set fwf = Nothing
    Set fwfc = Nothing
End Sub

' CreateAutoMethod
'
' This function creates a new automatic method using the provided sample as the
' "typical" sample. It saves the method to a temporary file and returns the name
' of the method.
'
'   filename:       [in]  name of data file
'   sampleIndex:    [in]  index of sample in file
'
'   return value: the name of the new method
'
Function CreateAutoMethod(filename As String, sampleIndex As Integer) As String
    Dim theMethod       As New QuantMethod                  ' new automatic method
    Dim theExtractor    As New ExtractMethodPeakData        ' used to initialise method
    Dim theName         As String                           ' name of new method
    
    ' Create new automatic method using default values for bunching factor, etc.
    Call theExtractor.BuildAutoMethodUsingDefaults(filename, sampleIndex, theMethod)
    
    ' Save method to temporary file.
    theName = Environ("TEMP") + "\Temp Method.qmf"
    Call theMethod.SaveToFile(theName)
    
    CreateAutoMethod = theName
    
    Set theExtractor = Nothing
    Set theMethod = Nothing
End Function
