/*
 Copyright (C) 2014 Ronald C Beavis, all rights reserved
 X! tandem
 This software is a component of the X! proteomics software
 development project

Use of this software governed by the Artistic license, as reproduced here:

The Artistic License for all X! software, binaries and documentation

Preamble
The intent of this document is to state the conditions under which a
Package may be copied, such that the Copyright Holder maintains some
semblance of artistic control over the development of the package,
while giving the Pas of the package the right to use and distribute
the Package in a more-or-less customary fashion, plus the right to
make reasonable modifications.

Definitions
"Package" refers to the collection of files distributed by the Copyright
  Holder, and derivatives of that collection of files created through
  textual modification.

"Standard Version" refers to such a Package if it has not been modified,
  or has been modified in accordance with the wishes of the Copyright
  Holder as specified below.

"Copyright Holder" is whoever is named in the copyright or copyrights
  for the package.

"You" is you, if you're thinking about copying or distributing this Package.

"Reasonable copying fee" is whatever you can justify on the basis of
  media cost, duplication charges, time of people involved, and so on.
  (You will not be required to justify it to the Copyright Holder, but
  only to the computing community at large as a market that must bear
  the fee.)

"Freely Available" means that no fee is charged for the item itself,
  though there may be fees involved in handling the item. It also means
  that recipients of the item may redistribute it under the same
  conditions they received it.

1. You may make and give away verbatim copies of the source form of the
Standard Version of this Package without restriction, provided that
you duplicate all of the original copyright notices and associated
disclaimers.

2. You may apply bug fixes, portability fixes and other modifications
derived from the Public Domain or from the Copyright Holder. A
Package modified in such a way shall still be considered the Standard
Version.

3. You may otherwise modify your copy of this Package in any way, provided
that you insert a prominent notice in each changed file stating how and
when you changed that file, and provided that you do at least ONE of the
following:

a.	place your modifications in the Public Domain or otherwise make them
  Freely Available, such as by posting said modifications to Usenet
  or an equivalent medium, or placing the modifications on a major
  archive site such as uunet.uu.net, or by allowing the Copyright Holder
  to include your modifications in the Standard Version of the Package.
b.	use the modified Package only within your corporation or organization.
c.	rename any non-standard executables so the names do not conflict
  with standard executables, which must also be provided, and provide
  a separate manual page for each non-standard executable that clearly
  documents how it differs from the Standard Version.
d.	make other distribution arrangements with the Copyright Holder.

4. You may distribute the programs of this Package in object code or
executable form, provided that you do at least ONE of the following:

a.	distribute a Standard Version of the executables and library files,
  together with instructions (in the manual page or equivalent) on
  where to get the Standard Version.
b.	accompany the distribution with the machine-readable source of the
  Package with your modifications.
c.	give non-standard executables non-standard names, and clearly
  document the differences in manual pages (or equivalent), together
  with instructions on where to get the Standard Version.
d.	make other distribution arrangements with the Copyright Holder.

5. You may charge a reasonable copying fee for any distribution of
this Package. You may charge any fee you choose for support of
this Package. You may not charge a fee for this Package itself.
However, you may distribute this Package in aggregate with other
(possibly commercial) programs as part of a larger (possibly
commercial) software distribution provided that you do not a
dvertise this Package as a product of your own. You may embed this
Package's interpreter within an executable of yours (by linking);
this shall be construed as a mere form of aggregation, provided that
the complete Standard Version of the interpreter is so embedded.

6. The scripts and library files supplied as input to or produced as
output from the programs of this Package do not automatically fall
under the copyright of this Package, but belong to whomever generated
them, and may be sold commercially, and may be aggregated with this
Package. If such scripts or library files are aggregated with this
Package via the so-called "undump" or "unexec" methods of producing
a binary executable image, then distribution of such an image shall
neither be construed as a distribution of this Package nor shall it
fall under the restrictions of Paragraphs 3 and 4, provided that you
do not represent such an executable image as a Standard Version of
this Package.

7. C subroutines (or comparably compiled subroutines in other languages)
supplied by you and linked into this Package in order to emulate
subroutines and variables of the language defined by this Package
shall not be considered part of this Package, but are the equivalent
of input as in Paragraph 6, provided these subroutines do not change
the language in any way that would cause it to fail the regression
tests for the language.

8. Aggregation of this Package with a commercial distribution is always
permitted provided that the use of this Package is embedded; that is,
when no overt attempt is made to make this Package's interfaces visible
to the end user of the commercial distribution. Such use shall not be
construed as a distribution of this Package.

9. The name of the Copyright Holder may not be used to endorse or promote
products derived from this software without specific prior written permission.

10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.

The End
*/

// File version: 2014-09-25
/*
 * the mreport object provides the functionality to export all of the
 * information collected in mprocess to an XML file. The file path was defined
 * in the original XML input parameter file. The file produced by mreport can be
 * used as an input parameter file to repeat a protein modeling session at a
 * later time.
 */

#include <sys/timeb.h>
#include <ctime>
#include <QDebug>
#include <QDateTime>
#include <QFileInfo>
#include <pappsomspp/core/pappsoexception.h>
#include <pappsomspp/core/amino_acid/aamodification.h>
#include "stdafx.h"


#ifdef HEADER2017
#include "common.h"
#include "msequence.h"
#include "msequencecollection.h"
#include "msequenceserver.h"
#include "msequtilities.h"
#include "mspectrum.h"
#include "xmlparameter.h"
#include "mscore.h"
#include "mprocess.h"
const QString mzid_report::m_processFlavor = "2017";
#endif

#ifdef HEADER2015
// #include <regex>
// #include "saxsaphandler.h"
#include "../common.h"
#include "../msequence.h"
#include "2015/msequencecollection.h"
#include "2015/msequenceserver.h"
#include "../msequtilities.h"
#include "2015/mspectrum.h"
#include "../xmlparameter.h"
#include "2015/mscore.h"
#include "2015/mprocess.h"
const QString mzid_report::m_processFlavor = "2015";
#endif


#ifdef HEADER2015P
// #include <regex>
// #include "saxsaphandler.h"
#include "../common.h"
#include "../msequence.h"
#include "2015p/msequencecollection.h"
#include "2015p/msequenceserver.h"
#include "../msequtilities.h"
#include "../xmlparameter.h"
#include "2015p/mspectrum.h"
#include "2015p/mscore.h"
#include "2015p/mprocess.h"
const QString mzid_report::m_processFlavor = "2015p";
#endif


#include "mzid_report.h"

const QString mzid_report::m_reversedProteinSequenceStringEndsWith =
  ":reversed";

// create the mzid_report object and load the UniMod definitions

mzid_report::mzid_report(const QString &sample_name,
                         const pappso::MsFileAccessor *p_msFileAccessor,
                         mscore &score)
  : mp_msFileAccessor(p_msFileAccessor), m_Score(score)
{
  load_unimod();
  m_sampleName = sample_name;
}

mzid_report::~mzid_report(void)
{
}


bool
mzid_report::getPerformanceMap(const string &_k, string &_v)
{
  if(m_performanceMap.find(_k) != m_performanceMap.end())
    {
      _v = m_performanceMap[_k];
      return true;
    }
  _v.erase(_v.begin(), _v.end());
  return false;
}
// Open the ofstream object using the file name supplied in the input file and
// add the header portion of the mzIndentML file
// Should be called initially in an use of the object

bool
mzid_report::start(XmlParameter &_x, XmlParameter &_p)
{
  string strKey = "output, path";
  string strValue;
  _x.get(strKey, strValue);
  if(strValue.size() == 0)
    {
      throw pappso::PappsoException(
        QObject::tr("strValue.size() == 0 : no output path"));
    }

  qDebug() << QString("%1.mzid").arg(strValue.c_str());
  m_outputFile = new QFile(QString("%1.mzid").arg(strValue.c_str()));


  if(m_outputFile->open(QIODevice::WriteOnly))
    {
      qDebug();
      m_outputStream = new pappso::MzIdentMlWriter();
      m_outputStream->setDevice(m_outputFile);
    }
  else
    {
      qDebug();
      throw pappso::PappsoException(
        QObject::tr(
          "unable to open file %1.mzid for writing, check path or permissions")
          .arg(strValue.c_str()));
    }


  strKey = "scoring, include reverse";
  _x.get(strKey, strValue);
  m_enumReverseSearchType = EnumReverseSearchType::no_decoy;
  if(strValue == "yes")
    {
      m_enumReverseSearchType = EnumReverseSearchType::reversed_sequences_added;
    }
  else if(strValue == "only")
    {
      m_enumReverseSearchType = EnumReverseSearchType::only_score_on_reversed;
    }

  strKey = "output, mzid decoy DB accession regexp";
  _x.get(strKey, strValue);
  if(strValue.length() == 0)
    {
      m_strRegex = "^XXX";
    }
  else
    {
      m_strRegex = strValue;
    }
  m_performanceMap = _p.m_mapParam;
  return add_header();
}

// Finish the XML output and close the ofstream object
// Should be called last in any use of the object

bool
mzid_report::end(void)
{

  m_outputStream->writeEndDocument();
  m_outputFile->close();


  delete m_outputFile;
  delete m_outputStream;

  return true;
}

// Output the mzIndentML header information

bool
mzid_report::add_header()
{

  qDebug();
  m_outputStream->writeStartMzIdentMlDocument("a1tandem", "1.2.0");
  // xmlns:GAML="http://www.bioml.com/gaml/"
  // m_ofOut << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  // m_ofOut << "<MzIdentML id=\"X! Tandem\" version=\"1.1.0\" "
  //          "xmlns=\"http://psidev.info/psi/pi/mzIdentML/1.1\" "
  //        "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
  //      "xsi:schemaLocation=\"http://psidev.info/psi/pi/mzIdentML/1.1 "
  //    "http://www.psidev.info/files/mzIdentML1.1.0.xsd\" creationDate=\""
  //<< _t << "\" >\n";
  m_outputStream->writeCvList();

  m_outputStream->writeStartElement("AnalysisSoftwareList");
  // m_ofOut << "<AnalysisSoftwareList "
  //          "xmlns=\"http://psidev.info/psi/pi/mzIdentML/1.1\">\n";


  string strKey;
  string strValue;
  strKey = "process, version";
  getPerformanceMap(strKey, strValue);
  string strVersion = strValue;

  m_outputStream->writeStartElement("AnalysisSoftware");
  m_outputStream->writeAttribute("version", strVersion.c_str());
  m_outputStream->writeAttribute("name", "X! Tandem");
  m_outputStream->writeAttribute("id", "ID_software");
  // m_ofOut << "    <AnalysisSoftware version=\"" << _s
  //       << "\" name=\"X! Tandem\" id=\"ID_software\">\n";

  m_outputStream->writeStartElement("SoftwareName");
  // m_ofOut << "        <SoftwareName>\n";

  m_outputStream->writeCvParam("PSI-MS", "MS:1001476", "X! Tandem", "");
  // m_ofOut << "            <cvParam accession=\"MS:1001476\" cvRef=\"PSI-MS\"
  // "
  //          "name=\"X\\! Tandem\"/>\n";
  m_outputStream->writeEndElement();
  // m_ofOut << "        </SoftwareName>\n";

  m_outputStream->writeEndElement();
  // m_ofOut << "    </AnalysisSoftware>\n";

  m_outputStream->writeEndElement();
  // m_ofOut << "</AnalysisSoftwareList>\n";

  qDebug();
  return true;
}

// Create the SequenceCollection portion of the mzIndentML file

bool
mzid_report::sequence_collection(vector<mspectrum> &_vs, vector<string> &_vp)
{
  if(m_outputStream->hasError())
    {
      return false;
    }
  m_outputStream->writeStartElement("SequenceCollection");
  // m_ofOut << "<SequenceCollection "
  //          "xmlns=\"http://psidev.info/psi/pi/mzIdentML/1.1\">\n";
  add_dbsequence(_vs);
  add_peptides(_vs);
  add_peptide_evidence(_vs);

  m_outputStream->writeEndElement();
  //  m_ofOut << "</SequenceCollection>\n";
  return true;
}

// Create the AnalysisCollection portion of the mzIdentML file

bool
mzid_report::analysis_collection(vector<mspectrum> &_vs, vector<string> &_vp)
{
  if(m_outputStream->hasError())
    {
      return false;
    }
  m_outputStream->writeStartElement("AnalysisCollection");
  // m_ofOut
  // << "<AnalysisCollection
  // xmlns=\"http://psidev.info/psi/pi/mzIdentML/1.1\">";

  m_outputStream->writeStartElement("SpectrumIdentification");
  m_outputStream->writeAttribute("spectrumIdentificationList_ref", "SI_LIST_1");
  m_outputStream->writeAttribute("spectrumIdentificationProtocol_ref",
                                 "SearchProtocol_1");
  m_outputStream->writeAttribute("id", "SpecIdent_1");
  //  m_ofOut
  //  << "\t<SpectrumIdentification spectrumIdentificationList_ref=\"SI_LIST_1\"
  //  "
  // "spectrumIdentificationProtocol_ref=\"SearchProtocol_1\" "
  //"id=\"SpecIdent_1\">\n";

  m_outputStream->writeStartElement("InputSpectra");
  m_outputStream->writeAttribute("spectraData_ref", "SID_1");
  m_outputStream->writeEndElement();
  // m_ofOut << "\t\t<InputSpectra spectraData_ref=\"SID_1\"/>\n";
  size_t a = 0;
  while(a < _vp.size())
    {
      m_outputStream->writeStartElement("SearchDatabaseRef");
      m_outputStream->writeAttribute("searchDatabase_ref",
                                     QString("SearchDB_%1").arg(a));
      //  m_ofOut << "\t\t<SearchDatabaseRef searchDatabase_ref=\"SearchDB_" <<
      //  a
      m_outputStream->writeEndElement();
      //<< "\"/>\n";
      a++;
    }

  m_outputStream->writeEndElement();
  // m_ofOut << "\t</SpectrumIdentification>\n";

  m_outputStream->writeEndElement();
  // m_ofOut << "</AnalysisCollection>\n";
  return true;
}

// Create the AnalysisProtocolCollection portion of the mzIdentML file

bool
mzid_report::analysis_protocol_collection(XmlParameter &_x)
{
  m_outputStream->writeStartElement("AnalysisProtocolCollection");
  // m_ofOut << "<AnalysisProtocolCollection "
  //          "xmlns=\"http://psidev.info/psi/pi/mzIdentML/1.1\">\n";

  m_outputStream->writeStartElement("SpectrumIdentificationProtocol");
  m_outputStream->writeAttribute("analysisSoftware_ref", "ID_software");
  m_outputStream->writeAttribute("id", "SearchProtocol_1");
  // m_ofOut << "<SpectrumIdentificationProtocol "
  //          "analysisSoftware_ref=\"ID_software\"
  //          id=\"SearchProtocol_1\">\n";
  m_outputStream->writeStartElement("SearchType");

  m_outputStream->writeCvParam("PSI-MS", "MS:1001083", "ms-ms search", "");
  // m_ofOut << "\t<SearchType>\n";
  // m_ofOut << "\t\t<cvParam accession=\"MS:1001083\" cvRef=\"PSI-MS\" "
  //          "name=\"ms-ms search\"/>\n";

  m_outputStream->writeEndElement();
  // m_ofOut << "\t</SearchType>\n";

  m_outputStream->writeStartElement("AdditionalSearchParams");

  for(auto &pair_param : _x.m_mapParam)
    {
      m_outputStream->writeUserParam(pair_param.first.c_str(),
                                     pair_param.second.c_str());
    }

  m_outputStream->writeUserParam(
    "decoy_accession_regexp",
    QString(".*%1$").arg(m_reversedProteinSequenceStringEndsWith));

  m_outputStream->writeUserParam(
    "process, tandemng",
    QString("tandemng %1 %2").arg(m_processFlavor).arg(tandemng_VERSION));


  for(auto &pair_param : m_performanceMap)
    {
      m_outputStream->writeUserParam(pair_param.first.c_str(),
                                     pair_param.second.c_str());
    }

  string strKey = "list path, default parameters";
  string strValue;
  if(_x.get(strKey, strValue))
    {

      m_outputStream->writeUserParam("xtandem_preset_file", strValue.c_str());
    }

  QFile preset_file(strValue.c_str());
  if(preset_file.open(QFile::ReadOnly | QFile::Text))
    {
      QTextStream in(&preset_file);
      // qDebug() << f.size() << in.readAll();

      m_outputStream->writeComment(in.readAll());

      preset_file.close();
    }
  else
    {
      throw pappso::PappsoException(
        QString("ERROR reading preset file %1, check path or file permission")
          .arg(strValue.c_str()));
    }

  m_outputStream->writeEndElement();


  m_outputStream->writeStartElement("ModificationParams");
  // m_ofOut << "\t<ModificationParams>\n";
  strKey = "residue, modification mass";
  _x.get(strKey, strValue);
  analysis_mods(strValue, true);
  strKey = "residue, potential modification mass";
  _x.get(strKey, strValue);
  analysis_mods(strValue, false);
  strKey = "refine, potential modification mass";
  _x.get(strKey, strValue);
  analysis_mods(strValue, false);
  strKey = "refine, potential modification mass 1";
  _x.get(strKey, strValue);
  analysis_mods(strValue, false);


  m_outputStream->writeEndElement();
  //  m_ofOut << "\t</ModificationParams>\n";

  m_outputStream->writeStartElement("Enzymes");
  // m_ofOut << "\t<Enzymes>\n";


  //  <note type="input" label="protein, cleavage semi">no</note>
  //  <note type="input" label="protein, cleavage site">[RK]|{P}</note>
  m_outputStream->writeStartElement("Enzyme");

  //<note type="input" label="scoring, maximum missed cleavage sites">1</note>
  strKey = "scoring, maximum missed cleavage sites";
  _x.get(strKey, strValue);
  m_outputStream->writeAttribute("missedCleavages", strValue.c_str());

  m_outputStream->writeAttribute("semiSpecific", "false");
  // m_ofOut << "\t<Enzyme missedCleavages=\"1000\" semiSpecific=\"false\" "
  m_outputStream->writeAttribute("id", "Tryp");
  //"id=\"Tryp\">\n";

  strKey = "protein, cleavage site";
  _x.get(strKey, strValue);
  if(strValue == "[RK]|{P}")
    {
      m_outputStream->writeStartElement("EnzymeName");
      // m_ofOut << "\t<EnzymeName>\n";

      m_outputStream->writeCvParam("PSI-MS", "MS:1001251", "Trypsin", "");
      // m_ofOut << "\t\t<cvParam accession=\"MS:1001251\" cvRef=\"PSI-MS\" "
      //          "name=\"Trypsin\"/>\n";
      m_outputStream->writeEndElement();
      // m_ofOut << "\t</EnzymeName>\n";
    }
  m_outputStream->writeEndElement();
  // m_ofOut << "\t</Enzyme>\n";
  m_outputStream->writeEndElement();
  // m_ofOut << "\t</Enzymes>\n";


  pappso::Enums::PrecisionUnit precision_unit =
    pappso::Enums::PrecisionUnit::ppm;
  m_outputStream->writeStartElement("FragmentTolerance");
  //	<FragmentTolerance>

  strKey = "spectrum, fragment monoisotopic mass error units";
  _x.get(strKey, strValue);
  if(strValue == "Daltons")
    {
      precision_unit = pappso::Enums::PrecisionUnit::dalton;
    }

  strKey = "spectrum, fragment monoisotopic mass error";
  _x.get(strKey, strValue);
  // <note type="input" label="spectrum, fragment monoisotopic mass
  // error">0.02</note>
  //  <note type="input" label="spectrum, fragment monoisotopic mass error
  //  units">Daltons</note>
  m_outputStream->writeCvParamUo("MS:1001412",
                                 "PSI-MS",
                                 "search tolerance plus value",
                                 strValue.c_str(),
                                 precision_unit);

  m_outputStream->writeCvParamUo("MS:1001413",
                                 "PSI-MS",
                                 "search tolerance minus value",
                                 strValue.c_str(),
                                 precision_unit);

  m_outputStream->writeEndElement();
  //	</FragmentTolerance>

  m_outputStream->writeStartElement("ParentTolerance");
  // m_ofOut << "\t<ParentTolerance>\n";

  precision_unit = pappso::Enums::PrecisionUnit::ppm;

  strKey = "spectrum, parent monoisotopic mass error units";
  _x.get(strKey, strValue);
  if(strValue == "Daltons")
    {
      precision_unit = pappso::Enums::PrecisionUnit::dalton;
    }
  // <note type="input" label="spectrum, parent monoisotopic mass error
  // minus">10</note> <note type="input" label="spectrum, parent monoisotopic
  // mass error plus">10</note> <note type="input" label="spectrum, parent
  // monoisotopic mass error units">ppm</note>


  strKey = "spectrum, parent monoisotopic mass error plus";
  _x.get(strKey, strValue);

  m_outputStream->writeCvParamUo("MS:1001412",
                                 "PSI-MS",
                                 "search tolerance plus value",
                                 strValue.c_str(),
                                 precision_unit);
  // m_ofOut << "\t<cvParam accession=\"MS:1001412\" cvRef=\"PSI-MS\" "
  //          "unitCvRef=\"UO\" "
  //        "unitName=\"parts per million\" unitAccession=\"UO:0000169\" "
  //      "value=\"20.0\" name=\"search tolerance plus value\"/>\n";

  strKey = "spectrum, parent monoisotopic mass error minus";
  _x.get(strKey, strValue);

  m_outputStream->writeCvParamUo("MS:1001413",
                                 "PSI-MS",
                                 "search tolerance minus value",
                                 strValue.c_str(),
                                 precision_unit);
  // m_ofOut << "\t<cvParam accession=\"MS:1001413\" cvRef=\"PSI-MS\" "
  //          "unitCvRef=\"UO\" "
  //        "unitName=\"parts per million\" unitAccession=\"UO:0000169\" "
  //      "value=\"20.0\" name=\"search tolerance minus value\"/>\n";

  m_outputStream->writeEndElement();
  // m_ofOut << "\t</ParentTolerance>\n";

  m_outputStream->writeStartElement("Threshold");
  // m_ofOut << "\t<Threshold>\n";
  m_outputStream->writeCvParam("PSI-MS", "MS:1001494", "no threshold", "");

  m_outputStream->writeEndElement();
  // m_ofOut << "\t</Threshold>\n";

  m_outputStream->writeEndElement();
  // m_ofOut << "\t</SpectrumIdentificationProtocol>\n";

  m_outputStream->writeEndElement();
  // m_ofOut << "</AnalysisProtocolCollection>\n";
  return true;
}

// Create the DataCollection portion of the mzIndentML file

bool
mzid_report::data_collection(vector<mspectrum> &_vs,
                             vector<string> &_vp,
                             XmlParameter &_x)
{

  m_outputStream->writeStartElement("DataCollection");
  // m_ofOut
  // << "<DataCollection
  // xmlns=\"http://psidev.info/psi/pi/mzIdentML/1.1\">\n";

  add_inputs(mp_msFileAccessor, _vs, _vp, _x);
  add_analysis(_vs, _vp, _x);


  m_outputStream->writeEndElement();
  // m_ofOut << "</DataCollection>\n";

  return true;
}

// Create the AnalysisData portion of the mzIndentML file
// Used by the data_collection method

bool
mzid_report::add_analysis(vector<mspectrum> &_vs,
                          vector<string> &_vp,
                          XmlParameter &_x)
{

  m_outputStream->writeStartElement("AnalysisData");
  // m_ofOut << "<AnalysisData>\n";


  m_outputStream->writeStartElement("SpectrumIdentificationList");
  m_outputStream->writeAttribute("id", "SI_LIST_1");
  // m_ofOut << "<SpectrumIdentificationList id=\"SI_LIST_1\">\n";

  m_outputStream->writeStartElement("FragmentationTable");
  // m_ofOut << " <FragmentationTable>\n";
  /*
      <FragmentationTable>
      */

  m_outputStream->writeStartElement("Measure");
  m_outputStream->writeAttribute("id", "Measure_MZ");
  // m_ofOut << "<Measure id=\"Measure_MZ\">\n";

  m_outputStream->writeCvParamUo("MS:1001225",
                                 "PSI-MS",
                                 "product ion m/z",
                                 "",
                                 "PSI-MS",
                                 "MS:1000040",
                                 "m/z");
  m_outputStream->writeEndElement();
  // m_ofOut << "</Measure>\n";
  /*  <Measure id="Measure_MZ">
        <cvParam accession="MS:1001225" cvRef="PSI-MS" unitCvRef="PSI-MS"
    unitName="m/z" unitAccession="MS:1000040" name="product ion m/z"/>
    </Measure>*/

  m_outputStream->writeStartElement("Measure");
  m_outputStream->writeAttribute("id", "Measure_Int");
  m_outputStream->writeCvParamUo("MS:1001226",
                                 "PSI-MS",
                                 "product ion intensity",
                                 "",
                                 "PSI-MS",
                                 "MS:1000131",
                                 "number of counts");
  m_outputStream->writeEndElement();
  // m_ofOut << "</Measure>\n";
  /*
    <Measure id="Measure_Int">
        <cvParam accession="MS:1001226" cvRef="PSI-MS" unitCvRef="PSI-MS"
unitName="number of counts" unitAccession="MS:1000131" name="product ion
intensity"/>
*/


  m_outputStream->writeStartElement("Measure");
  m_outputStream->writeAttribute("id", "Measure_Error");
  m_outputStream->writeCvParamUo("MS:1001227",
                                 "PSI-MS",
                                 "product ion m/z error",
                                 "",
                                 "PSI-MS",
                                 "MS:1000040",
                                 "m/z");
  m_outputStream->writeEndElement();
  // m_ofOut << "</Measure>\n";
  /*
    </Measure>
    <Measure id="Measure_Error">
        <cvParam accession="MS:1001227" cvRef="PSI-MS" unitCvRef="PSI-MS"
unitName="m/z" unitAccession="MS:1000040" name="product ion m/z error"/>
    </Measure>
</FragmentationTable>*/
  // m_ofOut << "<cvParam accession=\"MS:1001225\" cvRef=\"PSI-MS\" "
  //          "unitCvRef=\"PSI-MS\" unitName=\"m/z\" "
  //        "unitAccession=\"MS:1000040\" name=\"product ion m/z\"/>\n";
  m_outputStream->writeEndElement();
  // m_ofOut << "</FragmentationTable>\n";
  size_t a    = 0;
  size_t b    = 0;
  size_t c    = 0;
  char *pLine = new char[1024];
  int iScan   = 0;
  string strScan;
  size_t tPos    = 0;
  double dProton = 1.007276;
  vector<QString> vstrPeptides;
  vector<size_t> vtB;
  vector<size_t> vtC;
  string strPep;
  while(a < _vs.size())
    {
      if(_vs[a].m_vseqBest.empty())
        {
          a++;
          continue;
        }
      iScan = (int)(_vs[a].m_tId);
      tPos  = _vs[a].m_strDescription.find("scan=");
      if(tPos != _vs[a].m_strDescription.npos)
        {
          tPos += 5;
          strScan = _vs[a].m_strDescription.substr(
            tPos, _vs[a].m_strDescription.length() - tPos + 1);
          iScan = atoi(strScan.c_str());
        }

      m_outputStream->writeStartElement("SpectrumIdentificationResult");
      m_outputStream->writeAttribute("spectraData_ref", "SID_1");
      // m_ofOut << "<SpectrumIdentificationResult spectraData_ref=\"SID_1\" ";

      m_outputStream->writeAttribute("spectrumID",
                                     _vs[a].m_strDescription.c_str());

      m_outputStream->writeAttribute("id", QString("SIR_%1").arg(iScan));
      //  m_ofOut << "spectrumID=\"" << _vs[a].m_strDescription << "\" ";
      // m_ofOut << "id=\"SIR_" << iScan << "\">\n";
      b = 0;
      vstrPeptides.clear();
      vtC.clear();
      vtB.clear();
      while(b < _vs[a].m_vseqBest.size())
        {
          c = 0;
          while(c < _vs[a].m_vseqBest[b].m_vDomains.size())
            {
              QString domain_id =
                QString("%1_%2_%3").arg(_vs[a].m_tId).arg(b + 1).arg(c + 1);
              auto it = m_mapIdsToPeptides.find(domain_id);
              if(it == m_mapIdsToPeptides.end())
                {
                  qDebug() << "domain_id " << domain_id << " not found";
                  c++;
                  continue;
                }
              // strPep = m_mapIdsToPeptides.find(pLine)->second;
              vstrPeptides.push_back(it->second);
              vtB.push_back(b);
              vtC.push_back(c);
              c++;
            }
          b++;
        }
      size_t tOut = 0;
      QString strCurrentPeptide;
      size_t x = 0;
      while(tOut < vstrPeptides.size())
        {
          x = 0;
          while(x < vstrPeptides.size() && vstrPeptides[x].isEmpty())
            {
              x++;
            }
          if(x == vstrPeptides.size())
            {
              break;
            }
          strCurrentPeptide = vstrPeptides[x];
          x                 = 0;
          b                 = 0;

          m_outputStream->writeStartElement("SpectrumIdentificationItem");
          m_outputStream->writeAttribute("passThreshold", "true");
          m_outputStream->writeAttribute("rank", "1");
          m_outputStream->writeAttribute(

            "peptide_ref", QString("Pep_%1").arg(strCurrentPeptide));
          //   m_ofOut << "<SpectrumIdentificationItem passThreshold=\"true\" ";
          // m_ofOut << "rank=\"1\" peptide_ref=\"Pep_" << strCurrentPeptide
          // << "\" ";
          /* sprintf(
             pLine,
             "%.4lf",
             dProton +
               (_vs[a].m_vseqBest[vtB[x]].m_vDomains[vtC[x]].m_dMH - dProton) /
                 (double)(_vs[a].m_fZ));
          */
          m_outputStream->writeAttribute(

            "calculatedMassToCharge",
            mreport::massStr(
              dProton +
              (_vs[a].m_vseqBest[vtB[x]].m_vDomains[vtC[x]].m_dMH - dProton) /
                (double)(_vs[a].m_fZ)));
          // m_ofOut << "calculatedMassToCharge=\"" << pLine << "\" ";
          // sprintf(pLine,
          //       "%.4lf",
          //     dProton + (_vs[a].m_dMH - dProton) / (double)(_vs[a].m_fZ));
          m_outputStream->writeAttribute(

            "experimentalMassToCharge",
            mreport::massStr(dProton +
                             (_vs[a].m_dMH - dProton) / (double)(_vs[a].m_fZ)));

          //  m_ofOut << "experimentalMassToCharge=\"" << pLine << "\" ";

          m_outputStream->writeAttribute("chargeState",
                                         QString::number(_vs[a].m_fZ));
          // m_ofOut << "chargeState=\"" << (int)_vs[a].m_fZ << "\" ";

          m_outputStream->writeAttribute(

            "id", QString("SII_%1_%2").arg(_vs[a].m_tId).arg(x));
          // m_ofOut << "id=\"SII_" << _vs[a].m_tId << "_" << x << "\">\n";
          while(b < _vs[a].m_vseqBest.size())
            {
              c = 0;
              while(c < _vs[a].m_vseqBest[b].m_vDomains.size())
                {
                  QString pep_ev_id =
                    QString("%1_%2_%3").arg(_vs[a].m_tId).arg(b + 1).arg(c + 1);
                  if(strCurrentPeptide == vstrPeptides[x])
                    {

                      m_outputStream->writeStartElement("PeptideEvidenceRef");

                      m_outputStream->writeAttribute(

                        "peptideEvidence_ref",
                        QString("PepEv_%1").arg(pep_ev_id));
                      m_outputStream->writeEndElement();
                      // m_ofOut
                      // << "<PeptideEvidenceRef peptideEvidence_ref=\"PepEv_"
                      // << strPeptide << "\"/>\n";
                      tOut++;
                      vstrPeptides[x].clear();
                    }
                  x++;
                  c++;
                }
              b++;
            }
          /*sprintf(pLine,
                  "%.1e",
                  _vs[a].m_hHyper.expect(m_Score.hconvert(
                    _vs[a].m_vseqBest[0].m_vDomains[0].m_fHyper)));
          */
          m_outputStream->writeCvParam(
            "PSI-MS",
            "MS:1001330",
            "X!Tandem:expect",
            QString::number(_vs[a].m_hHyper.expect(
              m_Score.hconvert(_vs[a].m_vseqBest[0].m_vDomains[0].m_fHyper))));
          // m_ofOut
          // << "<cvParam accession=\"MS:1001330\" cvRef=\"PSI-MS\" value=\""
          // << pLine << "\" name=\"X\\!Tandem:expect\"/>\n";

          //  m_Score.report_score(pLine,
          //                     _vs[a].m_vseqBest[0].m_vDomains[0].m_fHyper);

          m_outputStream->writeCvParam(
            "PSI-MS",
            "MS:1001331",
            "X!Tandem:hyperscore",
            QString::number(
              m_Score.hconvert(_vs[a].m_vseqBest[0].m_vDomains[0].m_fHyper),
              'f',
              1));

          // m_ofOut
          //<< "<cvParam accession=\"MS:1001331\" cvRef=\"PSI-MS\" value=\""
          //<< pLine << "\" name=\"X\\!Tandem:hyperscore\"/>\n";
          m_outputStream->writeEndElement();
          // m_ofOut << "</SpectrumIdentificationItem>\n";
        }

      // id: MS:1003062
      // name: library spectrum index
      m_outputStream->writeCvParam("PSI-MS",
                                   "MS:1003062",
                                   "library spectrum index",
                                   QString::number(_vs[a].m_tId));
      // m_ofOut << "<cvParam accession=\"MS:1001115\" cvRef=\"PSI-MS\"
      // value=\""
      //       << iScan << "\" name=\"scan number(s)\"/>\n";


      //[Term]
      // id: MS:1000894
      // name: retention time
      // def: "A time interval from the start of chromatography when an
      // analyte exits a chromatographic column." [PSI:MS]


      //[Term]
      // id: UO:0000010
      // name: second
      m_outputStream->writeCvParamUo(
        "PSI-MS",
        "MS:1000894",
        "retention time",
        QString::number(_vs[a].m_retentionTimeInSeconds, 'f', 10),
        "UO",
        "UO:0000010",
        "second");

      m_outputStream->writeEndElement();
      // m_ofOut << "</SpectrumIdentificationResult>\n";

      a++;
    }

  m_outputStream->writeEndElement();

  m_outputStream->writeEndElement();
  // m_ofOut << "</SpectrumIdentificationList>\n</AnalysisData>\n";
  delete[] pLine;
  return true;
}

// Create the Inputs portion of the mzIndentML file
// Used by the data_collection method

bool
mzid_report::add_inputs(const pappso::MsFileAccessor *msfile,
                        vector<mspectrum> &_vs,
                        vector<string> &_vp,
                        XmlParameter &_x)
{

  m_outputStream->writeStartElement("Inputs");
  // m_ofOut << "<Inputs>\n";
  string strKey = "spectrum, path";
  size_t a      = 0;
  string strValue;
  size_t tPos = 0;
  while(a < _vp.size())
    {


      m_outputStream->writeStartElement("SearchDatabase");

      m_outputStream->writeAttribute("location", _vp[a].c_str());

      m_outputStream->writeAttribute("id", QString("SearchDB_%1").arg(a));
      // m_ofOut << "<SearchDatabase location=\"" << _vp[a] << "\"
      // id=\"SearchDB_"
      //       << a << "\">\n";

      m_outputStream->writeStartElement("FileFormat");
      // m_ofOut << "\t<FileFormat>\n";
      m_outputStream->writeCvParam("PSI-MS", "MS:1001348", "FASTA format", "");
      // m_ofOut << "\t\t<cvParam accession=\"MS:1001348\" cvRef=\"PSI-MS\" "
      //          "name=\"FASTA format\"/>\n";

      m_outputStream->writeEndElement();
      // m_ofOut << "\t</FileFormat>\n";

      m_outputStream->writeStartElement("DatabaseName");
      // m_ofOut << "\t<DatabaseName>\n";
      tPos     = _vp[a].find_last_of('/');
      strValue = _vp[a];
      if(tPos != _vp[a].npos)
        {
          tPos++;
          strValue = _vp[a].substr(tPos, _vp[a].size() - tPos + 1);
        }
      else
        {
          tPos = _vp[a].find_last_of('\\');
          if(tPos != _vp[a].npos)
            {
              tPos++;
              strValue = _vp[a].substr(tPos, _vp[a].size() - tPos + 1);
            }
        }

      m_outputStream->writeUserParam("DatabaseName", strValue.c_str());
      // m_ofOut << "\t\t<userParam name=\"" << strValue << "\"/>\n";

      m_outputStream->writeEndElement();
      // m_ofOut << "\t</DatabaseName>\n";
      m_outputStream->writeCvParam(
        "PSI-MS", "MS:1001197", "DB composition target+decoy", "");
      // m_ofOut << "\t<cvParam accession=\"MS:1001197\" cvRef=\"PSI-MS\" "
      //          "name=\"DB composition target+decoy\"/>\n";
      strKey = "output, mzid decoy DB accession regexp";
      _x.get(strKey, strValue);
      if(strValue.size() > 0)
        {

          m_outputStream->writeCvParam("PSI-MS",
                                       "MS: 1001283",
                                       "decoy DB accession regexp",
                                       strValue.c_str());
          //   m_ofOut
          //   << "\t<cvParam accession=\"MS:1001283\" cvRef=\"PSI-MS\"
          //   value=\""
          // << strValue << "\" name=\"decoy DB accession regexp\"/>\n";
        }
      else
        {

          m_outputStream->writeCvParam(
            "PSI-MS", "MS: 1001283", "decoy DB accession regexp", "^XXX");
          //  m_ofOut << "\t<cvParam accession=\"MS:1001283\" cvRef=\"PSI-MS\" "
          //           "value=\"^XXX\" name=\"decoy DB accession regexp\"/>\n";
        }

      m_outputStream->writeCvParam(
        "PSI-MS", "MS: 1001195", "decoy DB type reverse", "");
      // m_ofOut << "\t<cvParam accession=\"MS:1001195\" cvRef=\"PSI-MS\" "
      //          "name=\"decoy DB type reverse\"/>\n";

      m_outputStream->writeEndElement();
      //      m_ofOut << "\t</SearchDatabase>\n";
      a++;
    }
  strKey = "spectrum, path";
  _x.get(strKey, strValue);

  m_outputStream->writeStartElement("SpectraData");

  if(mp_msFileAccessor != nullptr)
    {
      m_outputStream->writeAttribute("location",
                                     mp_msFileAccessor->getFileName());
    }
  else
    {
      m_outputStream->writeAttribute("location", strValue.c_str());
    }
  // m_ofOut << "\t<SpectraData location=\"" << strValue << "\" ";

  if(m_sampleName.isEmpty())
    {
      m_outputStream->writeAttribute("name",
                                     QFileInfo(strValue.c_str()).baseName());
    }
  else
    {
      m_outputStream->writeAttribute("name", m_sampleName);
    }
  m_outputStream->writeAttribute("id", "SID_1");

  // m_ofOut << "name=\"" << strValue << "\" id=\"SID_1\">\n";

  m_outputStream->writeStartElement("FileFormat");
  // m_ofOut << "\t<FileFormat>\n";
  if(mp_msFileAccessor != nullptr)
    {
      const pappso::OboPsiModTerm term =
        mp_msFileAccessor->getOboPsiModTermFileFormat();
      m_outputStream->writeCvParam(term, "");
    }
  else
    {
      m_outputStream->writeCvParam(
        "PSI-MS", "MS:1000544", "Conversion to mzML", "");
    }
  // m_ofOut << "\t\t<cvParam accession=\"MS:1000058\" cvRef=\"PSI-MS\" "
  //          "name=\"mzML file\"/>\n";

  m_outputStream->writeEndElement();
  // m_ofOut << "\t</FileFormat>\n";

  m_outputStream->writeStartElement("SpectrumIDFormat");
  // m_ofOut << "\t<SpectrumIDFormat>\n";

  if(mp_msFileAccessor != nullptr)
    {
      const pappso::OboPsiModTerm term =
        mp_msFileAccessor->getOboPsiModTermNativeIDFormat();
      m_outputStream->writeCvParam(term, "");
    }
  else
    {
      m_outputStream->writeCvParam(
        "PSI-MS", "MS:1000824", "no nativeID format", "");
    }
  // m_ofOut << " \t\t<cvParam accession=\"MS:1000768\" cvRef=\"PSI-MS\" "
  //          "name=\"Thermo nativeID format\"/>\n";

  m_outputStream->writeEndElement();
  // m_ofOut << "\t</SpectrumIDFormat>\n";

  m_outputStream->writeEndElement();
  /// m_ofOut << "\t</SpectraData>\n";

  m_outputStream->writeEndElement();
  // m_ofOut << "</Inputs>\n";

  return true;
}

// Create the residue modification portion of the mzIndentML file
// Used by the analysis_protocol_collection method

bool
mzid_report::analysis_mods(string &_v, bool _b)
{
  string strValue = _v;
  char *pMass     = new char[256];
  char cRes       = '\0';
  size_t tA       = 0;
  size_t tB       = 0;
  size_t tLength  = strValue.length();
  string strUni;
  string strUniDescription;
  while(tA < tLength)
    {
      strcpy(pMass, "");
      tB = 0;
      while(strValue[tA] != '@' && tA < tLength)
        {
          pMass[tB] = strValue[tA];
          tB++;
          tA++;
        }
      pMass[tB] = '\0';
      tA++;
      cRes = strValue[tA];

      m_outputStream->writeStartElement("SearchModification");

      m_outputStream->writeAttribute("residues", QString(cRes));

      m_outputStream->writeAttribute("massDelta", pMass);

      // m_outputStream->writeAttribute("fixedMod",
      // mreport::massStr(pMass));
      //   m_ofOut << "\t\t<SearchModification residues=\"" << cRes
      //         << "\" massDelta=\"" << atof(pMass) << "\" fixedMod=\"";
      if(_b)
        {

          m_outputStream->writeAttribute("fixedMod", "true");
          // m_ofOut << "true\">\n";
        }
      else
        {

          m_outputStream->writeAttribute("fixedMod", "false");
          // m_ofOut << "false\">\n";
        }
      pappso::AaModificationP pmod = getPsiMod(atof(pMass));
      if(pmod != nullptr)
        {

          m_outputStream->writeCvParam(pmod);

          // m_ofOut << "\t\t\t<cvParam accession=\"" << strUni
          //       << "\" cvRef=\"UNIMOD\" name=\"" << strUniDescription
          //     << "\"/>\n";
        }

      m_outputStream->writeEndElement();
      //      m_ofOut << "\t\t</SearchModification>\n";
      while(strValue[tA] != ',' && tA < tLength)
        {
          tA++;
        }
      tA++;
    }
  delete[] pMass;
  return true;
}

// Create the DBSequence entries in the mzIndentML file
// Used by the sequence_collection method

bool
mzid_report::add_dbsequence(vector<mspectrum> &_vs)
{
  if(m_outputStream->hasError())
    {
      return false;
    }
  set<size_t> setUids;
  set<size_t>::iterator itUid;
  const size_t tSize = _vs.size();
  size_t a           = 0;
  size_t b           = 0;
  size_t tUid        = 0;
  QString strLabel;
  QString strDesc;
  while(a < tSize)
    {
      if(_vs[a].m_vseqBest.empty())
        {
          a++;
          continue;
        }
      b = 0;
      while(b < _vs[a].m_vseqBest.size())
        {
          tUid  = _vs[a].m_vseqBest[b].m_tUid;
          itUid = setUids.find(tUid);
          if(itUid == setUids.end())
            {
              parse_description(
                _vs[a].m_vseqBest[b].m_strDes, strLabel, strDesc);

              QString accession(strLabel);
              bool is_decoy = false;
              if((m_enumReverseSearchType != EnumReverseSearchType::no_decoy) &&
                 (QString(_vs[a].m_vseqBest[b].m_strDes.c_str())
                    .endsWith(m_reversedProteinSequenceStringEndsWith)))
                {
                  is_decoy = true;
                }
              if(is_decoy)
                {
                  if(accession.endsWith(
                       m_reversedProteinSequenceStringEndsWith))
                    {
                    }
                  else
                    {
                      accession.append(m_reversedProteinSequenceStringEndsWith);
                    }
                }


              m_outputStream->writeDBSequence(
                QString("DBSeq%1").arg(tUid),
                QString("SearchDB_%1").arg(_vs[a].m_vseqBest[b].m_siPath),
                accession,
                strDesc,
                _vs[a].m_vseqBest[b].m_strSeq.c_str(),
                is_decoy);
              // m_ofOut << "</DBSequence>\n";
              setUids.insert(tUid);
            }
          b++;
        }
      a++;
    }
  return true;
}

// Create the PeptideEvidence entries in the mzIndentML file
// Used by the sequence_collection method

bool
mzid_report::add_peptide_evidence(vector<mspectrum> &_vs)
{
  if(m_outputStream->hasError())
    {
      return false;
    }
  const size_t tSize = _vs.size();
  size_t a           = 0;
  size_t b           = 0;
  size_t c           = 0;
  size_t tUid        = 0;
  char *pLine        = new char[1024];
  string strPep;
  //	std::regex rgxReverse(m_strRegex);
  string strRev = m_strRegex.substr(1, m_strRegex.npos);
  while(a < tSize)
    {
      if(_vs[a].m_vseqBest.empty())
        {
          a++;
          continue;
        }
      b = 0;
      while(b < _vs[a].m_vseqBest.size())
        {
          tUid = _vs[a].m_vseqBest[b].m_tUid;
          c    = 0;
          while(c < _vs[a].m_vseqBest[b].m_vDomains.size())
            {

              QString domain_id =
                QString("%1_%2_%3").arg(_vs[a].m_tId).arg(b + 1).arg(c + 1);
              if(m_mapIdsToPeptides.find(domain_id) == m_mapIdsToPeptides.end())
                {
                  qDebug() << domain_id << "<br />\n";
                  c++;
                  continue;
                }
              auto it = m_mapIdsToPeptides.find(domain_id);
              if(it == m_mapIdsToPeptides.end())
                {
                  qDebug() << "domain id " << domain_id << " not found";
                  c++;
                  continue;
                }
              strPep = it->second.toStdString();
              //				if(std::regex_match(_vs[a].m_vseqBest[b].m_strDes,rgxReverse))
              //{

              m_outputStream->writeStartElement("PeptideEvidence");
              bool is_decoy = false;
              if(_vs[a].m_vseqBest[b].m_strDes.find(strRev) == 0)
                {
                  is_decoy = true;
                }
              if((m_enumReverseSearchType != EnumReverseSearchType::no_decoy) &&
                 (QString(_vs[a].m_vseqBest[b].m_strDes.c_str())
                    .endsWith(m_reversedProteinSequenceStringEndsWith)))
                {
                  is_decoy = true;
                }
              if(is_decoy)
                {
                  m_outputStream->writeAttribute("isDecoy", "true");
                }
              else
                {
                  m_outputStream->writeAttribute("isDecoy", "false");
                }

              m_outputStream->writeAttribute(
                "start",
                QString::number(_vs[a].m_vseqBest[b].m_vDomains[c].m_lS + 1));
              m_outputStream->writeAttribute(
                "end",
                QString::number(_vs[a].m_vseqBest[b].m_vDomains[c].m_lE + 1));
              m_outputStream->writeAttribute(
                "pre",
                QString(_vs[a].m_vseqBest[b].getPre(c, 1).c_str())
                  .replace("[", "-"));
              // m_ofOut << "\" pre=\"" << strPre;
              m_outputStream->writeAttribute(
                "post",
                QString(_vs[a].m_vseqBest[b].getPost(c, 1).c_str())
                  .replace("]", "-"));
              // m_ofOut << "<PeptideEvidence isDecoy=\"true\" post=\""
              //       << strPost;
              m_outputStream->writeAttribute(

                "peptide_ref", QString("Pep_%1").arg(strPep.c_str()));
              // m_ofOut << "\" peptide_ref=\"Pep_" <<
              // strPep;
              m_outputStream->writeAttribute("dBSequence_ref",
                                             QString("DBSeq%1").arg(tUid));
              // m_ofOut << "\" dBSequence_ref=\"DBSeq"
              // << tUid;
              m_outputStream->writeAttribute(
                "id", QString("PepEv_%1").arg(domain_id));
              m_outputStream->writeEndElement();
              // m_ofOut << "\" id=\"PepEv_" << strId
              // << "\"/>\n";
              c++;
            }
          b++;
        }
      a++;
    }
  delete[] pLine;
  return true;
}

// Create the Peptide entries in the mzIndentML file
// Used by the sequence_collection method

bool
mzid_report::add_peptides(vector<mspectrum> &_vs)
{

  if(m_outputStream->hasError())
    {
      return false;
    }
  size_t a = 0;
  size_t b = 0;
  size_t c = 0;
  size_t d = 0;
  string strSeq;
  string strUni;
  string strUniDesc;
  map<string, string> mapPeptidesToIds;
  map<string, string>::iterator itPtoI;
  string strOutput;
  // string strId;
  while(a < _vs.size())
    {
      if(_vs[a].m_vseqBest.empty())
        {
          a++;
          continue;
        }
      b = 0;
      while(b < _vs[a].m_vseqBest.size())
        {
          c         = 0;
          strOutput = "";
          while(c < _vs[a].m_vseqBest[b].m_vDomains.size())
            {
              strSeq = _vs[a].m_vseqBest[b].getDomainSequence(c);

              QString strSeqKey = strSeq.c_str();
              d                 = 0;
              while(d < _vs[a].m_vseqBest[b].m_vDomains[c].m_vAa.size())
                {
                  // strOutput += "\t<Modification
                  // monoisotopicMassDelta=\""; sprintf( pLine,
                  // "%.4lf",
                  //_vs[a].m_vseqBest[b].m_vDomains[c].m_vAa[d].m_dMod);
                  strSeqKey += " ";
                  strSeqKey += mreport::massStr(
                    _vs[a].m_vseqBest[b].m_vDomains[c].m_vAa[d].m_dMod);
                  // strOutput += pLine;
                  // strOutput += "\" location=\"";
                  // sprintf(
                  // pLine,
                  //"%i",
                  //_vs[a].m_vseqBest[b].m_vDomains[c].m_vAa[d].m_lPos -
                  //_vs[a].m_vseqBest[b].m_vDomains[c].m_lS + 1);
                  strSeqKey += " ";
                  strSeqKey += QString::number(
                    _vs[a].m_vseqBest[b].m_vDomains[c].m_vAa[d].m_lPos -
                    _vs[a].m_vseqBest[b].m_vDomains[c].m_lS + 1);
                  // strOutput += pLine;
                  // strOutput += "\">\n";
                  d++;
                }

              QString domainId =
                QString("%1_%2_%3").arg(_vs[a].m_tId).arg(b + 1).arg(c + 1);
              itPtoI = mapPeptidesToIds.find(strSeqKey.toStdString());
              if(itPtoI == mapPeptidesToIds.end())
                { // if new peptide
                  m_outputStream->writeStartElement("Peptide");
                  m_outputStream->writeAttribute("id",
                                                 QString("Pep_%1_%2_%3")
                                                   .arg(_vs[a].m_tId)
                                                   .arg(b + 1)
                                                   .arg(c + 1));
                  // sprintf(pLine, "<Peptide id=\"Pep_");
                  // strOutput = pLine;
                  // sprintf(pLine,
                  //       "%i_%i_%i",
                  //     (int)_vs[a].m_tId,
                  //   (int)(b + 1),
                  // (int)(c + 1));
                  // strId = pLine;
                  // strOutput += pLine;
                  // sprintf(pLine, "\">\n");
                  // strOutput += pLine;
                  m_outputStream->writeStartElement("PeptideSequence");
                  // strOutput += "\t<PeptideSequence>";
                  m_outputStream->writeCharacters(strSeq.c_str());
                  // strOutput += strSeq;
                  m_outputStream->writeEndElement();
                  // strOutput += "</PeptideSequence>\n";
                  d = 0;
                  while(d < _vs[a].m_vseqBest[b].m_vDomains[c].m_vAa.size())
                    {
                      m_outputStream->writeStartElement("Modification");
                      m_outputStream->writeAttribute(

                        "monoisotopicMassDelta",
                        mreport::massStr(
                          _vs[a].m_vseqBest[b].m_vDomains[c].m_vAa[d].m_dMod));
                      // strOutput += "\t<Modification
                      // monoisotopicMassDelta=\""; sprintf( pLine,
                      // "%.4lf",
                      //_vs[a].m_vseqBest[b].m_vDomains[c].m_vAa[d].m_dMod);
                      // strOutput += pLine;

                      m_outputStream->writeAttribute(

                        "location",
                        QString::number(
                          _vs[a].m_vseqBest[b].m_vDomains[c].m_vAa[d].m_lPos -
                          _vs[a].m_vseqBest[b].m_vDomains[c].m_lS + 1));


                      QChar aa_source(
                        _vs[a].m_vseqBest[b].m_vDomains[c].m_vAa[d].m_cRes);
                      m_outputStream->writeAttribute("residues", aa_source);
                      QChar aa_mut(
                        _vs[a].m_vseqBest[b].m_vDomains[c].m_vAa[d].m_cMut);

                      if(aa_mut != '\0' && aa_mut != aa_source)
                        {
                          // point mutation coded with one removal and one
                          // insertion
                          m_outputStream->writeCvParam(
                            pappso::AaModification::
                              getInstanceRemovalAccessionByAaLetter(aa_source));
                          m_outputStream->writeCvParam(
                            pappso::AaModification::
                              getInstanceInsertionAccessionByAaLetter(aa_mut));
                        }
                      // strOutput += "\" location=\"";
                      // sprintf(
                      // pLine,
                      //"%i",
                      //_vs[a].m_vseqBest[b].m_vDomains[c].m_vAa[d].m_lPos -
                      //_vs[a].m_vseqBest[b].m_vDomains[c].m_lS + 1);
                      // strOutput += pLine;
                      // strOutput += "\">\n";
                      pappso::AaModificationP pmod = getPsiMod(
                        _vs[a].m_vseqBest[b].m_vDomains[c].m_vAa[d].m_dMod);
                      if(pmod != nullptr)
                        {
                          m_outputStream->writeCvParam(pmod);
                          // strOutput += "\t\t<cvParam accession=\"";
                          // strOutput += strUni;
                          // strOutput += "\" cvRef=\"UNIMOD\" name=\"";
                          // strOutput += strUniDesc;
                          // strOutput += "\"/>\n";
                        }
                      m_outputStream->writeEndElement();
                      // strOutput += "\t</Modification>\n";
                      d++;
                    }
                  m_outputStream->writeEndElement();

                  // strOutput += "</Peptide>\n";

                  // m_ofOut << strOutput;
                  m_mapIdsToPeptides[domainId] = domainId;
                  mapPeptidesToIds[strSeqKey.toStdString()] =
                    domainId.toStdString();
                }
              else
                {
                  m_mapIdsToPeptides[domainId] =
                    QString(itPtoI->second.c_str());
                }
              c++;
            }
          b++;
        }
      a++;
    }
  return true;
}

// Parses FASTA description strings into accession numbers and descriptions

bool
mzid_report::parse_description(const string &_s, QString &_acc, QString &_desc)
{
  QStringList description_list =
    QString(_s.c_str()).split(" ", Qt::SkipEmptyParts);
  if(description_list.size() == 0)
    return false;
  if(description_list.size() > 1)
    {
      _acc = description_list[0];
      description_list.remove(0);
      _desc = description_list.join(" ");
    }
  else
    {
      _acc  = description_list[0];
      _desc = "";
    }
  return true;
}


// Creates a map of modification masses to UniMod identifiers and descriptions
// Called on creation of the mzid_report object: it does not need to be
// explicitly called

bool
mzid_report::load_unimod(void)
{
  int iValue;
  m_mapAaModificationP.clear();
  // m_mapUnimod.clear();
  // m_mapUnimodDescriptions.clear();

  // MOD:00397 iodoacetamide derivatized residue
  pappso::AaModificationP pmod =
    pappso::AaModification::getInstance("MOD:00397");
  iValue                       = get_unimod_mass(pmod->getMass());
  m_mapAaModificationP[iValue] = pmod;

  // id: MOD:00425 name: monohydroxylated residue
  pmod   = pappso::AaModification::getInstance("MOD:00425");
  iValue = get_unimod_mass(pmod->getMass());
  m_mapAaModificationP[iValue] = pmod;

  // id: MOD:00428 name: dihydroxylated residue
  pmod   = pappso::AaModification::getInstance("MOD:00428");
  iValue = get_unimod_mass(pmod->getMass());
  m_mapAaModificationP[iValue] = pmod;

  // id: MOD:01409 name: trihydroxylated residue
  pmod   = pappso::AaModification::getInstance("MOD:01409");
  iValue = get_unimod_mass(pmod->getMass());
  m_mapAaModificationP[iValue] = pmod;

  // id: MOD:00400 name: deamidated residue
  pmod   = pappso::AaModification::getInstance("MOD:00400");
  iValue = get_unimod_mass(pmod->getMass());
  m_mapAaModificationP[iValue] = pmod;


  // id: MOD:00704 name: dehydrated residue
  pmod   = pappso::AaModification::getInstance("MOD:00704");
  iValue = get_unimod_mass(pmod->getMass());
  m_mapAaModificationP[iValue] = pmod;


  // id: MOD:01160 name: deaminated residue
  pmod   = pappso::AaModification::getInstance("MOD:01160");
  iValue = get_unimod_mass(pmod->getMass());
  m_mapAaModificationP[iValue] = pmod;


  // id: MOD:00394 name: monoacetylated residue
  pmod   = pappso::AaModification::getInstance("MOD:00394");
  iValue = get_unimod_mass(pmod->getMass());
  m_mapAaModificationP[iValue] = pmod;


  // id: MOD:00696 name: phosphorylated residue
  pmod   = pappso::AaModification::getInstance("MOD:00696");
  iValue = get_unimod_mass(pmod->getMass());
  m_mapAaModificationP[iValue] = pmod;

  return true;
}

// Returns the UniMod identifier and description string, given a modification
// mass _m in Daltons

pappso::AaModificationP
mzid_report::getPsiMod(double _m) const
{
  int iValue                   = get_unimod_mass(_m);
  pappso::AaModificationP pmod = nullptr;
  auto itU                     = m_mapAaModificationP.find(iValue);
  if(itU != m_mapAaModificationP.end())
    {
      pmod = itU->second;
      itU  = m_mapAaModificationP.find(iValue);
      if(itU != m_mapAaModificationP.end())
        {
          pmod = itU->second;
        }
    }
  else
    {
      return nullptr;
    }
  return pmod;
}
