/* Wraps everything into a Cell Manager Class*/
 private CellManager toCellManager(ImagePlus imp, ArrayList<PolygonRoi> rois, ImagePlus av_imp) {
   CellManager cm = new CellManager(av_imp, imp, this.ovr);
   Iterator itr = rois.iterator();
   ArrayList<Double> av_sig = new ArrayList<>();
   PolygonRoi roi;
   while (itr.hasNext()) {
     roi = (PolygonRoi) itr.next();
     av_sig = Activity_Analysis.getAverageSignal(imp, roi);
     CalciumSignal ca_sig = new CalciumSignal(av_sig, this.dt_r);
     ovr.add(roi);
     ca_sig.DeltaF();
     cm.addCell(ca_sig, roi);
   }
   //            catch(Exception e){
   //                IJ.showMessage(e.getMessage());
   //            }
   //        }
   ovr.setLabelColor(Color.WHITE);
   //        ovr.setFillColor(Color.GREEN);
   ovr.setStrokeColor(Color.getHSBColor(100, 30, 87));
   av_imp.setOverlay(ovr);
   av_imp.show();
   IJ.run("In [+]", "");
   IJ.run("In [+]", "");
   return cm;
 }
  /* Methods */
  public void run(String argv) {
    if (this.setup()) { // validates conditions
      IJ.showStatus(" Dark noise removal...");
      imp_r = DarkNoiseRemoval(imp_r, NOISE_ROI);
      if (removeFirst) {
        ImageStack t_stack = imp_r.getStack(); // deletes first slice
        t_stack.deleteSlice(1);
        imp_r.setStack(t_stack);
      } else {
        // if first slice wasn't removed we must move the first index of the stim in binSize
        this.imp_s_index[0] -= Math.round((float) (this.dt_r / this.DT_S));
      }
      // imp_r.show();

      // get Cells by segmentation;
      IJ.showStatus(" Cell Segmentation...");
      ImagePlus avr_imp = AApSegmetator.getAverageIm(imp_r);
      AApSegmetator segmentator = new AApSegmetator(avr_imp);
      this.cells_roi = segmentator.SegmentCellsCWT();
      // this.cells_roi = segmentator.SegmentCellsML();

      // Resample stimulus
      ArrayList<Double> stim_vector = new ArrayList<>();
      if (!this.useArtifact) {
        IJ.showStatus(" Stimulus srtifact removal....");
        Stimulus_API sapi = new Stimulus_API();
        sapi.setup("", this.imp_s, this.cells_roi, 0);
        stim_vector =
            sapi.ResampleStimulus(
                this.dt_r, imp_r.getStackSize(), this.imp_s_index[0], this.imp_s_index[1]);
      } else {
        double[] var1 = Activity_Analysis.getAverageSignal(imp_r);
        Object[] var2 = Extract_Stimulus.getPeaks(var1, 1);
        TimeSeries var3 = Extract_Stimulus.getStimulusArray(var2, imp_r.getStackSize());
        for (int i = 0; i < var3.Signal.length; i++) {
          stim_vector.add(var3.Signal[i]);
        }
      }

      // Remove stimulus slices
      ArrayList<Integer> stim_sampels = new ArrayList<>();
      for (int i = 0; i < stim_vector.size(); i++) {
        if (stim_vector.get(i) > 0) stim_sampels.add(i);
      }
      this.imp_r = ReplaceSlices(this.imp_r, stim_sampels);
      //            this.imp_r.show();
      //            IJ.run("In [+]", "");
      //            IJ.run("In [+]", "");

      // Kalman filter
      ImageStack ims = imp_r.getStack();
      Kalman_Stack_Filter kl = new Kalman_Stack_Filter();
      kl.filter(ims, this.KL_PRECVAR, this.KM_GAIN);
      imp_r.setStack(ims);

      // wrap everything with the Cell manager
      this.cm = toCellManager(this.imp_r, this.cells_roi, avr_imp);

      System.out.print("Success!!");
    }

    // run local method

  }
  /* Setup GUI */
  protected final boolean setup() {
    if (IJ.versionLessThan("1.40c")) {
      return false;
    } else {
      int[] ids = WindowManager.getIDList();
      if (ids != null && ids.length >= 2) {
        ArrayList titlesList = new ArrayList();
        ArrayList idsList = new ArrayList();
        String currentTitle = null;

        for (int titles = 0; titles < ids.length; ++titles) {
          ImagePlus var1 = WindowManager.getImage(ids[titles]);
          titlesList.add(var1.getTitle());
          idsList.add(Integer.valueOf(ids[titles]));
          if (var1 == WindowManager.getCurrentImage()) {
            currentTitle = var1.getTitle();
          }
        }

        if (titlesList.size() < 2) {
          IJ.showMessage("You should have at least two stacks - stimulus and response.");
          return false;
        } else {
          String[] var8 = new String[titlesList.size()];
          titlesList.toArray(var8);
          if (currentTitle == null) {
            currentTitle = var8[0];
          }
          SubstackMaker sm = new SubstackMaker();
          GenericDialog gd = new GenericDialog("AAP - 1.1.0");
          // gd.setInsets(10, 45, 0);
          gd.addChoice("Stimulus stack", var8, currentTitle);
          gd.addChoice("Response stack", var8, currentTitle.equals(var8[0]) ? var8[1] : var8[0]);
          String defautltSlices =
              "1-" + WindowManager.getImage(((Integer) idsList.get(0)).intValue()).getStackSize();
          gd.addMessage("Enter a range (e.g. 2-14)...", null, Color.darkGray);
          gd.addStringField("Slices of Response:", defautltSlices, 40);
          gd.addCheckbox("Remove first slice", true);
          gd.addCheckbox("Use Artifact from response", true);
          gd.showDialog();
          if (gd.wasCanceled()) {
            return false;
          } else {
            this.imp_s =
                WindowManager.getImage(((Integer) idsList.get(gd.getNextChoiceIndex())).intValue());
            this.imp_r =
                WindowManager.getImage(((Integer) idsList.get(gd.getNextChoiceIndex())).intValue());
            String userInput = gd.getNextString();
            this.dt_r = Activity_Analysis.findSignalDt(this.imp_r.getTitle());
            if (userInput == null) {
              return false;
            }
            IJ.showStatus(" Making substack copy of selection...");
            this.imp_r = sm.makeSubstack(this.imp_r, userInput);
            this.imp_s_index = getFirstNLast(this.imp_r, userInput);
            if (this.imp_s_index[0] != 1 | !gd.getNextBoolean()) this.removeFirst = false;
            if (gd.getNextBoolean()) this.useArtifact = true;
            // this.imp_s = makeStimSubstack(this.imp_s , userInput);
            return true;
          }
        }
      } else {
        IJ.showMessage("You should have at least two stacks open.");
        return false;
      }
    }
  }