/* BEGIN software license
 *
 * msXpertSuite - mass spectrometry software suite
 * -----------------------------------------------
 * Copyright(C) 2009,...,2018 Filippo Rusconi
 *
 * http://www.msxpertsuite.org
 *
 * This file is part of the msXpertSuite project.
 *
 * The msXpertSuite project is the successor of the massXpert project. This
 * project now includes various independent modules:
 *
 * - massXpert, model polymer chemistries and simulate mass spectrometric data;
 * - mineXpert, a powerful TIC chromatogram/mass spectrum viewer/miner;
 *
 * This program 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 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * END software license
 */


////////////////////////////// Qt includes
#include <QStringList>
#include <QFile>
#include <QRegularExpression>
#include <QDebug>
#include <QVector>
#include <QCoreApplication>

#include <qmath.h>

////////////////////////////// local includes
#include <minexpert/nongui/MassSpecDataFileLoaderMs1.hpp>
#include <minexpert/nongui/globals.hpp>


namespace msXpSmineXpert
{

MassSpecDataFileLoaderMs1::MassSpecDataFileLoaderMs1()
{
}


MassSpecDataFileLoaderMs1::MassSpecDataFileLoaderMs1(const QString &fileName)
  : MassSpecDataFileLoader{fileName}
{
}


MassSpecDataFileLoaderMs1::~MassSpecDataFileLoaderMs1()
{
}


QString
MassSpecDataFileLoaderMs1::formatDescription() const
{
  QString description = QString(
    "The Ms1 file format stores survey scans mass data.\n"
    "The format is text-based, tabulated, and has the following schema:\n"
    "H	CreationDate Mon Mar 27 15:11:08 2017\n"
    "H	Extractor	ProteoWizard\n"
    "H	Extractor version	CompassXtract\n"
    "H	Source file	Analysis.baf\n"
    "S	1	1\n"
    "I	RTime	0.01915\n"
    "I	BPI	31484\n"
    "I	TIC	8254369\n"
    "694.5166 133\n"
    "and all the other peak data for that scan\n"
    "S	2	2\n"
    "I	RTime	0.03588333\n"
    "I	BPI	31493\n"
    "I	TIC	7780566\n"
    "694.5166 186\n"
    "and all the other peak data for that scan.\n");

  return description;
}


void
MassSpecDataFileLoaderMs1::cancelOperation()
{
  m_isOperationCancelled = true;

  qDebug() << __FILE__ << __LINE__ << "MzmlFileParser::cancelOperation";
}


int
MassSpecDataFileLoaderMs1::readSpectrumCount()
{
  // The dx file as produced by Bruker CompassXport has this kind of header:
  //
  // H CreationDate Mon Mar 27 15:11:08 2017
  // H Extractor	ProteoWizard
  // H Extractor version	CompassXtract
  // H Source file	Analysis.baf
  // S 1	1
  // I RTime	0.01915
  // I BPI	31484
  // I TIC	8254369
  // 694.5166 133
  // ...
  // and so on.

  // Then, for the next spectrum:

  // S 2	2
  // I RTime	0.03588333
  // I BPI	31493
  // I TIC	7780566
  // 694.5166 186
  // ...
  // and so on.

  // So the point here is to parse the whole file and monitor for the ^S <num>
  // <num>
  // line.

  // Reinit the spectrum count.
  m_spectrumCount = 0;

  if(m_fileName.isEmpty())
    {
      qDebug() << __FILE__ << __LINE__ << "fileName is empty";

      return -1;
    }

  QFile file(m_fileName);

  if(!file.open(QFile::ReadOnly | QFile::Text))
    {
      qDebug() << __FILE__ << __LINE__ << "Failed to open file" << m_fileName;

      return -1;
    }

  QRegularExpression scanNumberRegExp("^S\\s+(\\d+)\\s+(\\d+)\\s*$");

  QRegularExpressionMatch match;

  QString errorMsg;

  while(!file.atEnd())
    {
      QString line = file.readLine();

      // Does the line match the page and elution time regexp?
      match = scanNumberRegExp.match(line);

      if(match.hasMatch())
        {
          // qDebug() << __FILE__ << __LINE__
          //<< "line has matched the scan number regular expression.";

          m_spectrumCount++;
        }
    }

  file.close();

  return m_spectrumCount;
}


bool
MassSpecDataFileLoaderMs1::canLoadData(QString fileName)
{
  int LIMIT_PARSED_LINES_COUNT = 15;

  QFile file(fileName);

  if(!file.open(QFile::ReadOnly | QFile::Text))
    {
      qDebug() << __FILE__ << __LINE__ << "Failed to open file" << fileName;

      return false;
    }

  // This is how the file starts with, see the header lines?
  // H	CreationDate Mon Mar 27 15:11:08 2017
  // H	Extractor	ProteoWizard
  // H	Extractor version	CompassXtract
  // H	Source file	Analysis.baf
  // S	1	1
  // I	RTime	0.01915
  // I	BPI	31484
  // I	TIC	8254369
  // 694.5166 133
  // and all the other peaks of the scan.


  QRegularExpression endOfLineRegExp("^\\s+$");
  QRegularExpression massDataRegExp(
    "^(\\d*.?\\d+)\\s(-?\\d*\\.?\\d*[e-]?\\d*)");

  QRegularExpressionMatch regExpMatch;

  QString line;

  int linesRead              = 0;
  bool creationDateLineFound = false;
  bool sourceFileLineFound   = false;
  bool scan1LineFound        = false;
  bool realDataFound         = false;

  while(!file.atEnd() && linesRead < LIMIT_PARSED_LINES_COUNT)
    {
      line = file.readLine();
      ++linesRead;

      // qDebug() << __FILE__ << __LINE__ << "Current ms1 format line:" <<
      // line;

      regExpMatch = massDataRegExp.match(line);

      if(regExpMatch.hasMatch())
        {
          // qDebug() << __FILE__ << __LINE__
          //<< "line has matched real data:" << line;

          realDataFound = true;

          continue;
        }
      else if(line.isEmpty() || endOfLineRegExp.match(line).hasMatch())
        {
          // qDebug() << __FILE__ << __LINE__
          //<< "line is empty or only end of line";

          continue;
        }
      else if(line.startsWith('H'))
        {
          // qDebug() << __FILE__ << __LINE__ << "line starts with 'H'";

          if(line.contains("CreationDate"))
            creationDateLineFound = true;
          else if(line.contains("Source file"))
            sourceFileLineFound = true;
          else
            continue;
        }
      else if(line.startsWith('S'))
        {
          // qDebug() << __FILE__ << __LINE__ << "line starts with 'S'";

          if(line.contains("S\t1"))
            scan1LineFound = true;
          else
            continue;
        }
      else
        {
          continue;
        }
    }

  if(creationDateLineFound && sourceFileLineFound && scan1LineFound &&
     realDataFound)
    return true;

  return false;
}


msXpSlibmass::MassSpectrum *
MassSpecDataFileLoaderMs1::parseSpectrum(QFile *file)
{
  if(file == nullptr)
    qFatal("Fatal error at %s@%d. Program aborted.", __FILE__, __LINE__);

  // The file is a series of paragraphs that start a new spectrum like this:
  //
  // S	473	473
  // I	RTime	7.9157
  // I	BPI	5275
  // I	TIC	4151798
  // 694.5136 191
  // 694.5303 155
  //
  // When we get to this function, we already parsed the TIC line and we thus
  // should be at the first mz i pair.
  //

  // The line is in the format:
  // 694.499324 35.000000
  // note the space that is used as a delimiter.

  msXpSlibmass::MassSpectrum *massSpectrum = new msXpSlibmass::MassSpectrum;

  QRegularExpression realData("(\\d*\\.?\\d*)\\s+(-?\\d*\\.?\\d*e?\\d*)");
  QRegularExpressionMatch match;

  bool ok = false;

  while(!file->atEnd())
    {
      QString line = file->readLine();

      // S <numb> <numb> starts a new paragraph corresponding to a new
      // spectrum. We just need to return the parsed spectrum.

      if(line.contains(QRegularExpression("^S\\t+")))
        {

          // qDebug() << __FILE__ << __LINE__
          //<< "Encountered S * * line. Returning mass spectrum.";

          return massSpectrum;
        }

      match = realData.match(line);

      if(match.hasMatch())
        {
          double mz = match.captured(1).toDouble(&ok);
          if(!ok)
            {
              qDebug() << __FILE__ << __LINE__ << "Failed to convert mz"
                       << match.captured(1) << "to double.";

              delete massSpectrum;
              return nullptr;
            }


          double i = match.captured(2).toDouble(&ok);
          if(!ok)
            {
              qDebug() << __FILE__ << __LINE__ << "Failed to convert i"
                       << match.captured(2) << "to double.";

              delete massSpectrum;
              return nullptr;
            }

          // At this point we know that we have proper mz and i values. Let's
          // process these by creating a mass peak that we can append to the
          // spectrum that we allocated at the beginning of this function.

          msXpSlibmass::DataPoint *massPeak =
            new msXpSlibmass::DataPoint(mz, i);
          massSpectrum->append(massPeak);

          // qDebug() << __FILE__ << __LINE__
          //<< "Appended new mass peak to spectrum:"
          //<< "(" << mz << "," << i << ")";
        }
      else
        {
          qDebug() << __FILE__ << __LINE__ << "line" << line
                   << "does not match. Error?";
        }
    }
  // End of
  // while(!file->atEnd())

  return massSpectrum;
}


int
MassSpecDataFileLoaderMs1::loadData(MassSpecDataSet *massSpecDataSet)
{
  if(massSpecDataSet == nullptr)
    qFatal("Fatal error at %s@%d. Program aborted.", __FILE__, __LINE__);

  // Will set the value to m_spectrumCount only if it has not been set
  // already. The intialization value at instance creation is set to -1.

  if(m_spectrumCount == -1)
    readSpectrumCount();

  // readSpectrumCount() returns -1 on error.
  if(m_spectrumCount == -1)
    return -1;

  // qDebug() << __FILE__ << __LINE__ << "spectrumCount:" << m_spectrumCount;

  QFile file(m_fileName);

  if(!file.open(QFile::ReadOnly | QFile::Text))
    {
      qDebug() << __FILE__ << __LINE__ << "Failed to open file" << m_fileName;

      return -1;
    }

  // Craft the proper regular expression for the mass data:

  QRegularExpression headerRegExp("^H\\s+.+$");
  QRegularExpression scanNumberRegExp("^S\\s+(\\d+)\\s+(\\d+)\\s*$");

  QRegularExpression endOfLineRegExp("^\\s+$");
  QRegularExpression massDataRegExp(
    "^(\\d*.?\\d+)\\s(-?\\d*\\.?\\d*[e-]?\\d*)");
  QRegularExpression retentionTimeRegExp("RTime\\s+(\\d*\\.?\\d*)");
  QRegularExpression ticRegExp("TIC\\s+(\\d+)");

  QRegularExpressionMatch match;

  int spectraRead = 0;
  double rt       = 0.0;
  int scanNumber1 = 0;
  int scanNumber2 = 0;

  bool ok = false;

  // The format of the file is like this at the beginning
  // H	CreationDate Mon Mar 27 15:11:08 2017
  // H	Extractor	ProteoWizard
  // H	Extractor version	CompassXtract
  // H	Source file	Analysis.baf
  // S	1	1
  // I	RTime	0.01915
  // I	BPI	31484
  // I	TIC	8254369
  // 694.5166 133
  // 694.5334 195
  //
  // Then, each spectrum has a header like this and then the data:
  // S	2	2
  // I	RTime	0.03588333
  // I	BPI	31493
  // I	TIC	7780566

  while(!file.atEnd())
    {
      QCoreApplication::processEvents();

      if(m_isOperationCancelled)
        break;

      QString line = file.readLine();

      // qDebug() << __FILE__ << __LINE__ << "line is: " << line;

      // If the line has only a newline character or is empty, go on.
      match = endOfLineRegExp.match(line);
      if(match.hasMatch() || line.isEmpty())
        {
          // qDebug() << __FILE__ << __LINE__
          //<< "matched the end of line or line is empty.";

          continue;
        }

      match = headerRegExp.match(line);
      if(match.hasMatch())
        {
          // Header line

          // qDebug() << __FILE__ << __LINE__ << "Header line.";

          continue;
        }

      match = scanNumberRegExp.match(line);

      if(match.hasMatch())
        {
          scanNumber1 = match.captured(1).toInt(&ok);

          if(!ok)
            {
              qDebug() << __FILE__ << __LINE__ << "Failed to convert"
                       << match.captured(1) << "to double";

              return -1;
            }

          scanNumber2 = match.captured(2).toInt(&ok);

          if(!ok)
            {
              qDebug() << __FILE__ << __LINE__ << "Failed to convert"
                       << match.captured(1) << "to double";

              return -1;
            }

          qDebug() << __FILE__ << __LINE__
                   << "Scan number line found with numbers:" << scanNumber1
                   << "and" << scanNumber2;

          continue;
        }

      if(line.startsWith("I BPI"))
        {

          // qDebug() << __FILE__ << __LINE__ << "Info line (BPI)";

          continue;
        }

      match = retentionTimeRegExp.match(line);

      if(match.hasMatch())
        {
          rt = match.captured(1).toDouble(&ok);

          if(!ok)
            {
              qDebug() << __FILE__ << __LINE__ << "Failed to convert"
                       << match.captured(1) << "to double";

              return -1;
            }

          // qDebug() << __FILE__ << __LINE__ << "rt:" << rt;

          continue;
        }

      match = ticRegExp.match(line);

      if(match.hasMatch())
        {
          match.captured(1).toDouble(&ok);

          if(!ok)
            {
              qDebug() << __FILE__ << __LINE__ << "Failed to convert"
                       << match.captured(1) << "to double";

              return -1;
            }

          // qDebug() << __FILE__ << __LINE__ << "TIC line parsed: " << tic;

          // We know that the TIC line is located right before the spectrum
          // data. Delegate the parsing to another function.

          msXpSlibmass::MassSpectrum *newSpectrum = parseSpectrum(&file);

          if(newSpectrum == nullptr)
            qFatal(
              "Fatal error at %s@%d. Failed to parse spectrum. Program "
              "aborted.",
              __FILE__,
              __LINE__);

          // Do not forget to set that retention time to the spectrum
          // itself !

          newSpectrum->rrt() = rt;

          if(massSpecDataSet->isStreamed())
            {
              // We are reading in streamed mode. This is the chance we
              // have to compute the TIC for the spectrum:

              double newTic = newSpectrum->valSum();

              // Had already another spectrum have the same rt ? If so
              // another TIC was already computed.

              double oldTic = massSpecDataSet->m_ticChromMap.value(rt, qSNaN());

              if(!qIsNaN(oldTic))
                {

                  // A rt by the same value alreay existed, update the
                  // tic value and insert it, that will erase the old
                  // value, because the map is NOT a multimap.

                  newTic += oldTic;
                }

              // And now store the key/value pair for later to use to
              // plot the TIC chromatogram.

              massSpecDataSet->m_ticChromMap.insert(rt, newTic);

              // Now delete the mass spectrum, that we won't use anymore.
              delete newSpectrum;
            }
          else
            {
              massSpecDataSet->appendMassSpectrum(newSpectrum);
              massSpecDataSet->insertRtHash(rt, newSpectrum);
            }

          // At this point we can increment the number of spectra that were
          // effectively read.

          ++spectraRead;
        }
      // End of tic had matched and thus
      // parsed the spectrum and processed it.

      QString msg = QString("Parsed spectrum number %1\n").arg(spectraRead);

      emit updateFeedbackSignal(
        msg, spectraRead, true /* setVisible */, LogType::LOG_TO_BOTH);
    }
  // End of
  // while(!file.atEnd())

  // We may be here because the operation was cancelled. Of course, in that
  // case we have not read all the spectra, but it is not an error, the user
  // knows he has cancelled the operation.

  if(!m_isOperationCancelled)
    {
      if(spectraRead != m_spectrumCount)
        {

          qDebug() << __FILE__ << __LINE__
                   << "The number of parsed spectra does not match the "
                      "previous analysis of the file."
                   << "spectraRead:" << spectraRead
                   << "and m_spectrumCount:" << m_spectrumCount;

          qFatal("Fatal error at %s@%d. Failed to parse file. Program aborted.",
                 __FILE__,
                 __LINE__);
        }

      // Sanity check:
      if(!massSpecDataSet->isStreamed())
        {
          if(massSpecDataSet->m_massSpectra.size() != spectraRead)
            {
              qDebug() << __FILE__ << __LINE__
                       << "The number of parsed spectra does "
                          "not match the previous analysis "
                          "of the file.";


              qFatal(
                "Fatal error at %s@%d. Failed to parse file. Program "
                "aborted.",
                __FILE__,
                __LINE__);
            }
        }
    }

  file.close();

  return spectraRead;
}


int
MassSpecDataFileLoaderMs1::streamedIntegration(const History &history,
                                               QVector<double> *keyVector,
                                               QVector<double> *valVector,
                                               double *intensity)
{
  if(keyVector == Q_NULLPTR && valVector == Q_NULLPTR && intensity == Q_NULLPTR)
    qFatal("Fatal error at %s@%d. Program aborted.", __FILE__, __LINE__);

  if(intensity == Q_NULLPTR)
    {
      if(keyVector == Q_NULLPTR || valVector == Q_NULLPTR)
        qFatal("Fatal error at %s@%d. Program aborted.", __FILE__, __LINE__);
    }
  else
    {
      if(keyVector != Q_NULLPTR || valVector != Q_NULLPTR)
        qFatal("Fatal error at %s@%d. Program aborted.", __FILE__, __LINE__);
    }

  if(!history.isValid())
    {
      qDebug() << __FILE__ << __LINE__
               << "The History is not valid. Returning.";

      return -1;
    }

  // We are asked to compute a mass spectrum on the basis of what is in
  // the history parameter. Let's craft a SQL query string, perform the
  // query and then compute the TIC chromatogram, of which time is the key
  // and count is the value, returned in the keyVector and valVector
  // parameters.

  // At this point, we need to make sure we have all the rt/dt
  // integrations so that we can take them into account while doing the
  // SELECT operations for the database (m_db).

  // RT integration.
  // ===============
  bool rtIntegration = false;
  double rtStart     = -1;
  double rtEnd       = -1;
  rtIntegration      = history.innermostRtRange(&rtStart, &rtEnd);

  if(!rtIntegration)
    qFatal(
      "Fatal error at %s@%d. Cannot integration over RT with no"
      "integration specifications overs RT. Program aborted.",
      __FILE__,
      __LINE__);


  qDebug() << __FILE__ << __LINE__
           << "The integration is asked between RT range [" << rtStart << "-"
           << rtEnd << "]";

  // We need to iterate in the file and interrogate the various
  //##PAGE= T= 1.158000 lines to extract only the spectra matching the
  // integration rt range.

  QFile file(m_fileName);

  if(!file.open(QFile::ReadOnly | QFile::Text))
    {
      qDebug() << __FILE__ << __LINE__ << "Failed to open file" << m_fileName;

      return -1;
    }

  // Craft the proper regular expression for the mass data:

  QRegularExpression headerRegExp("^H\\s+.+$");
  QRegularExpression scanNumberRegExp("^S\\s+(\\d+)\\s+(\\d+)\\s*$");

  QRegularExpression endOfLineRegExp("^\\s+$");
  QRegularExpression massDataRegExp(
    "^(\\d*.?\\d+)\\s(-?\\d*\\.?\\d*[e-]?\\d*)");
  QRegularExpression retentionTimeRegExp("RTime\\s+(\\d*\\.?\\d*)");
  QRegularExpression ticRegExp("TIC\\s+(\\d+)");

  QRegularExpressionMatch match;

  msXpSlibmass::MassSpectrum combinedMassSpectrum;

  int spectraRead = 0;
  double rt       = 0.0;
  int scanNumber1 = 0;
  int scanNumber2 = 0;

  bool ok = false;

  // The format of the file is like this at the beginning
  // H	CreationDate Mon Mar 27 15:11:08 2017
  // H	Extractor	ProteoWizard
  // H	Extractor version	CompassXtract
  // H	Source file	Analysis.baf
  // S	1	1
  // I	RTime	0.01915
  // I	BPI	31484
  // I	TIC	8254369
  // 694.5166 133
  // 694.5334 195
  //
  // Then, each spectrum has a header like this and then the data:
  // S	2	2
  // I	RTime	0.03588333
  // I	BPI	31493
  // I	TIC	7780566

  // Before going on with the actual results parsing, let's setup the
  // feedback routine. Note the min = 0 and max = 0 values because we cannot
  // determine the count of spectra to load. Simply provide a moving
  // feedback.

  QString msgSkeleton = "Computing streamed m/z integration";

  emit updateFeedbackSignal(
    msgSkeleton, 0, true /* setVisible */, LogType::LOG_TO_BOTH);

  while(!file.atEnd())
    {
      if(m_isOperationCancelled)
        break;

      QString line = file.readLine();

      // qDebug() << __FILE__ << __LINE__ << "line is: " << line;

      // If the line has only a newline character or is empty, go on.
      match = endOfLineRegExp.match(line);
      if(match.hasMatch() || line.isEmpty())
        {
          // qDebug() << __FILE__ << __LINE__
          //<< "matched the end of line or line is empty.";

          continue;
        }

      match = headerRegExp.match(line);
      if(match.hasMatch())
        {
          // Header line

          // qDebug() << __FILE__ << __LINE__ << "Header line.";

          continue;
        }

      match = scanNumberRegExp.match(line);

      if(match.hasMatch())
        {
          scanNumber1 = match.captured(1).toInt(&ok);

          if(!ok)
            {
              qDebug() << __FILE__ << __LINE__ << "Failed to convert"
                       << match.captured(1) << "to double";

              return -1;
            }

          scanNumber2 = match.captured(2).toInt(&ok);

          if(!ok)
            {
              qDebug() << __FILE__ << __LINE__ << "Failed to convert"
                       << match.captured(1) << "to double";

              return -1;
            }

          qDebug() << __FILE__ << __LINE__
                   << "Scan number line found with numbers:" << scanNumber1
                   << "and" << scanNumber2;

          continue;
        }

      if(line.startsWith("I BPI"))
        {

          // qDebug() << __FILE__ << __LINE__ << "Info line (BPI)";

          continue;
        }

      match = retentionTimeRegExp.match(line);

      if(match.hasMatch())
        {
          rt = match.captured(1).toDouble(&ok);

          if(!ok)
            {
              qDebug() << __FILE__ << __LINE__ << "Failed to convert"
                       << match.captured(1) << "to double";

              return -1;
            }

          // qDebug() << __FILE__ << __LINE__ << "rt:" << rt;

          if(rt < rtStart)
            continue;
          if(rt > rtEnd)
            break;
        }

      // At this point we know we are in the target retention time interval.
      // Go on with the parsing.

      match = ticRegExp.match(line);

      if(match.hasMatch())
        {
          match.captured(1).toDouble(&ok);

          if(!ok)
            {
              qDebug() << __FILE__ << __LINE__ << "Failed to convert"
                       << match.captured(1) << "to double";

              return -1;
            }

          // qDebug() << __FILE__ << __LINE__ << "TIC line parsed: " << tic;

          // We know that the TIC line is located right before the spectrum
          // data. Delegate the parsing to another function.

          msXpSlibmass::MassSpectrum *newSpectrum = parseSpectrum(&file);

          if(newSpectrum == nullptr)
            qFatal(
              "Fatal error at %s@%d. Failed to parse spectrum. Program "
              "aborted.",
              __FILE__,
              __LINE__);

          // Do not forget to set that retention time to the spectrum
          // itself !

          newSpectrum->rrt() = rt;

          // We are reading in streamed mode. We need to combine each new
          // spectrum to the previous ones.

          // qDebug() << __FILE__ << __LINE__ << "integrating for rt:" << rt;

          combinedMassSpectrum.combine(*newSpectrum);

          // At this point we can increment the number of spectra that were
          // effectively read.
          ++spectraRead;

          QString msg = QString(" -- spectrum number %1\n").arg(spectraRead);

          emit updateFeedbackSignal(msgSkeleton + msg,
                                    -1,
                                    true /* setVisible */,
                                    LogType::LOG_TO_STATUS_BAR);

          // qDebug() << __FILE__ << __LINE__ << msg;
        }
      // End of tic had matched and thus
      // parsed the spectrum and processed it.
    }
  // End of
  // while(!file.atEnd())

  if(intensity != Q_NULLPTR)
    *intensity = combinedMassSpectrum.valSum();
  else
    {
      *keyVector = QVector<double>::fromList(combinedMassSpectrum.keyList());
      *valVector = QVector<double>::fromList(combinedMassSpectrum.valList());
    }

  file.close();

  // qDebug() << __FILE__ << __LINE__ << "Mz streamed integration has parsed "
  //<< spectraRead << "spectra.";

  return spectraRead;
}

} // namespace msXpSmineXpert
