gt:           if (msmsScanNumber > 0)
context: /*
   * Copyright 2006-2018 The MZmine 2 Development Team
   *
   * This file is part of MZmine 2.
   *
   * MZmine 2 is free software; you can redistribute it and/or modify it under the terms of the GNU
   * General Public License as published by the Free Software Foundation; either version 2 of the
   * License, or (at your option) any later version.
   *
   * MZmine 2 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 MZmine 2; if not,
   * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
   * USA
   */
  /*
   * This module was prepared by Abi Sarvepalli, Christopher Jensen, and Zheng Zhang at the Dorrestein
   * Lab (University of California, San Diego).
   *
   * It is freely available under the GNU GPL licence of MZmine2.
   *
   * For any questions or concerns, please refer to:
   * https://groups.google.com/forum/#!forum/molecular_networking_bug_reports
   *
   * Credit to the Du-Lab development team for the initial commitment to the MGF export module.
   */
  
  package net.sf.mzmine.modules.peaklistmethods.io.gnpsexport.fbmn;
  
  import java.io.File;
  import java.io.FileWriter;
  import java.io.IOException;
  import java.text.DecimalFormat;
  import java.text.MessageFormat;
  import java.text.NumberFormat;
  import java.util.Arrays;
  import java.util.logging.Level;
  import java.util.logging.Logger;
  import java.util.regex.Pattern;
  import net.sf.mzmine.datamodel.DataPoint;
  import net.sf.mzmine.datamodel.Feature;
  import net.sf.mzmine.datamodel.MassList;
  import net.sf.mzmine.datamodel.PeakList;
  import net.sf.mzmine.datamodel.PeakListRow;
  import net.sf.mzmine.datamodel.Scan;
  import net.sf.mzmine.datamodel.impl.SimpleFeature;
  import net.sf.mzmine.datamodel.impl.SimplePeakListRow;
  import net.sf.mzmine.main.MZmineCore;
  import net.sf.mzmine.modules.peaklistmethods.io.gnpsexport.fbmn.GnpsFbmnExportAndSubmitParameters.RowFilter;
  import net.sf.mzmine.modules.tools.msmsspectramerge.MergedSpectrum;
  import net.sf.mzmine.modules.tools.msmsspectramerge.MsMsSpectraMergeModule;
  import net.sf.mzmine.modules.tools.msmsspectramerge.MsMsSpectraMergeParameters;
  import net.sf.mzmine.parameters.ParameterSet;
  import net.sf.mzmine.taskcontrol.AbstractTask;
  import net.sf.mzmine.taskcontrol.TaskStatus;
  import net.sf.mzmine.util.PeakUtils;
  import net.sf.mzmine.util.files.FileAndPathUtil;
  
  /**
   * Exports all files needed for GNPS
   *
   * @author Robin Schmid (robinschmid@uni-muenster.de)
   *
   */
  public class GnpsFbmnMgfExportTask extends AbstractTask {
    // Logger.
    private final Logger LOG = Logger.getLogger(getClass().getName());
  
    //
    private final PeakList[] peakLists;
    private final File fileName;
    private final String plNamePattern = "{}";
    private int currentIndex = 0;
    private final String massListName;
    private final MsMsSpectraMergeParameters mergeParameters;
  
    // by robin
    private NumberFormat mzForm = MZmineCore.getConfiguration().getMZFormat();
    private NumberFormat intensityForm = MZmineCore.getConfiguration().getIntensityFormat();
    // seconds
    private NumberFormat rtsForm = new DecimalFormat("0.###");
    // correlation
    private NumberFormat corrForm = new DecimalFormat("0.0000");
  
    private RowFilter filter;
  
    GnpsFbmnMgfExportTask(ParameterSet parameters) {
      this.peakLists = parameters.getParameter(GnpsFbmnExportAndSubmitParameters.PEAK_LISTS).getValue()
          .getMatchingPeakLists();
  
      this.fileName = parameters.getParameter(GnpsFbmnExportAndSubmitParameters.FILENAME).getValue();
      this.massListName = parameters.getParameter(GnpsFbmnExportAndSubmitParameters.MASS_LIST).getValue();
      this.filter = parameters.getParameter(GnpsFbmnExportAndSubmitParameters.FILTER).getValue();
      if (parameters.getParameter(GnpsFbmnExportAndSubmitParameters.MERGE_PARAMETER).getValue()) {
        mergeParameters = parameters.getParameter(GnpsFbmnExportAndSubmitParameters.MERGE_PARAMETER)
            .getEmbeddedParameters();
      } else {
        mergeParameters = null;
      }
    }
  
    @Override
    public double getFinishedPercentage() {
      if (peakLists.length == 0)
        return 1;
      else
        return currentIndex / peakLists.length;
    }
  
    @Override
    public void run() {
      setStatus(TaskStatus.PROCESSING);
  
      // Shall export several files?
      boolean substitute = fileName.getPath().contains(plNamePattern);
  
      // Process feature lists
      for (PeakList peakList : peakLists) {
        currentIndex++;
  
        // Filename
        File curFile = fileName;
        if (substitute) {
          // Cleanup from illegal filename characters
          String cleanPlName = peakList.getName().replaceAll("[^a-zA-Z0-9.-]", "_");
          // Substitute
          String newFilename =
              fileName.getPath().replaceAll(Pattern.quote(plNamePattern), cleanPlName);
          curFile = new File(newFilename);
        }
        curFile = FileAndPathUtil.getRealFilePath(curFile, "mgf");
  
        // Open file
        FileWriter writer;
        try {
          writer = new FileWriter(curFile);
        } catch (Exception e) {
          setStatus(TaskStatus.ERROR);
          setErrorMessage("Could not open file " + curFile + " for writing.");
          return;
        }
  
        try {
          export(peakList, writer, curFile);
        } catch (IOException e) {
          setStatus(TaskStatus.ERROR);
          setErrorMessage("Error while writing into file " + curFile + ": " + e.getMessage());
          return;
        }
  
        // Cancel?
        if (isCanceled()) {
          return;
        }
  
        // Close file
        try {
          writer.close();
        } catch (Exception e) {
          setStatus(TaskStatus.ERROR);
          setErrorMessage("Could not close file " + curFile);
          return;
        }
  
        // If feature list substitution pattern wasn't found,
        // treat one feature list only
        if (!substitute)
          break;
      }
  
      if (getStatus() == TaskStatus.PROCESSING)
        setStatus(TaskStatus.FINISHED);
    }
  
    private int export(PeakList peakList, FileWriter writer, File curFile) throws IOException {
      final String newLine = System.lineSeparator();
  
      // count exported
      int count = 0;
      int countMissingMassList = 0;
      for (PeakListRow row : peakList.getRows()) {
        // do not export if no MSMS
        if (!filter.filter(row))
          continue;
  
        String rowID = Integer.toString(row.getID());
        double retTimeInSeconds = ((row.getAverageRT() * 60 * 100.0) / 100.);
  
        // Get the MS/MS scan number
        Feature bestPeak = row.getBestPeak();
        if (bestPeak == null)
          continue;
        int msmsScanNumber = bestPeak.getMostIntenseFragmentScanNumber();
        if (rowID != null) {
          PeakListRow copyRow = copyPeakRow(row);
          // Best peak always exists, because feature list row has at least one peak
          bestPeak = copyRow.getBestPeak();
  
          // Get the heighest peak with a MS/MS scan number (with mass list)
          boolean missingMassList = false;
          msmsScanNumber = bestPeak.getMostIntenseFragmentScanNumber();
          while (msmsScanNumber < 1
              || getScan(bestPeak, msmsScanNumber).getMassList(massListName) == null) {
            // missing masslist
  