static void run(
  const gchar *     name,
  gint              nparams,
	const GimpParam * param,
	gint *            nreturn_vals,
	GimpParam **      return_vals)
{
  static GimpParam values[2];   /* Gimp return values. !!! Allow 2: status and error message. */
  TGimpAdapterParameters pluginParameters;
  TImageSynthParameters engineParameters;
  
  GimpDrawable *drawable = NULL;
  GimpDrawable *corpus_drawable = NULL; 
  GimpDrawable *map_in_drawable= NULL; 
  GimpDrawable *map_out_drawable= NULL; 
  gboolean ok, with_map;
  
  /* 
  Local copies of pixmaps (not using gimp regions.) 
  2-D arrays of Pixel, addressable by Coordinates (Point).
  c++: static Bitmap<Pixelel>
  */
  Map targetMap;
  Map corpusMap;
  Map targetMaskMap;
  Map corpusMaskMap;
  
  int cancelFlag = 0;
  
  #ifdef SYNTH_THREADED
  // This is as early as it can be called.  Not sure it needs to be called.  See later call to it.
  // Call it early since calls to gdk, gtk might require this?
  g_thread_init(NULL);
  #endif

  #ifdef DEBUG
  gimp_message_set_handler(1); // To console instead of GUI
  start_time = clock();
  #endif
  
  // internationalization i18n
  // Note these constants are defined in the build environment.
  /*  Initialize i18n support  */
#if defined(G_OS_WIN32)
  bindtextdomain (GETTEXT_PACKAGE, gimp_locale_directory());
#else
  bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
#endif
#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif
  textdomain (GETTEXT_PACKAGE);

  *nreturn_vals = 1;
  *return_vals = values;
  values[0].type = GIMP_PDB_STATUS;
  values[0].data.d_status = GIMP_PDB_EXECUTION_ERROR; /* Unless everything succeeds. */
  
  drawable = gimp_drawable_get(param[2].data.d_drawable);

  /* Check image type (could be called non-interactive) */
  if (!gimp_drawable_is_rgb(drawable->drawable_id) &&
      !gimp_drawable_is_gray(drawable->drawable_id)) 
  {
    ERROR_RETURN(_("Incompatible image mode."));
  }


  /* Deal with run mode */
  ok = FALSE;
  switch(param[0].data.d_int32) 
  {
    case GIMP_RUN_INTERACTIVE :
      ok = get_last_parameters(&pluginParameters,drawable->drawable_id, RESYNTH_ENGINE_PDB_NAME);
      gimp_message("Resynthesizer engine should not be called interactively");
      /* But keep going with last (or default) parameters, really no harm. */
      break;
    case GIMP_RUN_NONINTERACTIVE :
      ok = get_parameters_from_list(&pluginParameters, nparams, param); 
      break;
    case GIMP_RUN_WITH_LAST_VALS :
      ok = get_last_parameters(&pluginParameters,drawable->drawable_id, RESYNTH_ENGINE_PDB_NAME); 
      break;
  }

  if (!ok) 
  {
    ERROR_RETURN(_("Resynthesizer failed to get parameters."));
  }
  
  /* Limit neighbours parameter to size allocated. */
  if (pluginParameters.neighbours > IMAGE_SYNTH_MAX_NEIGHBORS )
    pluginParameters.neighbours = IMAGE_SYNTH_MAX_NEIGHBORS;
  
  corpus_drawable = gimp_drawable_get(pluginParameters.corpus_id);
  
  /* The target and corpus must have the same base type.
  In earlier version, they must have the same bpp.
  But now we don't compare the alphas, so they can differ in presence of alpha.
  */
  if (! equal_basetypes(drawable, corpus_drawable) )
  {
    ERROR_RETURN(_("The input texture and output image must have the same number of color channels."));
  }
  
  
  with_map = (pluginParameters.input_map_id != -1 && pluginParameters.output_map_id != -1);
  /* If only one map is passed, it is ignored quietly. */
  map_in_drawable=0;
  map_out_drawable=0;

  if (with_map) 
  {
    map_in_drawable = gimp_drawable_get(pluginParameters.input_map_id);
    map_out_drawable = gimp_drawable_get(pluginParameters.output_map_id);
    /* All these can be wrong at the same time.  
    Forego userfriendliness for ease of programming: abort on first error
    */
    if ( ! equal_basetypes(map_in_drawable, map_out_drawable) )
    {
      /* Maps need the same base type. Formerly needed the same bpp. */
      ERROR_RETURN(_("The input and output maps must have the same mode"));
    } 
    if (map_in_drawable->width != corpus_drawable->width || 
               map_in_drawable->height != corpus_drawable->height) 
    {
      ERROR_RETURN(_("The input map should be the same size as the input texture image"));
    } 
    if (map_out_drawable->width != drawable->width || 
               map_out_drawable->height != drawable->height) 
    {
      ERROR_RETURN(_("The output map should be the same size as the output image"));
    }
  }

  /* 
  The engine should not be run interactively so no need to store last values. 
  I.E. the meaning of "last" is "last values set by user interaction".
  */
  
  #ifdef ANIMATE
  // Copy local pointer vars to globals
  targetDrawableCopy = drawable;
  targetMapCopy = &targetMap;
  #endif
  
  /* Error checks done, initialization work begins.  So start progress callbacks. */
  progressStart("Initializing...");
  
  /* 
  Set flags for presence of alpha channels. 
  The flag is an optimization.  Alternatives:
  - a function
  - OR standardize the internal pixmap to ALWAYS have an alpha pixelel
  initialized to VISIBLE and set from any alpha pixelel.
  */
  gboolean is_alpha_image = gimp_drawable_has_alpha(drawable->drawable_id);
  gboolean is_alpha_corpus = gimp_drawable_has_alpha(corpus_drawable->drawable_id);
  
  // Image adaption requires format indices
  // WAS  prepareImageFormatIndices(drawable, corpus_drawable, with_map, map_in_drawable);
  TFormatIndices formatIndices;
  
  guint map_count = (with_map? count_color_channels(map_in_drawable) : 0 );
    
  prepareImageFormatIndices(
    &formatIndices,
    count_color_channels(drawable),
    map_count,
    is_alpha_image,
    is_alpha_corpus,
    with_map
    );
  
  #ifdef ADAPT_SIMPLE
    /* Adapt Gimp to an engine with a simpler interface. */
    setDefaultParams(&parameters);
    ImageBuffer imageBuffer;
    ImageBuffer maskBuffer;
    
    // TODO change to new signature
    adaptGimpToSimple(drawable, &imageBuffer, &maskBuffer);  // From Gimp to simple
    g_printf("Here3\n");
    adaptSimpleAPI(&imageBuffer, &maskBuffer);        // From simple to existing engine API
    
  #else
    g_printf("Gimp adaption\n");
    /* target/context adaption */
    fetch_image_mask_map(drawable, &targetMap, formatIndices.total_bpp, 
      &targetMaskMap, 
      MASK_TOTALLY_SELECTED, 
      map_out_drawable, formatIndices.map_start_bip);
    
      #ifdef ANIMATE
      clear_target_pixels(formatIndices.colorEndBip);  // For debugging, blacken so new colors sparkle
      #endif
  
    /*  corpus adaption */
    fetch_image_mask_map(corpus_drawable, &corpusMap, formatIndices.total_bpp, 
      &corpusMaskMap,
      MASK_TOTALLY_SELECTED, 
      map_in_drawable, formatIndices.map_start_bip);
      
    // TODO These are artifacts of earlier design, not used.
    free_map(&corpusMaskMap);
    free_map(&targetMaskMap);
    
    adaptParameters(&pluginParameters, &engineParameters);
    
  #endif
  
  // After possible adaption, check size again
  g_assert(targetMap.width * targetMap.height); // Image is not empty
  g_assert(corpusMap.width * corpusMap.height); // Corpus is not empty
  
  // Done with adaption: now main image data in canonical pixmaps, etc.
  // Begin real work
  progressStart("synthesizing...");
  
  int result = engine(
    engineParameters, 
    &formatIndices, 
    &targetMap, 
    &corpusMap,
    progressUpdate,
    (void *) 0,
    &cancelFlag
    );
  
  if (result == IMAGE_SYNTH_ERROR_EMPTY_CORPUS)
  {
    ERROR_RETURN(_("The texture source is empty. Does any selection include non-transparent pixels?"));
  }
  else if  (result == IMAGE_SYNTH_ERROR_EMPTY_TARGET )
  {
    ERROR_RETURN(_("The output layer is empty. Does any selection have visible pixels in the active layer?"));
  }
  
  // Normal post-process adaption follows

  /* dump_target_points(); */ /* detailed debugging. */
  // print_post_stats();
  
  // Update Gimp image from local pixmap
  // Note this works even for test harness where ADAPT_SIMPLE
  // but then it does NOT test returning results in buffer.
  
  /* 
  We could test antiAdaptImage() here.
  But antiAdaptImage() has already been tested once on the incoming side.
  So no compelling need to test it again here.
  */
  post_results_to_gimp(drawable, targetMap); 
  
  /* Clean up */
  // Adapted
  free_map(&targetMap);
  free_map(&corpusMap);
  // GIMP
  detach_drawables(drawable, corpus_drawable, map_in_drawable, map_out_drawable);
  gimp_progress_end();
  values[0].data.d_status = GIMP_PDB_SUCCESS;
} 
    EndCriteria::Type DifferentialEvolution::minimize(Problem& P,
											const EndCriteria& endCriteria) {

		EndCriteria::Type ecType = EndCriteria::MaxIterations;
	    QL_REQUIRE(P.currentValue().size() == nParam_,
			"Number of parameters mismatch between problem and DE optimizer");
        P.reset();		
		init();

		Real bestCost = QL_MAX_REAL;
		Size bestPop  = 0;
		for (Size p = 0; p < nPop_; ++p) {
			Array tmp(currGen_[p].pop_);
			try {
				currGen_[p].cost_ = P.costFunction().value(tmp);
			} catch (Error&) {
				currGen_[p].cost_ = QL_MAX_REAL;
			}
			if (currGen_[p].cost_ < bestCost) {
				bestPop = p;
				bestCost = currGen_[p].cost_;
			}
		}

		Size lastChange = 0;
		Size lastParamChange = 0;
		for(Size i=0; i<endCriteria.maxIterations(); ++i) {

			Size newBestPop = bestPop;
			Real newBestCost = bestCost;

			for (Size p=0; p<nPop_; ++p) {
				// Find 3 different populations randomly
				Size r1;
				do {
					r1 = static_cast <Size> (uniformRng_.nextInt32() % nPop_);
				}		
				while(r1 == p || r1 == bestPop);

				Size r2;
				do {
					r2 = static_cast <Size> (uniformRng_.nextInt32() % nPop_);
				}
				while ( r2 == p || r2 == bestPop || r2 == r1);

				Size r3;
				do {
					r3 = static_cast <Size> (uniformRng_.nextInt32() % nPop_);
				} while ( r3 == p || r3 == bestPop || r3 == r1 || r3 == r2);

				for(Size j=0; j<nParam_; ++j) {
					nextGen_[p].pop_[j] = currGen_[p].pop_[j];
				}

				Size j = static_cast <Size> (uniformRng_.nextInt32() % nParam_);
				Size L = 0;
				do {
					const double tmp = 
						currGen_[      p].pop_[j] * a0_
					  + currGen_[     r1].pop_[j] * a1_
					  + currGen_[     r2].pop_[j] * a2_
					  + currGen_[     r3].pop_[j] * a3_
					  + currGen_[bestPop].pop_[j] * aBest_;

					nextGen_[p].pop_[j] =
						std::min(maxParams_[j], std::max(minParams_[j], tmp));

					j = (j+1)%nParam_;
					++L;
				} while ((uniformRng_.nextReal() < CR_) && (L < nParam_));

				// Evaluate the new population
				Array tmp(nextGen_[p].pop_);
				try {
					nextGen_[p].cost_ = P.costFunction().value(tmp);
                } catch (Error&) {
					nextGen_[p].cost_ = QL_MAX_REAL;
                }

				// Not better, discard it and keep the old one.
				if (nextGen_[p].cost_ >= currGen_[p].cost_) {
					nextGen_[p] = currGen_[p];
				}
				// Better, keep it.
				else {
					// New best?
					if (nextGen_[p].cost_ < newBestCost) {
						newBestPop = p;
						newBestCost = nextGen_[p].cost_;
					}
				}
			}

			if(std::abs(newBestCost-bestCost) > endCriteria.functionEpsilon()) {
				lastChange = i;
			}
			const Array absDiff = Abs(nextGen_[newBestPop].pop_-currGen_[bestPop].pop_);
			if(*std::max_element(absDiff.begin(), absDiff.end()) > endCriteria.rootEpsilon()) {
				lastParamChange = i;
			}

			bestPop = newBestPop;
			bestCost = newBestCost;
			currGen_ = nextGen_;

            if(i-lastChange > endCriteria.maxStationaryStateIterations()) {
				ecType = EndCriteria::StationaryFunctionValue;
				break;
			}
			if(i-lastParamChange > endCriteria.maxStationaryStateIterations()) {
				ecType = EndCriteria::StationaryPoint;
				break;
			}

            if (adaptive_) adaptParameters();
		}
		
		const Array res(currGen_[bestPop].pop_);
        P.setCurrentValue(res);
        P.setFunctionValue(bestCost);
        
        return ecType;
    }