示例#1
0
  /**
   * Creates a new JNI communication handler for the Control & Monitoring API.
   *
   * @throws CMException Thrown when the C JNI library cannot be loaded (libcmjni) or one of the XML
   *     (de)serializers cannot be initialised.
   */
  public JniCommunicator() throws CommunicationException {
    try {
      System.loadLibrary("cmjni");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Could not load JNI library 'cmjni'. Reason:\n" + e.getMessage());
      throw new CommunicationException("Could not load JNI library 'cmjni': " + e.getMessage());
    }

    initialized = false;
    JniCommunicator.connectionAlive = false;
    entityDeserializer = DataTransformerFactory.getEntityDeserializer(DataTransformerFactory.XML);
    typeDeserializer = DataTransformerFactory.getMetaTypeDeserializer(DataTransformerFactory.XML);
    entitySerializer = DataTransformerFactory.getEntitySerializer(DataTransformerFactory.XML);
    statusDeserializer = DataTransformerFactory.getStatusDeserializer(DataTransformerFactory.XML);
    snapshotDeserializer =
        DataTransformerFactory.getSnapshotDeserializer(DataTransformerFactory.XML);
    snapshotSerializer = DataTransformerFactory.getSnapshotSerializer(DataTransformerFactory.XML);
    untypedSampleDeserializer =
        DataTransformerFactory.getUntypedSampleDeserializer(DataTransformerFactory.XML);
    userDataSerializer = DataTransformerFactory.getUserDataSerializer(DataTransformerFactory.XML);
    qosDeserializer = DataTransformerFactory.getQoSDeserializer(DataTransformerFactory.XML);
    qosSerializer = DataTransformerFactory.getQoSSerializer(DataTransformerFactory.XML);
    statisticsDeserializer =
        DataTransformerFactory.getStatisticsDeserializer(DataTransformerFactory.XML);
  }
示例#2
0
 public void testIncludeSymbolNameInLookupError() {
   NativeLibrary lib = NativeLibrary.getInstance("testlib");
   try {
     lib.getGlobalVariableAddress(getName());
     fail("Non-existent global variable lookup should fail");
   } catch (UnsatisfiedLinkError e) {
     assertTrue(
         "Expect symbol name in error message: " + e.getMessage(),
         e.getMessage().indexOf(getName()) != -1);
   }
 }
示例#3
0
 public void initSystem() {
   Pointer[] p = new Pointer[1];
   try {
     int result = LibUsbLibrary.libUsb.libusb_init(p);
     checkError("init", result);
     this.context = p[0];
     // LibUsbLibrary.libUsb.libusb_set_debug(this.context, 4);
   } catch (UnsatisfiedLinkError e) {
     if (e.getMessage().matches(".*cannot open shared object file.*")) {
       System.out.println("Libusb not found. Minimum libusb version is 1.0.14");
       System.out.println("It can be downloaded on http://www.libusbx.org");
     } else {
       System.out.println(e.getLocalizedMessage());
     }
     System.exit(1);
   }
   try {
     libusb_version v = LibUsbLibrary.libUsb.libusb_get_version();
     if (v.major != (short) 1 || v.minor != (short) 0 || v.micro < (short) 14) {
       System.out.println(
           "Minimum libusb version is 1.0.14. Found " + v.major + "." + v.minor + "." + v.micro);
       System.out.println("It can be downloaded on http://www.libusbx.org");
       System.exit(1);
     }
   } catch (UnsatisfiedLinkError e) {
     System.out.println(
         "A libusb was found but not with the right version. Minimum libusb version is 1.0.14");
     System.out.println("It can be downloaded on http://www.libusbx.org");
     System.exit(1);
   }
 }
示例#4
0
 /**
  * Look up the given global variable within this library.
  *
  * @param symbolName
  * @return Pointer representing the global variable address
  * @throws UnsatisfiedLinkError if the symbol is not found
  */
 public Pointer getGlobalVariableAddress(String symbolName) {
   try {
     return new Pointer(getSymbolAddress(symbolName));
   } catch (UnsatisfiedLinkError e) {
     throw new UnsatisfiedLinkError("Error looking up '" + symbolName + "': " + e.getMessage());
   }
 }
示例#5
0
 static {
   try {
     System.loadLibrary("ADPCMAndroid");
     //      return;
   } catch (UnsatisfiedLinkError localUnsatisfiedLinkError) {
     System.out.println("loadLibrary(ADPCMAndroid)," + localUnsatisfiedLinkError.getMessage());
   }
 }
示例#6
0
  /** Start the search with the loaded terms. */
  public void doSearch() {

    try {

      /* Start timing */
      timer.start();

      /* Start a new desktop query */
      JGDQuery jgdQuery = new JGDQuery(query);

      /* Limit the number of results */
      jgdQuery.setNum(maxResults);

      /* Filter by files only */
      jgdQuery.setFilterByFiles();

      /* Execute the jgdQuery */
      Results jgdResults = jgdQuery.execute();

      /* Get the result */
      List<?> l = jgdResults.getResult();

      for (Object jdgResult : l) {

        GoogleDesktopFile googleDesktopFile = (GoogleDesktopFile) jdgResult;

        /* Create a new file object from the result */
        File file = new File(googleDesktopFile.get_uri());

        /* If this fails, skip it */
        if (file == null) {
          continue;
        }

        log.info("Local result found: " + file.toString());

        Resource resource = new Resource();
        resource.setArticle(new FileArticle());
        resource.setData(new FileData(file));

        /* Add to total results with extended data */
        results.put(file.toURI(), resource);
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    } catch (UnsatisfiedLinkError ule) {
      log.error(ule.getMessage(), ule);
    } catch (NoClassDefFoundError ncdefe) {
      log.error(ncdefe.getMessage(), ncdefe);
    }

    /* Stop timing */
    timer.stop();
  }
 public SigarLibrary() {
   logger.info("Initializing SIGAR library");
   try {
     sigar = new Sigar();
     mounts = sigar.getFileSystemMap();
     initialized = true;
   } catch (SigarException e) {
     logger.info("Could not initialize SIGAR library {} ", e.getMessage());
   } catch (UnsatisfiedLinkError linkError) {
     logger.info("Could not initialize SIGAR library {} ", linkError.getMessage());
   }
 }
示例#8
0
  /**
   * Method to actual load the library and post process more meaningful error messages if necessary.
   *
   * @param name native library (not extensions or directory paths)
   * @param errors the errors
   * @return the library
   */
  public static boolean loadLibrary(String name, List<Error> errors) {

    Error error = null;

    try {
      System.loadLibrary(name);
    } catch (UnsatisfiedLinkError e) {
      error = e;
      String msg = e.getMessage();

      String mappedName = System.mapLibraryName(name);

      if (msg.contains("dependent libraries")) {
        error =
            new UnsatisfiedLinkError(
                mappedName
                    + " native library is found, but needs "
                    + " dependency library(ies) installed first.");
      }

      if (msg.contains("specified procedure")) {
        error =
            new UnsatisfiedLinkError(
                "Dependency version mismatch: "
                    + mappedName
                    + " library is found, but can't find a required native function"
                    + " call it is dependent on. Make sure all dependencies at the"
                    + " right version levels are installed.");
      }

      if (msg.contains("java.library.path")) {
        error =
            new UnsatisfiedLinkError(
                mappedName
                    + " native library is not found. "
                    + "Make sure its installed in /usr/lib or /usr/lib64 or "
                    + "\\windows\\system32 or \\widows\\system64 or "
                    + "set JVM -Djava.library.path=<dir_path_jnetpcap_library> to "
                    + "its location.");
      }

    } catch (Error e) {
      error = e;
    }

    if (error != null) {
      errors.add(error);
    }

    return error == null;
  }
示例#9
0
文件: Library.java 项目: jfellus/agem
 public static String load(String libname, String mode) {
   try {
     String lib = "retin_" + libname + "-" + getArchName() + "-" + getCCName() + "-" + mode;
     //			System.out.println ("Library "+lib+" try...");
     System.loadLibrary(lib);
     System.out.println("Library " + lib + " loaded");
   } catch (Exception ex) {
     return ex.getMessage();
   } catch (UnsatisfiedLinkError ex) {
     ex.printStackTrace();
     return ex.getMessage();
   }
   return null;
 }
示例#10
0
文件: Function.java 项目: suyimin/jna
 /**
  * Create a new <code>Function</code> that is linked with a native function that follows the given
  * calling convention.
  *
  * <p>The allocated instance represents a pointer to the named native function from the supplied
  * library, called with the given calling convention.
  *
  * @param library {@link NativeLibrary} in which to find the function
  * @param functionName Name of the native function to be linked with
  * @param callFlags Function <a href="#callflags">call flags</a>
  * @param encoding Encoding for conversion between Java and native strings.
  * @throws UnsatisfiedLinkError if the given function name is not found within the library.
  */
 Function(NativeLibrary library, String functionName, int callFlags, String encoding) {
   checkCallingConvention(callFlags & MASK_CC);
   if (functionName == null) throw new NullPointerException("Function name must not be null");
   this.library = library;
   this.functionName = functionName;
   this.callFlags = callFlags;
   this.options = library.options;
   this.encoding = encoding != null ? encoding : Native.getDefaultStringEncoding();
   try {
     this.peer = library.getSymbolAddress(functionName);
   } catch (UnsatisfiedLinkError e) {
     throw new UnsatisfiedLinkError(
         "Error looking up function '" + functionName + "': " + e.getMessage());
   }
 }
示例#11
0
  public static Editline create(String appName) {
    Editline e = new Editline();

    try {
      /** attempt to load libjava-editline.so */
      System.loadLibrary("java-editline");
    } catch (UnsatisfiedLinkError ule) {
      System.out.println("Error loading libjava-editline.so: " + ule.getMessage());
      e._useEditline = false;
    }

    if (e._useEditline) {
      e.initEditlineImpl(appName);
    }

    return e;
  }
示例#12
0
 private void link() {
   synchronized (linkStatus) {
     try {
       if (linkStatus.attemptLoad()) {
         linkStatus.checkVersion(getLibMajorVersion(), getLibMinorVersion());
         linkStatus.check(native_clinit());
       }
       if (linkStatus.useNative()) {
         linkStatus.check(native_init());
         native_lock = new Object();
       }
     } catch (UnsatisfiedLinkError e) {
       linkStatus.fail(e);
       if (DEBUG && debuglevel > 2) debug(e.getMessage());
     }
     if (DEBUG && debuglevel > 2) debug("Using native library? " + (native_lock != null));
   }
 }
示例#13
0
 static boolean load(final String libName, final StringBuffer message) {
   try {
     if (libName.indexOf(SEPARATOR) != -1) {
       System.load(libName);
     } else {
       System.loadLibrary(libName);
     }
     return true;
   } catch (UnsatisfiedLinkError e) {
     if (message.length() == 0) {
       message.append(DELIMITER);
     }
     message.append('\t');
     message.append(e.getMessage());
     message.append(DELIMITER);
   }
   return false;
 }
  /**
   * Creates the gStreamer pipeline and blocks until it starts successfully
   *
   * @param newRec The RecordingImpl of the capture we wish to perform.
   * @return The recording ID (equal to newRec.getID()) or null in the case of an error
   */
  public void start(RecordingImpl newRec) {
    // Create the pipeline
    try {
      pipeline = create(newRec.getProperties(), false);
    } catch (UnsatisfiedLinkError e) {
      throw new UnableToStartCaptureException(
          e.getMessage() + " : please add libjv4linfo.so to /usr/lib to correct this issue.");
    }

    // Check if the pipeline came up ok
    if (pipeline == null) {
      // logger.error("Capture {} could not start, pipeline was null!", newRec.getID());
      captureFailureHandler.resetOnFailure(newRec.getID());
      throw new UnableToStartCaptureException(
          "Capture " + newRec.getID() + " could not start, pipeline was null!");
    }

    logger.info("Initializing devices for capture.");

    hookUpBus();

    // Grab time to wait for pipeline to start
    int wait;
    String waitProp = newRec.getProperty(CaptureParameters.CAPTURE_START_WAIT);
    if (waitProp != null) {
      wait = Integer.parseInt(waitProp);
    } else {
      wait = 5; // Default taken from gstreamer docs
    }

    pipeline.debugToDotFile(Pipeline.DEBUG_GRAPH_SHOW_ALL, pipeline.getName());
    // Try and start the pipeline
    pipeline.play();
    if (pipeline.getState(wait * GStreamerPipeline.GST_SECOND) != State.PLAYING) {
      // In case of an error call stop to clean up the pipeline.
      logger.debug("Pipeline was unable to start after " + wait + " seconds.");
      stop(GStreamerPipeline.DEFAULT_PIPELINE_SHUTDOWN_TIMEOUT);
      throw new UnableToStartCaptureException(
          "Unable to start pipeline after " + wait + " seconds.  Aborting!");
    }
    logger.info("{} started.", pipeline.getName());
  }
  public static void main(String[] args) {
    try {
      System.setProperty("sun.java2d.noddraw", "true");
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
    }
    JFrame f = new JFrame("Balloon Test");
    final String BALLOON_TEXT =
        "<html><center>"
            + "This is some sample balloon text<br>"
            + "which has been formatted with html.<br>"
            + "Click to dismiss.</center></html>";
    final JLabel content = new JLabel(BALLOON_TEXT);
    content.setIconTextGap(10);
    content.setBorder(new EmptyBorder(0, 8, 0, 8));
    content.setSize(content.getPreferredSize());
    content.setIcon(new InfoIcon());
    JLabel label = new JLabel("Click anywhere for more information");
    label.setHorizontalAlignment(SwingConstants.CENTER);
    label.addMouseListener(
        new MouseAdapter() {
          private MouseListener listener =
              new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                  hidePopup(e);
                }
              };
          private Popup popup;

          private void hidePopup(MouseEvent e) {
            e.getComponent().removeMouseListener(listener);
            if (popup != null) popup.hide();
          }

          public void mousePressed(MouseEvent e) {
            hidePopup(e);
            popup = BalloonManager.getBalloon(e.getComponent(), content, e.getX(), e.getY());
            popup.show();
            content.getParent().addMouseListener(listener);
          }
        });
    f.getContentPane().add(label);
    f.pack();
    f.setSize(new Dimension(300, 300));
    f.setLocation(100, 100);
    try {
      // Force a load of JNA
      WindowUtils.setWindowMask(f, WindowUtils.MASK_NONE);
      f.setVisible(true);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    } catch (UnsatisfiedLinkError e) {
      e.printStackTrace();
      String msg = e.getMessage() + "\nError loading the JNA library";
      JTextArea area = new JTextArea(msg);
      area.setOpaque(false);
      area.setFont(UIManager.getFont("Label.font"));
      area.setEditable(false);
      area.setColumns(80);
      area.setRows(8);
      area.setWrapStyleWord(true);
      area.setLineWrap(true);
      JOptionPane.showMessageDialog(
          null,
          new JScrollPane(area),
          "Library Load Error: "
              + System.getProperty("os.name")
              + "/"
              + System.getProperty("os.arch"),
          JOptionPane.ERROR_MESSAGE);
      System.exit(1);
    }
  }
示例#16
0
  private static NativeLibrary loadLibrary(String libraryName, Map options) {
    boolean isAbsolutePath = new File(libraryName).isAbsolute();
    List searchPath = new LinkedList();
    int openFlags = openFlags(options);

    // Append web start path, if available.  Note that this does not
    // attempt any library name variations
    String webstartPath = Native.getWebStartLibraryPath(libraryName);
    if (webstartPath != null) {
      searchPath.add(webstartPath);
    }

    //
    // Prepend any custom search paths specifically for this library
    //
    List customPaths = (List) searchPaths.get(libraryName);
    if (customPaths != null) {
      synchronized (customPaths) {
        searchPath.addAll(0, customPaths);
      }
    }

    searchPath.addAll(initPaths("jna.library.path"));
    String libraryPath = findLibraryPath(libraryName, searchPath);
    long handle = 0;
    //
    // Only search user specified paths first.  This will also fall back
    // to dlopen/LoadLibrary() since findLibraryPath returns the mapped
    // name if it cannot find the library.
    //
    try {
      handle = Native.open(libraryPath, openFlags);
    } catch (UnsatisfiedLinkError e) {
      // Add the system paths back for all fallback searching
      searchPath.addAll(librarySearchPath);
    }
    try {
      if (handle == 0) {
        libraryPath = findLibraryPath(libraryName, searchPath);
        handle = Native.open(libraryPath, openFlags);
        if (handle == 0) {
          throw new UnsatisfiedLinkError("Failed to load library '" + libraryName + "'");
        }
      }
    } catch (UnsatisfiedLinkError e) {
      // For android, try to "preload" the library using
      // System.loadLibrary(), which looks into the private /data/data
      // path, not found in any properties
      if (Platform.isAndroid()) {
        try {
          System.loadLibrary(libraryName);
          handle = Native.open(libraryPath, openFlags);
        } catch (UnsatisfiedLinkError e2) {
          e = e2;
        }
      } else if (Platform.isLinux()) {
        //
        // Failed to load the library normally - try to match libfoo.so.*
        //
        libraryPath = matchLibrary(libraryName, searchPath);
        if (libraryPath != null) {
          try {
            handle = Native.open(libraryPath, openFlags);
          } catch (UnsatisfiedLinkError e2) {
            e = e2;
          }
        }
      }
      // Search framework libraries on OS X
      else if (Platform.isMac() && !libraryName.endsWith(".dylib")) {
        libraryPath = matchFramework(libraryName);
        if (libraryPath != null) {
          try {
            handle = Native.open(libraryPath, openFlags);
          } catch (UnsatisfiedLinkError e2) {
            e = e2;
          }
        }
      }
      // Try the same library with a "lib" prefix
      else if (Platform.isWindows() && !isAbsolutePath) {
        libraryPath = findLibraryPath("lib" + libraryName, searchPath);
        try {
          handle = Native.open(libraryPath, openFlags);
        } catch (UnsatisfiedLinkError e2) {
          e = e2;
        }
      }
      // As a last resort, try to extract the library from the class
      // path, using the current context class loader.
      if (handle == 0) {
        try {
          File embedded =
              Native.extractFromResourcePath(
                  libraryName, (ClassLoader) options.get(Library.OPTION_CLASSLOADER));
          handle = Native.open(embedded.getAbsolutePath());
          // Don't leave temporary files around
          if (Native.isUnpacked(embedded)) {
            Native.deleteLibrary(embedded);
          }
        } catch (IOException e2) {
          e = new UnsatisfiedLinkError(e2.getMessage());
        }
      }

      if (handle == 0) {
        throw new UnsatisfiedLinkError(
            "Unable to load library '" + libraryName + "': " + e.getMessage());
      }
    }
    return new NativeLibrary(libraryName, libraryPath, handle, options);
  }
示例#17
0
  // Setup
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    Log.v("SDL", "Device: " + android.os.Build.DEVICE);
    Log.v("SDL", "Model: " + android.os.Build.MODEL);
    Log.v("SDL", "onCreate():" + mSingleton);
    super.onCreate(savedInstanceState);

    SDLActivity.initialize();
    // So we can call stuff from static callbacks
    mSingleton = this;

    // Load shared libraries
    String errorMsgBrokenLib = "";
    try {
      loadLibraries();
    } catch (UnsatisfiedLinkError e) {
      System.err.println(e.getMessage());
      mBrokenLibraries = true;
      errorMsgBrokenLib = e.getMessage();
    } catch (Exception e) {
      System.err.println(e.getMessage());
      mBrokenLibraries = true;
      errorMsgBrokenLib = e.getMessage();
    }

    if (mBrokenLibraries) {
      AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
      dlgAlert.setMessage(
          "An error occurred while trying to start the application. Please try again and/or reinstall."
              + System.getProperty("line.separator")
              + System.getProperty("line.separator")
              + "Error: "
              + errorMsgBrokenLib);
      dlgAlert.setTitle("SDL Error");
      dlgAlert.setPositiveButton(
          "Exit",
          new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
              // if this button is clicked, close current activity
              SDLActivity.mSingleton.finish();
            }
          });
      dlgAlert.setCancelable(false);
      dlgAlert.create().show();

      return;
    }

    // Set up the surface
    mSurface = new SDLSurface(getApplication());

    if (Build.VERSION.SDK_INT >= 12) {
      mJoystickHandler = new SDLJoystickHandler_API12();
    } else {
      mJoystickHandler = new SDLJoystickHandler();
    }

    mLayout = new AbsoluteLayout(this);
    mLayout.addView(mSurface);

    setContentView(mLayout);
  }
示例#18
0
  /**
   * Open the player
   *
   * @param remoteHost Remote host
   * @param remotePort Remote port
   */
  public void open(String remoteHost, int remotePort) {
    if (opened) {
      // Already opened
      return;
    }

    // Check video codec
    if (selectedVideoCodec == null) {
      notifyPlayerEventError("Video codec not selected");
      return;
    }

    // Init video encoder
    try {
      NativeH264EncoderParams nativeH264EncoderParams = new NativeH264EncoderParams();

      // Codec dimensions
      nativeH264EncoderParams.setFrameWidth(selectedVideoCodec.getWidth());
      nativeH264EncoderParams.setFrameHeight(selectedVideoCodec.getHeight());
      nativeH264EncoderParams.setFrameRate(selectedVideoCodec.getFramerate());
      nativeH264EncoderParams.setBitRate(selectedVideoCodec.getBitrate());

      // Codec profile and level
      nativeH264EncoderParams.setProfilesAndLevel(selectedVideoCodec.getCodecParams());

      // Codec settings optimization
      nativeH264EncoderParams.setEncMode(NativeH264EncoderParams.ENCODING_MODE_STREAMING);
      nativeH264EncoderParams.setSceneDetection(false);

      if (logger.isActivated()) {
        logger.info(
            "Init H264Encoder "
                + selectedVideoCodec.getCodecParams()
                + " "
                + selectedVideoCodec.getWidth()
                + "x"
                + selectedVideoCodec.getHeight()
                + " "
                + selectedVideoCodec.getFramerate()
                + " "
                + selectedVideoCodec.getBitrate());
      }
      int result = NativeH264Encoder.InitEncoder(nativeH264EncoderParams);
      if (result != 0) {
        notifyPlayerEventError("Encoder init failed with error code " + result);
        return;
      }
    } catch (UnsatisfiedLinkError e) {
      notifyPlayerEventError(e.getMessage());
      return;
    }

    // Init the RTP layer
    try {
      releasePort();
      rtpSender = new VideoRtpSender(videoFormat, localRtpPort);
      rtpInput = new MediaRtpInput();
      rtpInput.open();
      if (videoRenderer != null) {
        // The video renderer is supposed to be opened and so we used its RTP stream
        if (logger.isActivated()) {
          logger.debug("Player shares the renderer RTP stream");
        }
        rtpSender.prepareSession(
            rtpInput, remoteHost, remotePort, videoRenderer.getRtpInputStream(), this);
      } else {
        // The video renderer doesn't exist and so we create a new RTP stream
        rtpSender.prepareSession(rtpInput, remoteHost, remotePort, this);
      }

    } catch (Exception e) {
      notifyPlayerEventError(e.getMessage());
      return;
    }

    // Player is opened
    opened = true;
    notifyPlayerEventOpened();
  }
  @Override
  public int fitData(ICurveFitData[] dataArray) {
    int returnValue = 0;
    int noise = getNoiseModel().ordinal();

    // Corresponds to TRI2 'normal' stopping criteria.  ('strict' is 0.0001
    //   and 'very strict' is 0.000001.)
    double chiSquareDelta = 0.01;

    // load the native library, if not already loaded
    if (!s_libraryLoaded) {

      synchronized (s_synchObject) {

        // check again to see if some other thread loaded it
        if (!s_libraryLoaded) {

          // look for library on path
          try {
            // System.out.println("Using JNA");
            s_library = (CLibrary) Native.loadLibrary("slim-curve-1.0-SNAPSHOT", CLibrary.class);
            s_libraryLoaded = true;
            s_libraryOnPath = true;
          } catch (UnsatisfiedLinkError e) {
            System.out.println("Library not on path " + e.getMessage());
          }
        }

        if (!s_libraryLoaded) {
          // look for library in jar, using JNI
          // System.out.println("Using JNI");
          s_libraryLoaded =
              NativeLibraryUtil.loadVersionedNativeLibrary(this.getClass(), "slim-curve");
        }
      }
    }
    if (!s_libraryLoaded) {
      IJ.log("Native library not loaded.  Unable to do fit.");
      return 0;
    }

    // use arrays to pass double by reference
    double[] chiSquare = new double[1];
    double[] z = new double[1];
    double[] a = new double[1];
    double[] tau = new double[1];

    // count number of free parameters
    int numParamFree = 0;
    for (boolean free : m_free) {
      if (free) {
        ++numParamFree;
      }
    }

    if (FitAlgorithm.SLIMCURVE_RLD.equals(m_fitAlgorithm)
        || FitAlgorithm.SLIMCURVE_RLD_LMA.equals(m_fitAlgorithm)) {
      // RLD or triple integral fit

      // TODO ARG passing in array of data is broken
      for (ICurveFitData data : dataArray) {
        // set start and stop
        int start = data.getAdjustedDataStartIndex();
        int stop = data.getAdjustedTransEndIndex();
        double[] trans = data.getAdjustedTransient();

        // initialize parameters to be fitted
        a[0] = getEstimator().getDefaultA();
        tau[0] = getEstimator().getDefaultT();
        z[0] = getEstimator().getDefaultZ();

        // these lines give more TRI2 compatible fit results
        int RLDnoise = noise;
        if (FitAlgorithm.SLIMCURVE_RLD_LMA.equals(m_fitAlgorithm)) {
          start = getEstimator().getEstimateStartIndex(trans, start, stop);
          a[0] = getEstimator().getEstimateAValue(a[0], trans, start, stop);
          NoiseModel noiseModel = NoiseModel.values()[noise];
          RLDnoise = getEstimator().getEstimateNoiseModel(noiseModel).ordinal();
        }

        int chiSquareAdjust = stop - start - 3;

        returnValue =
            doRLDFit(
                m_xInc,
                trans,
                start,
                stop,
                m_instrumentResponse,
                null == m_instrumentResponse ? 0 : m_instrumentResponse.length,
                RLDnoise,
                data.getSig(),
                z,
                a,
                tau,
                data.getYFitted(),
                chiSquare,
                data.getChiSquareTarget() * chiSquareAdjust);
        // System.out.println("RLD returns " + returnValue);

        // TODO actually RLD fitting won't return an error code; in an error situation it should
        // recover with best guess probably
        // if (returnValue < 0) { System.out.println("RLD fails " + returnValue); ; return
        // returnValue; }//TODO ARG don't do LMA if RLD fails
        // TODO actually TRI2 recovers from a bad RLD estimate

        if (FitAlgorithm.SLIMCURVE_RLD.equals(m_fitAlgorithm)) {
          // set outgoing parameters; note m_free ignored here
          data.getParams()[0] = chiSquare[0] / chiSquareAdjust;
          data.getParams()[1] = z[0];
          data.getParams()[2] = a[0];
          data.getParams()[3] = tau[0];
        }
      }
    }

    if (FitAlgorithm.SLIMCURVE_LMA.equals(m_fitAlgorithm)
        || FitAlgorithm.SLIMCURVE_RLD_LMA.equals(m_fitAlgorithm)) {

      // TODO ARG the idea of processing many ICurveFitData's in a loop is broken; here and
      // elsewhere

      // if we are doing an LMA but just did an RLD estimate we may need to
      //   adjust those monoexponential RLD results to be initial estimates for
      //   a triexponential LMA fit, for example.
      if (FitAlgorithm.SLIMCURVE_RLD_LMA.equals(m_fitAlgorithm)) {
        getEstimator()
            .adjustEstimatedParams(
                dataArray[0].getParams(), m_free, m_fitFunction, a[0], tau[0], z[0]);
      }

      // LMA fit
      for (ICurveFitData data : dataArray) {

        // set start and stop
        int start = data.getAdjustedDataStartIndex();
        int stop = data.getAdjustedTransEndIndex();
        double[] trans = data.getAdjustedTransient();

        int chiSquareAdjust = stop - start - numParamFree;

        returnValue =
            doLMAFit(
                m_xInc,
                trans,
                start,
                stop,
                m_instrumentResponse,
                null == m_instrumentResponse ? 0 : m_instrumentResponse.length,
                noise,
                data.getSig(),
                data.getParams(),
                toIntArray(m_free),
                data.getParams().length - 1,
                data.getYFitted(),
                chiSquare,
                data.getChiSquareTarget() * chiSquareAdjust,
                chiSquareDelta);

        // System.out.println("LMA fit returns chisq of " + chiSquare[0] + " or " +
        // data.getParams()[0]);

        if (returnValue < 0 && returnValue != -2) { // Error code -2 means "k > MAX_ITERS"
          // error, so params are meaningless
          for (int i = 0; i < data.getParams().length; ++i) {
            data.getParams()[i] = Double.NaN;
          }
        } else {
          // compute reduced chi square
          data.getParams()[0] /= chiSquareAdjust;

          // compute AIC
          // System.out.println("chisq from LMA is " + chiSquare[0]);
          chiSquare[0] += 2 * numParamFree;
          data.setChiSquare(chiSquare[0]);
          // System.out.println(" -> becomes AIC " + chiSquare[0]);
          // TODO ARG since chisquare is returned in two places I am misusing one to be the AIC.
          //  if AIC based model selection takes off might be cleaner to add as a parameter?
        }
      }
    }

    return returnValue;
  }