/**
 * \filed core/msrun.cpp
 * \date 5/4/2017
 * \author Olivier Langella
 * \brief describes an MS run (chemical sample injected in a mass spectrometer)
 */


/*******************************************************************************
 * Copyright (c) 2017 Olivier Langella <Olivier.Langella@u-psud.fr>.
 *
 * This file is part of i2MassChroQ.
 *
 *     i2MassChroQ 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.
 *
 *     i2MassChroQ 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 i2MassChroQ.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contributors:
 *     Olivier Langella <Olivier.Langella@u-psud.fr> - initial API and
 *implementation
 ******************************************************************************/


#include "msrun.h"
#include <QFileInfo>
#include <QSettings>
#include <QDebug>
#include <QDir>
#include <pappsomspp/core/exception/exceptionnotfound.h>
#include <pappsomspp/core/xicextractor/msrunxicextractorfactory.h>
#include "../utils/msrunstatisticshandler.h"
#include <pappsomspp/core/msfile/msfileaccessor.h>
#include <pappsomspp/core/exception/exceptionnotimplemented.h>
#include <pappsomspp/core/msrun/private/timsmsrunreaderms2.h>
#include <pappsomspp/core/processing/filters/filterexclusionmz.h>
#include <pappsomspp/core/vendors/tims/timsddaprecursors.h>
#include <pappsomspp/core/precision.h>
#include "peptideevidence.h"
#include "alignmentgroup.h"
#include "project.h"

MsRun::MsRun(const QString &location) : pappso::MsRunId(location)
{
  QFileInfo fileinfo(location);
}

MsRun::MsRun(const MsRun &other) : pappso::MsRunId(other)
{
  m_msRunStatisticsMap = other.m_msRunStatisticsMap;
  // m_centroidOptions = other.m_centroidOptions;
}

MsRun::~MsRun()
{
  if(mpa_msrunRetentionTime != nullptr)
    {
      delete mpa_msrunRetentionTime;
    }
}
pappso::MsRunReaderSPtr &
MsRun::getMsRunReaderSPtr()
{
  // qDebug() << " filename=" << getFileName();
  if(msp_msRunReader == nullptr)
    {
      buildMsRunReaderSp();
    }

  return msp_msRunReader;
}

void
MsRun::buildMsRunReaderSp()
{
  qDebug() << " runid=" << getRunId() << " xmlid=" << getXmlId();
  pappso::MsFileAccessor *p_accessor = nullptr;

  try
    {

      p_accessor = new pappso::MsFileAccessor(getFileName(), "runa1");

      p_accessor->setPreferredFileReaderType(pappso::Enums::MsDataFormat::brukerTims,
                                             pappso::Enums::FileReaderType::tims_ms2);
      this->setMsDataFormat(p_accessor->getFileFormat());
    }
  catch(pappso::ExceptionNotFound &error)
    {
      qDebug() << "not found";
      msp_msRunReader = nullptr;
      /// p_accessor       = nullptr;
      // throw error;
      // file not found, don't throw exception, we'll try another location
    }
  if(p_accessor != nullptr)
    {
      try
        {
          msp_msRunReader =
            p_accessor->getMsRunReaderSPtrByRunId(getRunId(), getXmlId());
          delete p_accessor;
          p_accessor = nullptr;

          pappso::TimsMsRunReaderMs2 *tims2_reader =
            dynamic_cast<pappso::TimsMsRunReaderMs2 *>(msp_msRunReader.get());
          if(tims2_reader != nullptr)
            {

              std::shared_ptr<pappso::FilterSuite> ms2filter =
                std::make_shared<pappso::FilterSuite>();

              ms2filter.get()->push_back(
                std::make_shared<pappso::FilterMzExclusion>(
                  pappso::PrecisionFactory::getDaltonInstance(0.01)));

              tims2_reader->setMs2FilterCstSPtr(ms2filter);
            }

          this->setMsDataFormat(
            msp_msRunReader.get()->getMsRunId().get()->getMsDataFormat());
        }

      catch(pappso::PappsoException &error2)
        {
          msp_msRunReader = nullptr;
          if(p_accessor != nullptr)
            {
              delete p_accessor;
              p_accessor = nullptr;
            }
          throw error2;
        }
    }
}


void
MsRun::freeMsRunReaderSp()
{
  msp_msRunReader = nullptr;
}

void
MsRun::setMsRunStatistics(MsRunStatistics param, const QVariant &value)
{
  m_msRunStatisticsMap.insert(
    std::pair<MsRunStatistics, QVariant>(param, value));
}

const std::map<MsRunStatistics, QVariant> &
MsRun::getMsRunStatisticsMap() const
{
  return m_msRunStatisticsMap;
}

const QVariant
MsRun::getMsRunStatistics(MsRunStatistics param) const
{
  try
    {
      return m_msRunStatisticsMap.at(param);
    }
  catch(std::out_of_range &std_error)
    {
      return QVariant();
    }
}

pappso::MsRunReaderSPtr
MsRun::findMsRunFile()
{
  // first look at the file path :)
  qDebug();
  pappso::MsRunReaderSPtr msrun_reader_sp = getMsRunReaderSPtr();
  if(msrun_reader_sp != nullptr)
    {
      QFileInfo real_file(this->getFileName());
      if(real_file.exists())
        {

          qDebug();
          freeMsRunReaderSp();
          qDebug();
          return msrun_reader_sp;
        }
      else
        {
          msrun_reader_sp = nullptr;
        }
    }
  qDebug();
  QFileInfo file_original(this->getFileName());
  QString basename     = file_original.baseName();
  QString onlyfilename = file_original.fileName();
  QSettings settings;
  QString path = settings.value("path/mzdatadir", "").toString();

  QDir dir_search(path);

  QFileInfoList files = dir_search.entryInfoList();
  foreach(QFileInfo file, files)
    {
      if(file.isDir())
        {
          qDebug() << "DIR: " << file.fileName();
          if(file.baseName() == getSampleName())
            {

              this->setFileName(file.absoluteFilePath());
              try
                {
                  if(msrun_reader_sp == nullptr)
                    {

                      pappso::MsFileAccessor accessor(getFileName(), "");
                      accessor.setPreferredFileReaderType(
                        pappso::Enums::MsDataFormat::brukerTims,
                        pappso::Enums::FileReaderType::tims_ms2);
                      qDebug()
                        << " runid=" << getRunId() << " xmlid=" << getXmlId();

                      msrun_reader_sp = accessor.getMsRunReaderSPtrByRunId(
                        getRunId(), getXmlId());

                      this->setMsDataFormat(msrun_reader_sp.get()
                                              ->getMsRunId()
                                              .get()
                                              ->getMsDataFormat());

                      freeMsRunReaderSp();
                      return msrun_reader_sp;
                    }
                }
              catch(pappso::PappsoException &error)
                {
                }
            }
        }
      else
        {
          qDebug() << "FILE: " << file.fileName();
          if(onlyfilename == file.fileName())
            {
              this->setFileName(file.absoluteFilePath());
              try
                {
                  if(msrun_reader_sp == nullptr)
                    {

                      pappso::MsFileAccessor accessor(getFileName(), "");
                      accessor.setPreferredFileReaderType(
                        pappso::Enums::MsDataFormat::brukerTims,
                        pappso::Enums::FileReaderType::tims_ms2);
                      qDebug()
                        << " runid=" << getRunId() << " xmlid=" << getXmlId();

                      msrun_reader_sp = accessor.getMsRunReaderSPtrByRunId(
                        getRunId(), getXmlId());

                      this->setMsDataFormat(msrun_reader_sp.get()
                                              ->getMsRunId()
                                              .get()
                                              ->getMsDataFormat());

                      freeMsRunReaderSp();
                      return msrun_reader_sp;
                    }
                }
              catch(pappso::PappsoException &error)
                {
                }
            }
          if((file.fileName().contains(onlyfilename)) ||
             (file.fileName().contains(basename)) ||
             (file.fileName().contains(this->getSampleName())))
            {
              try
                {
                  this->setFileName(file.absoluteFilePath());

                  if(msrun_reader_sp == nullptr)
                    {

                      pappso::MsFileAccessor accessor(getFileName(), "");

                      accessor.setPreferredFileReaderType(
                        pappso::Enums::MsDataFormat::brukerTims,
                        pappso::Enums::FileReaderType::tims_ms2);
                      qDebug()
                        << " runid=" << getRunId() << " xmlid=" << getXmlId();
                      msrun_reader_sp = accessor.getMsRunReaderSPtrByRunId(
                        getRunId(), getXmlId());

                      this->setMsDataFormat(msrun_reader_sp.get()
                                              ->getMsRunId()
                                              .get()
                                              ->getMsDataFormat());
                      freeMsRunReaderSp();
                      return msrun_reader_sp;
                    }
                }
              catch(pappso::PappsoException &error)
                {
                  msrun_reader_sp = nullptr;
                }
            }
        }
    }
  this->setFileName(file_original.absoluteFilePath());
  freeMsRunReaderSp();
  qDebug();
  return msrun_reader_sp;
}

void
MsRun::checkMsRunStatistics()
{

  MsRunStatisticsHandler stats;
  checkMsRunStatistics(&stats);
}

void
MsRun::checkMsRunStatistics(MsRunStatisticsHandler *currentHandler)
{
  // qWarning();
  QVariant msrun_var = getMsRunStatistics(MsRunStatistics::total_spectra);
  if(msrun_var.isNull())
    {
      try
        {

          pappso::MsRunReaderSPtr local_msrun_reader_sp = getMsRunReaderSPtr();
          if(this->getMsDataFormat() == pappso::Enums::MsDataFormat::brukerTims)
            {
              pappso::TimsMsRunReaderMs2 *tims2_reader =
                dynamic_cast<pappso::TimsMsRunReaderMs2 *>(
                  local_msrun_reader_sp.get());
              if(tims2_reader == nullptr)
                {
                  qDebug();
                }
              else
                {
                  pappso::TimsDataSp tims_data =
                    tims2_reader->getTimsDataSPtr();

                  if(tims_data.get() == nullptr)
                    {
                      qDebug();
                    }
                  else
                    {
                      if(currentHandler->shouldStop())
                        { // statistics handler was stopped : don't use
                          // collected statistics because it is only partial
                        }
                      else
                        {
                          setMsRunStatistics(MsRunStatistics::total_spectra,
                                             "NA");
                          // not the number of MS1 or MS2 but the number of
                          // scans and precursors. Compute from th mobillity
                          // results
                          setMsRunStatistics(MsRunStatistics::total_spectra_ms1,
                                             (unsigned int)tims_data.get()
                                               ->getTimsDdaPrecursorsPtr()
                                               ->getTotalPrecursorCount());
                          setMsRunStatistics(MsRunStatistics::total_spectra_ms2,
                                             (unsigned int)tims_data.get()
                                               ->getTimsDdaPrecursorsPtr()
                                               ->getTotalPrecursorCount());
                          setMsRunStatistics(MsRunStatistics::total_spectra_ms3,
                                             0);
                          setMsRunStatistics(MsRunStatistics::tic_spectra_ms1,
                                             "NA");
                          setMsRunStatistics(MsRunStatistics::tic_spectra_ms2,
                                             "NA");
                          setMsRunStatistics(MsRunStatistics::tic_spectra_ms3,
                                             "NA");
                        }
                    }
                }
            }
          else
            {
              pappso::MsRunReadConfig config;
              config.setNeedPeakList(true);
              config.setMsLevels({1, 2, 3});
              local_msrun_reader_sp.get()->readSpectrumCollection2(
                config, *currentHandler);

              setMsRunStatistics(MsRunStatistics::total_spectra,
                                 (unsigned int)currentHandler->getTotalCount());
              setMsRunStatistics(
                MsRunStatistics::total_spectra_ms1,
                (unsigned int)currentHandler->getMsLevelCount(1));
              setMsRunStatistics(
                MsRunStatistics::total_spectra_ms2,
                (unsigned int)currentHandler->getMsLevelCount(2));
              setMsRunStatistics(
                MsRunStatistics::total_spectra_ms3,
                (unsigned int)currentHandler->getMsLevelCount(3));
              setMsRunStatistics(MsRunStatistics::tic_spectra_ms1,
                                 currentHandler->getMsLevelTic(1));
              setMsRunStatistics(MsRunStatistics::tic_spectra_ms2,
                                 currentHandler->getMsLevelTic(2));
              setMsRunStatistics(MsRunStatistics::tic_spectra_ms3,
                                 currentHandler->getMsLevelTic(3));
            }
        }
      catch(pappso::ExceptionNotFound &error)
        {
          // no file found, no statistics
        }
    }
  freeMsRunReaderSp();
  // qWarning();
}

pappso::MsRunXicExtractorInterfaceSp
MsRun::getMsRunXicExtractorInterfaceSp()
{
  if(msp_msRunXicExtractor != nullptr)
    {
      return msp_msRunXicExtractor;
    }
  qDebug();
  msp_msRunReader = this->findMsRunFile();
  qDebug();
  if(msp_msRunReader != nullptr)
    {

      qDebug();
      pappso::MsRunXicExtractorFactory::getInstance().setTmpDir(
        QDir::tempPath());

      QSettings settings;
      QString xic_extraction_method =
        settings.value("global/xic_extractor", "pwiz").toString();
      if(xic_extraction_method == "pwiz")
        {
          pappso::MsRunXicExtractorFactory::getInstance()
            .setMsRunXicExtractorFactoryType(
              pappso::MsRunXicExtractorFactoryType::direct);
          msp_msRunXicExtractor =
            pappso::MsRunXicExtractorFactory::getInstance()
              .buildMsRunXicExtractorSp(msp_msRunReader);
        }
      else
        {
          pappso::MsRunXicExtractorFactory::getInstance()
            .setMsRunXicExtractorFactoryType(
              pappso::MsRunXicExtractorFactoryType::diskbuffer);
          msp_msRunXicExtractor =
            pappso::MsRunXicExtractorFactory::getInstance()
              .buildMsRunXicExtractorSp(msp_msRunReader);
        }
      //_xic_extractor_sp = pappso::MsRunXicExtractorFactory::getInstance()
      //                      .buildMsRunXicExtractorDiskBufferSp(*this);

      qDebug();
    }
  freeMsRunReaderSp();
  return msp_msRunXicExtractor;
}

void
MsRun::buildMsRunRetentionTime(
  const PeptideEvidenceStore &peptide_evidence_store)
{
  pappso::MsRunReaderSPtr reader;
  try
    {
      reader = getMsRunReaderSPtr();
    }
  catch(pappso::PappsoException &error)
    {
      throw pappso::ExceptionNotFound(
        QObject::tr(
          "Error while processing MSrun \"%1\" for sample named \"%2\" :\n%3")
          .arg(getXmlId())
          .arg(getSampleName())
          .arg(error.qwhat()));
    }
  if(reader == nullptr)
    {
      throw pappso::ExceptionNotFound(
        QObject::tr(
          "MSrun \"%1\" for sample named \"%2\" file \"%3\" not found")
          .arg(getXmlId())
          .arg(getSampleName())
          .arg(getFileName()));
    }
  if(mpa_msrunRetentionTime == nullptr)
    {
      mpa_msrunRetentionTime =
        new pappso::MsRunRetentionTime<const pappso::Peptide *>(
          reader.get()->getRetentionTimeLine());
    }
  for(auto &peptide_evidence : peptide_evidence_store.getPeptideEvidenceList())
    {
      if(peptide_evidence.get()->isValid())
        {
          if(peptide_evidence.get()->getMsRunP() == this)
            {
              mpa_msrunRetentionTime->addPeptideAsSeamark(
                peptide_evidence.get()
                  ->getPeptideXtpSp()
                  .get()
                  ->getNativePeptideP(),
                peptide_evidence.get()->getRetentionTime(),
                1);
            }
        }
    }
  reader.get()->releaseDevice();
  // mpa_msrunRetentionTime->computePeptideRetentionTimes();
  freeMsRunReaderSp();
}

void
MsRun::computeMsRunRetentionTime()
{
  if(mpa_msrunRetentionTime != nullptr)
    {
      qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__
               << " msrun id=" << getXmlId();
      mpa_msrunRetentionTime->computeSeamarks();
    }
}

void
MsRun::clearMsRunRetentionTime()
{
  if(mpa_msrunRetentionTime != nullptr)
    {
      delete mpa_msrunRetentionTime;
      mpa_msrunRetentionTime = nullptr;
    }
}


pappso::MsRunRetentionTime<const pappso::Peptide *> *
MsRun::getMsRunRetentionTimePtr()
{
  return mpa_msrunRetentionTime;
}


MsRunAlignmentGroupSp
MsRun::getAlignmentGroup()
{
  return msp_alignmentGroup;
}

void
MsRun::setAlignmentGroup(MsRunAlignmentGroupSp new_group)
{
  msp_alignmentGroup = new_group;
}


pappso::MassSpectrumCstSPtr
MsRun::getMassSpectrumCstSPtrByScanNumber(std::size_t scan_number)
{

  qDebug() << "scan=" << scan_number;
  if(getMsDataFormat() == pappso::Enums::MsDataFormat::MGF)
    {
      scan_number = scan_number - 1;
      qDebug() << "MGF format";
    }
  pappso::MsRunReaderSPtr msrun_reader_sp = getMsRunReaderSPtr();

  if(msrun_reader_sp == nullptr)
    {
      msrun_reader_sp = findMsRunFile();
      if(msrun_reader_sp == nullptr)
        {
          throw pappso::ExceptionNotFound(
            QObject::tr("mz data \"%1\" file not found").arg(getFileName()));
        }
    }
  qDebug();
  msrun_reader_sp = getMsRunReaderSPtr();
  if(msrun_reader_sp == nullptr)
    {
      throw pappso::ExceptionNotFound(
        QObject::tr("mz data \"%1\" file not found").arg(getFileName()));
    }


  // qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__  <<
  // _ms_run_sp.get()->getMsRunReaderSp().get()->getSpectrumListSize();

  std::size_t spectrum_index = scan_number;

  if(msrun_reader_sp.get()->hasScanNumbers())
    {
      qDebug() << "HAS SCAN NUMBERS";
      spectrum_index =
        msrun_reader_sp.get()->scanNumber2SpectrumIndex(scan_number);
    }

  qDebug() << " spectrum file="
           << msrun_reader_sp.get()->getMsRunId().get()->getFileName()
           << " index=" << spectrum_index;
  pappso::MassSpectrumCstSPtr spectrum_sp =
    msrun_reader_sp.get()->massSpectrumCstSPtr(spectrum_index);
  qDebug();
  return spectrum_sp;
}

pappso::QualifiedMassSpectrum
MsRun::getQualifiedMassSpectrumByScanNumber(std::size_t scan_number, bool data)
{

  qDebug() << "scan=" << scan_number;
  if(getMsDataFormat() == pappso::Enums::MsDataFormat::MGF)
    {
      scan_number = scan_number - 1;
      qDebug() << "MGF format";
    }
  pappso::MsRunReaderSPtr msrun_reader_sp = getMsRunReaderSPtr();

  if(msrun_reader_sp == nullptr)
    {
      msrun_reader_sp = findMsRunFile();
      if(msrun_reader_sp == nullptr)
        {
          throw pappso::ExceptionNotFound(
            QObject::tr("mz data \"%1\" file not found").arg(getFileName()));
        }
    }
  qDebug();
  msrun_reader_sp = getMsRunReaderSPtr();
  if(msrun_reader_sp == nullptr)
    {
      throw pappso::ExceptionNotFound(
        QObject::tr("mz data \"%1\" file not found").arg(getFileName()));
    }


  // qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__  <<
  // _ms_run_sp.get()->getMsRunReaderSp().get()->getSpectrumListSize();

  std::size_t spectrum_index = scan_number;

  if(msrun_reader_sp.get()->hasScanNumbers())
    {
      qDebug() << "HAS SCAN NUMBERS";
      spectrum_index =
        msrun_reader_sp.get()->scanNumber2SpectrumIndex(scan_number);
    }

  qDebug() << " spectrum file="
           << msrun_reader_sp.get()->getMsRunId().get()->getFileName()
           << " index=" << spectrum_index;
  return msrun_reader_sp.get()->qualifiedMassSpectrum(spectrum_index, data);
}


pappso::MassSpectrumCstSPtr
MsRun::getMassSpectrumCstSPtrBySpectrumIndex(std::size_t spectrum_index)
{

  pappso::MsRunReaderSPtr msrun_reader_sp = getMsRunReaderSPtr();

  if(msrun_reader_sp == nullptr)
    {
      msrun_reader_sp = findMsRunFile();
      if(msrun_reader_sp == nullptr)
        {
          throw pappso::ExceptionNotFound(
            QObject::tr("mz data \"%1\" file not found").arg(getFileName()));
        }
    }
  qDebug();
  msrun_reader_sp = getMsRunReaderSPtr();
  if(msrun_reader_sp == nullptr)
    {
      throw pappso::ExceptionNotFound(
        QObject::tr("mz data \"%1\" file not found").arg(getFileName()));
    }

  qDebug() << " spectrum file="
           << msrun_reader_sp.get()->getMsRunId().get()->getFileName()
           << " index=" << spectrum_index;
  pappso::MassSpectrumCstSPtr spectrum_sp =
    msrun_reader_sp.get()->massSpectrumCstSPtr(spectrum_index);
  qDebug();
  return spectrum_sp;
}

pappso::QualifiedMassSpectrum
MsRun::getQualifiedMassSpectrumBySpectrumIndex(std::size_t spectrum_index,
                                               bool data)
{

  pappso::MsRunReaderSPtr msrun_reader_sp = getMsRunReaderSPtr();

  if(msrun_reader_sp == nullptr)
    {
      msrun_reader_sp = findMsRunFile();
      if(msrun_reader_sp == nullptr)
        {
          throw pappso::ExceptionNotFound(
            QObject::tr("mz data \"%1\" file not found").arg(getFileName()));
        }
    }
  qDebug();
  msrun_reader_sp = getMsRunReaderSPtr();
  if(msrun_reader_sp == nullptr)
    {
      throw pappso::ExceptionNotFound(
        QObject::tr("mz data \"%1\" file not found").arg(getFileName()));
    }

  qDebug() << " spectrum file="
           << msrun_reader_sp.get()->getMsRunId().get()->getFileName()
           << " index=" << spectrum_index;
  return msrun_reader_sp.get()->qualifiedMassSpectrum(spectrum_index, data);
}


std::size_t
MsRun::scanNumber2SpectrumIndex(std::size_t scan_number)
{

  qDebug() << "scan=" << scan_number;
  if(getMsDataFormat() == pappso::Enums::MsDataFormat::MGF)
    {
      scan_number = scan_number - 1;
      qDebug() << "MGF format";
    }
  pappso::MsRunReaderSPtr msrun_reader_sp = getMsRunReaderSPtr();

  if(msrun_reader_sp == nullptr)
    {
      msrun_reader_sp = findMsRunFile();
      if(msrun_reader_sp == nullptr)
        {
          throw pappso::ExceptionNotFound(
            QObject::tr("mz data \"%1\" file not found").arg(getFileName()));
        }
    }
  qDebug();
  msrun_reader_sp = getMsRunReaderSPtr();
  if(msrun_reader_sp == nullptr)
    {
      throw pappso::ExceptionNotFound(
        QObject::tr("mz data \"%1\" file not found").arg(getFileName()));
    }


  if(msrun_reader_sp.get()->hasScanNumbers())
    {
      qDebug() << "HAS SCAN NUMBERS";
      return msrun_reader_sp.get()->scanNumber2SpectrumIndex(scan_number);
    }
  else
    {
      throw pappso::ExceptionNotFound(
        QObject::tr("mz data \"%1\" file does not contain scan numbers")
          .arg(getFileName()));
    }
}

std::size_t
MsRun::countUniqueValidSpectrumIndexList(const Project *project_p) const
{
  auto ident_list = project_p->getIdentificationDataSourceStore()
                      .getIdentificationDataSourceList();


  std::vector<std::size_t> spectra_set;

  for(auto ident : ident_list)
    {
      if(ident.get()->getMsRunSp().get() == this)
        {
          for(const PeptideEvidenceSp &peptide_evidence_sp :
              ident.get()->getPeptideEvidenceStore().getPeptideEvidenceList())
            {
              if(peptide_evidence_sp.get()->isValid())
                spectra_set.push_back(
                  peptide_evidence_sp.get()->getUniqueIndex());
            }
        }
    }

  std::sort(spectra_set.begin(), spectra_set.end());

  return std::distance(spectra_set.begin(),
                       std::unique(spectra_set.begin(), spectra_set.end()));
}
