public void getUserPreferences() {
   if (maincont == null) {
     return;
   }
   Preferences p =
       NbPreferences.forModule(
           com.iontorrent.torrentscout.explorer.options.TorrentExplorerPanel.class);
   int span = p.getInt("span", 8);
   int size = p.getInt("masksize", 100);
   automatic_nn = p.getBoolean("automatic_nn", true);
   maincont.setRasterSize(size);
   maincont.setSpan(span);
   maincont.setMedianFunction("median");
 }
 @Override
 public void flowChanged(ArrayList<Integer> flows) {
   int f = flows.get(0);
   if (maincont == null) {
     return;
   }
   if (f == maincont.getFlow()) {
     return;
   }
   p("flow changed");
   maincont.setFlow(f);
   // this.rasterViewCreate(true, null);
   // recomputeChart();
 }
 protected boolean getExpContext() {
   //  Exception e = new Exception("showing stack trace");
   //   p(ErrorHandler.getString(e));
   if (expContext == null) {
     expContext = GlobalContext.getContext().getExperimentContext();
   }
   if (expContext == null) {
     GuiUtils.showNonModalMsg("Got no experiment context from global contexet");
     return false;
   }
   maincont = ExplorerContext.getCurContext(expContext);
   info.setText(expContext.getRawDir());
   this.btnreload.setToolTipText(
       "Reload data from dir " + expContext.getRawDir() + " at " + maincont.getAbsDataAreaCoord());
   return true;
 }
  public ProcessTopComponent() {
    initComponents();
    setName(NbBundle.getMessage(ProcessTopComponent.class, "CTL_ProcessTopComponent"));
    setToolTipText(NbBundle.getMessage(ProcessTopComponent.class, "HINT_ProcessTopComponent"));

    flowPanel = new FlowNrPanel(this);

    if (maincont == null) {
      flowPanel.setFlow(0);
    } else {
      flowPanel.setFlow(maincont.getFlow());
      typePanel.setType(maincont.getFiletype());
    }
    typePanel = new FiletypePanel(this);

    this.toolbar.add(this.flowPanel, null, 0);
    toolbar.add(this.typePanel, null, 0);
  }
  @Override
  public void taskDone(Task t) {
    p("Task " + t + " is done");
    setCursor(null);
    // if (t.isSuccess()) {
    this.data = ((ComputeNN) t).getData();

    p("Got nndata " + data);
    if (data == null) {
      JOptionPane.showMessageDialog(this, "There was a problem in nn compute, I got no result");
    } else {
      maincont.setData(data);
      rasterViewCreate(
          false,
          "After masked neighbor subtraction, span="
              + maincont.getSpan()
              + ", BG mask="
              + maincont.getBgMask());
    }
  }
  public boolean doSelectCoord() throws HeadlessException {

    SingleCoordSelectionPanel pan = new SingleCoordSelectionPanel();
    // pan.setMaxX(this.expContext.getNrcols());
    // pan.setMaxY(this.expContext.getNrrows());
    if (maincont.getAbsDataAreaCoord() != null) {
      pan.setCoord1(maincont.getAbsDataAreaCoord());
    }
    int ans =
        JOptionPane.showConfirmDialog(
            this, pan, "Enter a selection:", JOptionPane.OK_CANCEL_OPTION);
    if (ans == JOptionPane.CANCEL_OPTION) {
      return true;
    }
    // RELATIVE to current sub experiment
    WellCoordinate c1 =
        new WellCoordinate(
            pan.getCoord1().getCol() - maincont.getExp().getColOffset(),
            pan.getCoord1().getRow() - maincont.getExp().getRowOffset());
    WellCoordinate c2 = c1.add(100, 100);
    WellSelection sel = new WellSelection(c1, c2);
    WellCoordinate abs = pan.getCoord1();
    if (maincont.getAbsDataAreaCoord() != null && abs.equals(maincont.getAbsDataAreaCoord())) {
      GuiUtils.showNonModalMsg("Same coordinates, I won't to anything", "Process");
      return true;
    }
    maincont.setAbsDataAreaCoord(abs);

    LookupUtils.publish(wellSelectionContent, sel);

    return false;
  }
  @Override
  public void fileTypeChanged(RawType filetype) {
    if (maincont == null) {
      return;
    }

    if (maincont != null) {
      maincont.setFiletype(filetype);
    }
    p("filetypechanged");

    //    this.rasterViewCreate(true, null);

  }
 private void update(ExperimentContext result) {
   if (result == null) {
     result = GlobalContext.getContext().getExperimentContext();
   }
   if (result == null) {
     // GuiUtils.showNonModalMsg("Got no experiment context");
     return;
   }
   if (result != null) {
     this.expContext = result;
     maincont = ExplorerContext.getCurContext(result);
     getUserPreferences();
     addGui();
   }
 }
  private void subtractActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_subtractActionPerformed

    RasterData data = maincont.getData();
    if (data == null) {
      JOptionPane.showMessageDialog(this, "I have no data yet to subtract anything from :-)");
      return;
    }
    if (subtract_type == null) {
      subtract_type = maincont.getFiletype();
    }
    FlowSelection pan =
        new FlowSelection(
            "Select the flow and file type you wish to subtract from the currently selected data");
    pan.setFlow(subtract_flow);
    pan.setFiletype(subtract_type);
    int ans =
        JOptionPane.showConfirmDialog(
            this,
            pan,
            "Data Subtraction",
            JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE);
    if (ans != JOptionPane.OK_OPTION) {
      return;
    }

    subtract_flow = pan.getFlow();
    subtract_type = pan.getFiletype();
    // otherwise load the data and then subtract
    RasterData sub = null;
    DataAccessManager manager = DataAccessManager.getManager(maincont.getExp().getWellContext());
    try {
      p("Loading subregion, RELATIVE coord " + maincont.getRelativeDataAreaCoord());
      sub =
          manager.getRasterDataForArea(
              null,
              maincont.getRasterSize(),
              maincont.getRelativeDataAreaCoord(),
              pan.getFlow(),
              pan.getFiletype(),
              null,
              0,
              -1);
      // now subtract first frame
    } catch (Exception ex) {
      p("Error when loading: " + ErrorHandler.getString(ex));
    }
    if (sub == null) {
      JOptionPane.showMessageDialog(
          this,
          "I could not load flow "
              + pan.getFlow()
              + ", "
              + pan.getFiletype()
              + ", @ "
              + maincont.getAbsDataAreaCoord());
      return;
    }
    String what = "raw";
    if (this.automatic_nn) {
      GuiUtils.showNonModalMsg("Computing NN before subtraction");
      sub = computeNN(null, sub);
      what = "NN subtracted";
    }

    data.subtract(sub);
    JOptionPane.showMessageDialog(
        this,
        "I subtracted the "
            + what
            + " data from "
            + pan.getFlow()
            + ", "
            + pan.getFiletype()
            + ", @ "
            + maincont.getAbsDataAreaCoord());
    this.rasterViewUpdate();
  } // GEN-LAST:event_subtractActionPerformed
 private void btnNNActionPerformed(
     java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnNNActionPerformed
   p(" about to compute nn. Maincont is: " + maincont + ", data is: " + maincont.getData());
   ComputeNN task = new ComputeNN(this);
   task.execute();
 } // GEN-LAST:event_btnNNActionPerformed
  public void rasterViewCreate(boolean load, String title) {
    p("=========rasterViewCreate called: load=" + load);
    // if (load) {
    //  Exception e = new Exception("Tracing call");
    //   p(ErrorHandler.getString(e));
    //  }
    if (!getExpContext()) {
      return;
    }
    if (load) {
      if (selection != null)
        GuiUtils.showNonModalMsg(
            "Loading "
                + selection
                + " for "
                + maincont.getFiletype()
                + ", flow "
                + maincont.getFlow(),
            "Process");
    }

    String base = "?";
    if (maincont.getFiletype() == RawType.ACQ) {
      base = "" + maincont.getExp().getWellContext().getBase(maincont.getFlow());
    }
    this.flowPanel.setToolTipText(
        "<html>Base for flow "
            + maincont.getFlow()
            + ":"
            + base
            + "<br>Flow order: "
            + maincont.getExp().getFlowOrder()
            + "</html>");

    raster = new RasterView(maincont, load);

    this.panImage.removeAll();
    panImage.add(raster);
    // repaint();
    //  p("adding raster view");
    if (load) {
      this.getUserPreferences();
    }
    raster.update(load, maincont);

    // paintImmediately(0,0,1000,1000);
    panImage.repaint();
    raster.repaint();

    if (load) {
      title = "Raw data";
    }
    title += " flow " + maincont.getFlow() + "=" + base;
    chartViewCreate(title);

    invalidate();
    revalidate();
    // this.paintAll(getGraphics());
    repaint();
    if (load) {
      if (this.automatic_nn) {
        p("also doing nn - disable nn");
        this.btnNN.setEnabled(false);
        btnNN.setText("");
        btnNN.setToolTipText(
            "Automatically computing NN - check Explorer Options if you wish to change it!");
        RasterData data = computeNN(null);
        maincont.setData(data);
        rasterViewCreate(
            false,
            "After masked neighbor subtraction, span="
                + maincont.getSpan()
                + ", BG mask="
                + maincont.getBgMask());
      } else {
        this.btnNN.setEnabled(true);
        btnNN.setText("Compute NN");
        btnNN.setToolTipText(
            "Click to compute NN bg subtraction - check Explorer Options if you wish <b>automate</b> this!");
      }
    }
  }
  private RasterData computeNN(ProgressListener prog, RasterData rawdata) {
    //   p("computeNN. Maincont is: " + maincont);
    if (rawdata == null) {
      GuiUtils.showNonModalDialog(
          "<html>I see no data yet - did you already pick a region?<br>"
              + "(Even if you see something somewhere, if you didn't actually select a region, it might just show some sample data)</html>",
          "No data - region selected?");
      return null;
    }
    RasterData nndata = null;
    try {
      if (maincont == null) {
        maincont = ExplorerContext.getCurContext(expContext);
      }
      int span = Math.max(1, this.maincont.getSpan());
      NearestNeighbor nn = new NearestNeighbor(span, maincont.getMedianFunction());
      BitMask ignore = maincont.getIgnoreMask();
      BitMask take = maincont.getBgMask();

      if (take != null && take == ignore) {
        JOptionPane.showMessageDialog(
            this,
            "You select the same mask for ignore and bg :-). \nYou should select another mask for the bg (or you get a null result. I will just return the old data.");
        return rawdata;
      }
      if (take != null && take.computePercentage() < 1) {
        int ans =
            JOptionPane.showConfirmDialog(
                this,
                "<html>The bg mask only has "
                    + take.computePercentage()
                    + "% wells, do you want to still use it?"
                    + "<br><b>Did you already select a region?</b>"
                    + "<br>You might want to use the MaskEditor (and <b>refresh</b> the masks possibly) to check them</html>",
                "Few wells",
                JOptionPane.OK_CANCEL_OPTION);
        if (ans == JOptionPane.CANCEL_OPTION) {
          return rawdata;
        }
      }
      maincont.setBgMask(take);
      maincont.setIgnoreMask(ignore);
      if (prog != null)
        prog.setMessage(
            "Masked neighbor subtraction: ignore mask " + ignore + " and empty mask " + take);
      // RasterData nndata = nn.compute(rawdata, mask, prog, span);

      //   p("calling computebetter");
      // if (boxslow.isSelected()) nndata =nn.computeSlow(rawdata, ignore, take, prog, span);
      nndata = nn.computeBetter(rawdata, ignore, take, prog, span);

    } catch (Exception e) {
      p("Error with nn: " + ErrorHandler.getString(e));
      JOptionPane.showMessageDialog(
          this,
          "I was not able to do the masked neighbor subtraction:\n" + ErrorHandler.getString(e));
      return null;
    }
    if (nndata == null) {
      JOptionPane.showMessageDialog(
          this,
          "I was not able to do the masked neighbor subtraction - I got no error but also no result :-) ");
    }
    return nndata;
  }
 private RasterData computeNN(ProgressListener prog) {
   return computeNN(prog, maincont.getData());
 }
  //    private class WellSelectionListener implements LookupListener {
  //
  //        @Override
  //        public void resultChanged(LookupEvent ev) {
  //            //ask
  //            int ans = JOptionPane.showConfirmDialog(ProcessTopComponent.this, "Would you like to
  // reload the data with the updated coordinate?");
  //            if (ans == JOptionPane.OK_OPTION) getLatestSelection();
  //        }
  //    }
  //    private void getLatestSelection() {
  //        final Collection<? extends WellSelection> selections =
  // selectionSelection.allInstances();
  //        if (!selections.isEmpty()) {
  //            //  p("Getting last selection");
  //            selection = null;
  //            Iterator<WellSelection> it = (Iterator<WellSelection>) selections.iterator();
  //            while (it.hasNext()) {
  //                selection = it.next();
  //            }
  //            p("Got a selection: " + selection);
  //            maincont.setDataAreaCoord(selection.getCoord1());
  //            maincont.getExp().getWellContext().setSelection(selection);
  //
  //            //   p("SubscriberListener Got WellSelection:" + cur_context);
  //            GuiUtils.showNonModalMsg("Process: Got a well selection: " + selection);
  //            // rasterViewUpdate(true);
  //        }
  //
  //    }
  private void addGui() {

    if (expContext == null) {
      expContext = GlobalContext.getContext().getExperimentContext();
    }
    if (expContext == null) {
      //  GuiUtils.showNonModalMsg("Got no experiment context");
      return;
    }
    maincont = ExplorerContext.getCurContext(expContext);
    getUserPreferences();

    rasterViewCreate(true, null);

    maincont.addListener(
        new ContextChangeAdapter() {

          @Override
          public void fileTypeChanged(RawType t) {
            p("RawType chnaged: " + t);
            typePanel.setType(t);
            // rasterViewCreate(true, null);
          }

          @Override
          public void flowChanged(int flow) {
            p("flow changed: " + flow);
            rasterViewCreate(true, "Raw data");
          }

          @Override
          public void dataChanged(
              RasterData data,
              int startrow,
              int startcol,
              int startflow,
              int endrow,
              int endcol,
              int endflow) {
            p(
                "RasterData chnged: "
                    + startrow
                    + "/"
                    + startcol
                    + "/"
                    + startflow
                    + ", NOT reloading automatically");
            // rasterViewUpdate();
          }

          @Override
          public void coordChanged(WellCoordinate coord) {
            // p("coord chnged: " + coord);
            chartViewUpdate();
          }

          @Override
          public void dataAreaCoordChanged(WellCoordinate coord) {
            p("data area coord changed: " + coord);
            btnreload.setToolTipText("Reload data from at " + maincont.getAbsDataAreaCoord());
            // rebuildMaskComboBoxes();
            rasterViewCreate(true, "Raw data");
          }

          @Override
          public void widgetChanged(Widget w) {
            p("widget chnged: " + w);
            chartViewUpdate();
          }
        });
    if (expContext.getWellContext().getCoordinate() == null) {
      expContext.getWellContext().setCoordinate(new WellCoordinate(100, 100));
    }
  }