Fixed compile warnings re: type safety

Fixed compile warnings re: type safety

--- nucleusSegmentation/src/include/utilityTileAnalysis.h
+++ nucleusSegmentation/src/include/utilityTileAnalysis.h
@@ -25,10 +25,10 @@
 #include "itkRelabelComponentImageFilter.h"

 #include "Normalization.h"
+#include "HistologicalEntities.h"
 #include "BinaryMaskAnalysisFilter.h"
 #include "SFLSLocalChanVeseSegmentor2D.h"

-
 #include "itkTypedefs.h"

 #include "utilityScalarImage.h"
@@ -36,817 +36,845 @@

 #include "time.h"

-namespace ImagenomicAnalytics
-{
-  namespace TileAnalysis
-  {
-    //--------------------------------------------------------------------------------
-    // Extract hematoxylin channel
-    template<typename TNull>
-      itkUCharImageType::Pointer ExtractHematoxylinChannel(itkRGBImageType::Pointer HAndEImage) {
-      int width = HAndEImage->GetLargestPossibleRegion().GetSize()[0];
-      int height = HAndEImage->GetLargestPossibleRegion().GetSize()[1];
-
-      std::string stainType = "H&E";
-
-      double leng, A, V, C, log255 = log(255.0);
-      int i, j;
-      int channelIndex = 0; ///< 0: Hematoxylin; 1: Eosin
-      double MODx[3];
-      double MODy[3];
-      double MODz[3];
-      double cosx[3];
-      double cosy[3];
-      double cosz[3];
-      double len[3];
-      double q[9];
-      // unsigned char rLUT[256];
-      // unsigned char gLUT[256];
-      // unsigned char bLUT[256];
-
-      //if (!stainType.compare("H&E"))
-      {
-	// GL Haem matrix
-	MODx[0] = 0.644211; //0.650;
-	MODy[0] = 0.716556; //0.704;
-	MODz[0] = 0.266844; //0.286;
-	// GL Eos matrix
-	MODx[1] = 0.092789; //0.072;
-	MODy[1] = 0.954111; //0.990;
-	MODz[1] = 0.283111; //0.105;
-	// Zero matrix
-	MODx[2] = 0.0;
-	MODy[2] = 0.0;
-	MODz[2] = 0.0;
-      }
-
-
-      // start
-      for (i = 0; i < 3; i++) {
-	//normalise vector length
-	cosx[i] = cosy[i] = cosz[i] = 0.0;
-	len[i] = sqrt(MODx[i] * MODx[i] + MODy[i] * MODy[i] + MODz[i] * MODz[i]);
-	if (len[i] != 0.0) {
-	  cosx[i] = MODx[i] / len[i];
-	  cosy[i] = MODy[i] / len[i];
-	  cosz[i] = MODz[i] / len[i];
-	}
-      }
-
-
-      // translation matrix
-      if (cosx[1] == 0.0) { //2nd colour is unspecified
-	if (cosy[1] == 0.0) {
-	  if (cosz[1] == 0.0) {
-	    cosx[1] = cosz[0];
-	    cosy[1] = cosx[0];
-	    cosz[1] = cosy[0];
-	  }
-	}
-      }
-
-      if (cosx[2] == 0.0) { // 3rd colour is unspecified
-	if (cosy[2] == 0.0) {
-	  if (cosz[2] == 0.0) {
-	    if ((cosx[0] * cosx[0] + cosx[1] * cosx[1]) > 1) {
-	      cosx[2] = 0.0;
-	    } else {
-	      cosx[2] = sqrt(1.0 - (cosx[0] * cosx[0]) - (cosx[1] * cosx[1]));
-	    }
-
-	    if ((cosy[0] * cosy[0] + cosy[1] * cosy[1]) > 1) {
-	      cosy[2] = 0.0;
-	    } else {
-	      cosy[2] = sqrt(1.0 - (cosy[0] * cosy[0]) - (cosy[1] * cosy[1]));
-	    }
-
-	    if ((cosz[0] * cosz[0] + cosz[1] * cosz[1]) > 1) {
-	      cosz[2] = 0.0;
-	    } else {
-	      cosz[2] = sqrt(1.0 - (cosz[0] * cosz[0]) - (cosz[1] * cosz[1]));
-	    }
-	  }
-	}
-      }
-
-      leng = sqrt(cosx[2] * cosx[2] + cosy[2] * cosy[2] + cosz[2] * cosz[2]);
-
-      cosx[2] = cosx[2] / leng;
-      cosy[2] = cosy[2] / leng;
-      cosz[2] = cosz[2] / leng;
-
-      for (i = 0; i < 3; i++) {
-	if (cosx[i] == 0.0) cosx[i] = 0.001;
-	if (cosy[i] == 0.0) cosy[i] = 0.001;
-	if (cosz[i] == 0.0) cosz[i] = 0.001;
-      }
-
-      //matrix inversion
-      A = cosy[1] - cosx[1] * cosy[0] / cosx[0];
-      V = cosz[1] - cosx[1] * cosz[0] / cosx[0];
-      C = cosz[2] - cosy[2] * V / A + cosx[2] * (V / A * cosy[0] / cosx[0] - cosz[0] / cosx[0]);
-      q[2] = (-cosx[2] / cosx[0] - cosx[2] / A * cosx[1] / cosx[0] * cosy[0] / cosx[0] +
-	      cosy[2] / A * cosx[1] / cosx[0]) / C;
-      q[1] = -q[2] * V / A - cosx[1] / (cosx[0] * A);
-      q[0] = 1.0 / cosx[0] - q[1] * cosy[0] / cosx[0] - q[2] * cosz[0] / cosx[0];
-      q[5] = (-cosy[2] / A + cosx[2] / A * cosy[0] / cosx[0]) / C;
-      q[4] = -q[5] * V / A + 1.0 / A;
-      q[3] = -q[4] * cosy[0] / cosx[0] - q[5] * cosz[0] / cosx[0];
-      q[8] = 1.0 / C;
-      q[7] = -q[8] * V / A;
-      q[6] = -q[7] * cosy[0] / cosx[0] - q[8] * cosz[0] / cosx[0];
-
-      // initialize 3 output colour stacks
-      itkUCharImageType::Pointer hematoxylinChannel = itkUCharImageType::New();
-      hematoxylinChannel->SetRegions(HAndEImage->GetLargestPossibleRegion());
-      hematoxylinChannel->Allocate();
-      hematoxylinChannel->CopyInformation(HAndEImage);
-
-      itkUCharImageType::PixelType *newpixels = hematoxylinChannel->GetBufferPointer();
-
-      // for (j=0; j<256; j++)
-      //   {
-      //     rLUT[255-j]=static_cast<unsigned char>(255.0 - (double)j * cosx[channelIndex]);
-      //     gLUT[255-j]=static_cast<unsigned char>(255.0 - (double)j * cosy[channelIndex]);
-      //     bLUT[255-j]=static_cast<unsigned char>(255.0 - (double)j * cosz[channelIndex]);
-      //   }
-
-      // translate ------------------
-      int imagesize = width * height;
-
-      itkRGBImageType::PixelType *rgbImagePointer = HAndEImage->GetBufferPointer();
-
-      for (j = 0; j < imagesize; j++) {
-	// log transform the RGB data
-	unsigned char R = rgbImagePointer[j].GetRed();
-	unsigned char G = rgbImagePointer[j].GetGreen();
-	unsigned char B = rgbImagePointer[j].GetBlue();
-	double Rlog = -((255.0 * log((static_cast<double>(R) + 1) / 255.0)) / log255);
-	double Glog = -((255.0 * log((static_cast<double>(G) + 1) / 255.0)) / log255);
-	double Blog = -((255.0 * log((static_cast<double>(B) + 1) / 255.0)) / log255);
-
-	// rescale to match original paper values
-	double Rscaled = Rlog * q[channelIndex * 3];
-	double Gscaled = Glog * q[channelIndex * 3 + 1];
-	double Bscaled = Blog * q[channelIndex * 3 + 2];
-	double output = exp(-((Rscaled + Gscaled + Bscaled) - 255.0) * log255 / 255.0);
-
-	if (output > 255) {
-	  output = 255;
-	}
-
-	unsigned char idx = static_cast<unsigned char>(0xff & static_cast<int>(floor(output + .5)));
-
-	////////////////////////////////////////////////////////////////////////////////
-	/// Index to rgb to gray
-	///
-	/// The original ImageJ plugin output the colorful H
-	/// channel as a indexed image using a LUT. Here I first
-	/// use the LUT to convert the index to rgb and then
-	/// convert to gray. The formula below is what we have
-	/// in matlab rgb2gray
-	//newpixels[j] = static_cast<itkUCharImageType::PixelType>(0.2989*rLUT[idx] + 0.5870*gLUT[idx] + 0.1140*bLUT[idx]);
-	newpixels[j] = idx;
-	/// Index to rgb to gray, end
-	////////////////////////////////////////////////////////////////////////////////
-      }
-
-
-      return hematoxylinChannel;
-    }
-    //================================================================================
-
-
-    template<typename TNull>
-      cv::Mat normalizeImageColor(cv::Mat image) {
-      float meanT[3] = {-0.632356, -0.0516004, 0.0376543};
-      float stdT[3] = {0.26235, 0.0514831,
-		       0.0114217}; ///< These are learnt from the tempalte GBM image selected by George
-      cv::Mat newImgCV = nscale::Normalization::normalization(image, meanT, stdT);
-
-      return newImgCV;
-    }
-
-
-    template<typename TNull>
-      itkUCharImageType::Pointer extractTissueMask(cv::Mat image) {
-      float mData[8] = {-0.154, 0.035, 0.549, -45.718, -0.057, -0.817, 1.170, -49.887};
-      cv::Mat M = cv::Mat(2, 4, CV_32FC1, &mData);
-
-      cv::Mat maskCV = nscale::Normalization::segFG(image, M);
-      itkUCharImageType::Pointer foregroundMask = itk::OpenCVImageBridge::CVMatToITKImage<itkUCharImageType>(
-													     maskCV);
-
-      return foregroundMask;
-    }
-
-
-    template<typename InputImageType>
-      std::vector<typename InputImageType::PixelType>
-      computeMultipleThresholdsForGrayScaleImage(typename InputImageType::Pointer inputImage)
-      {
-	typedef typename InputImageType::PixelType PixelType;
-	std::vector<PixelType> multipleThresholds;
-
-	{
-	  typedef itk::HuangThresholdImageFilter <InputImageType, InputImageType> CalculatorType;
-	  typename CalculatorType::Pointer calculator = CalculatorType::New();
-	  calculator->SetInput(inputImage);
-	  calculator->Update();
-	  multipleThresholds.push_back(calculator->GetThreshold());
-	}
-
-	/* { */
-	/*   typedef itk::IntermodesThresholdImageFilter<InputImageType, InputImageType> CalculatorType; */
-	/*   typename CalculatorType::Pointer calculator = CalculatorType::New(); */
-	/*   calculator->SetInput(inputImage); */
-	/*   calculator->Update(); */
-	/*   multipleThresholds.push_back(calculator->GetThreshold()); */
-	/* } */
-
-	{
-	  typedef itk::IsoDataThresholdImageFilter <InputImageType, InputImageType> CalculatorType;
-	  typename CalculatorType::Pointer calculator = CalculatorType::New();
-	  calculator->SetInput(inputImage);
-	  calculator->Update();
-	  multipleThresholds.push_back(calculator->GetThreshold());
-	}
-
-	/* { */
-	/*   typedef itk::KittlerIllingworthThresholdImageFilter<InputImageType, InputImageType> CalculatorType; */
-	/*   typename CalculatorType::Pointer calculator = CalculatorType::New(); */
-	/*   calculator->SetInput(inputImage); */
-	/*   calculator->Update(); */
-	/*   multipleThresholds.push_back(calculator->GetThreshold()); */
-	/* } */
-
-	{
-	  typedef itk::LiThresholdImageFilter <InputImageType, InputImageType> CalculatorType;
-	  typename CalculatorType::Pointer calculator = CalculatorType::New();
-	  calculator->SetInput(inputImage);
-	  calculator->Update();
-	  multipleThresholds.push_back(calculator->GetThreshold());
-	}
-
-	{
-	  typedef itk::MaximumEntropyThresholdImageFilter <InputImageType, InputImageType> CalculatorType;
-	  typename CalculatorType::Pointer calculator = CalculatorType::New();
-	  calculator->SetInput(inputImage);
-	  calculator->Update();
-	  multipleThresholds.push_back(calculator->GetThreshold());
-	}
-
-	{
-	  typedef itk::MomentsThresholdImageFilter <InputImageType, InputImageType> CalculatorType;
-	  typename CalculatorType::Pointer calculator = CalculatorType::New();
-	  calculator->SetInput(inputImage);
-	  calculator->Update();
-	  multipleThresholds.push_back(calculator->GetThreshold());
-	}
-
-	{
-	  typedef itk::OtsuThresholdImageFilter <InputImageType, InputImageType, InputImageType> CalculatorType;
-	  typename CalculatorType::Pointer calculator = CalculatorType::New();
-	  calculator->SetInput(inputImage);
-	  calculator->Update();
-	  multipleThresholds.push_back(calculator->GetThreshold());
-	}
-
-	{
-	  typedef itk::RenyiEntropyThresholdImageFilter <InputImageType, InputImageType> CalculatorType;
-	  typename CalculatorType::Pointer calculator = CalculatorType::New();
-	  calculator->SetInput(inputImage);
-	  calculator->Update();
-	  multipleThresholds.push_back(calculator->GetThreshold());
-	}
-
-	{
-	  typedef itk::ShanbhagThresholdImageFilter <InputImageType, InputImageType> CalculatorType;
-	  typename CalculatorType::Pointer calculator = CalculatorType::New();
-	  calculator->SetInput(inputImage);
-	  calculator->Update();
-	  multipleThresholds.push_back(calculator->GetThreshold());
-	}
-
-	{
-	  typedef itk::TriangleThresholdImageFilter <InputImageType, InputImageType> CalculatorType;
-	  typename CalculatorType::Pointer calculator = CalculatorType::New();
-	  calculator->SetInput(inputImage);
-	  calculator->Update();
-	  multipleThresholds.push_back(calculator->GetThreshold());
-	}
-
-	{
-	  typedef itk::YenThresholdImageFilter <InputImageType, InputImageType> CalculatorType;
-	  typename CalculatorType::Pointer calculator = CalculatorType::New();
-	  calculator->SetInput(inputImage);
-	  calculator->Update();
-	  multipleThresholds.push_back(calculator->GetThreshold());
-	}
-
-	return multipleThresholds;
-      }
-
-
-    template<typename InputImageType, typename OutputImageType>
-      typename OutputImageType::Pointer
-      optimalThresholdImage(typename InputImageType::Pointer inputImage,
-			    typename OutputImageType::PixelType maskValue, float &theThreshold)
-    {
-      itkFloatImageType::Pointer image = ScalarImage::castItkImage<InputImageType, itkFloatImageType>(inputImage);
-
-      std::vector<itkFloatImageType::PixelType> a = computeMultipleThresholdsForGrayScaleImage<itkFloatImageType>(image);
-      std::sort(a.begin(), a.end());
-
-      float ratio = 0.75;
-      long n = static_cast<long>(ratio * static_cast<float>(a.size()));
-
-      theThreshold = a[n];
-
-      typename OutputImageType::Pointer mask = OutputImageType::New();
-      mask->SetRegions(image->GetLargestPossibleRegion());
-      mask->Allocate();
-      mask->FillBuffer(0);
-      const itkFloatImageType::PixelType *imageBufferPointer = image->GetBufferPointer();
-      typename OutputImageType::PixelType *maskBufferPointer = mask->GetBufferPointer();
-      std::size_t numPixels = mask->GetLargestPossibleRegion().GetNumberOfPixels();
-      for (std::size_t it = 0; it < numPixels; ++it) {
-	maskBufferPointer[it] = imageBufferPointer[it] <= theThreshold ? maskValue : 0;
-      }
-
-      return mask;
-    }
-
-    template<typename TNull>
-      itkUCharImageType::Pointer processTile(cv::Mat thisTileCV, \
-					     itkUShortImageType::Pointer &outputLabelImageUShort, \
-					     float otsuRatio = 1.0, \
-					     double curvatureWeight = 0.8, \
-					     float sizeThld = 3, \
-					     float sizeUpperThld = 200, \
-					     double mpp = 0.25, \
-					     float msKernel = 20.0, \
-					     int levelsetNumberOfIteration = 100, \
-					     bool doDeclump = false)
-    {
-      std::cout << "normalizeImageColor.....\n" << std::flush;
-      cv::Mat newImgCV = normalizeImageColor<char>(thisTileCV);
-
-      std::cout << "extractTissueMask.....\n" << std::flush;
-      itkUCharImageType::Pointer foregroundMask = extractTissueMask<char>(newImgCV);
-
-      itkRGBImageType::Pointer thisTile = itk::OpenCVImageBridge::CVMatToITKImage<itkRGBImageType>(thisTileCV);
-
-      //IO::writeImage<itkRGBImageType>(thisTile, "thisTile.png", 0);
-
-      std::cout << "ExtractHematoxylinChannel.....\n" << std::flush;
-      itkUCharImageType::Pointer hematoxylinImage = ExtractHematoxylinChannel<char>(thisTile);
-
-      short maskValue = 1;
-
-      itkFloatImageType::Pointer hemaFloat = ScalarImage::castItkImage<itkUCharImageType, itkFloatImageType>(
-                                                                                hematoxylinImage);
-
-      std::cout << "ThresholdImage.....\n" << std::flush;
-
-      itkUCharImageType::Pointer nucleusBinaryMask = ScalarImage::otsuThresholdImage<char>(hemaFloat, maskValue,
-                                                                                otsuRatio);
-
-      long numPixels = nucleusBinaryMask->GetLargestPossibleRegion().GetNumberOfPixels();
-
-      //std::cout<<"output otsuThresholdImage.....\n"<<std::flush;
-      //ImagenomicAnalytics::IO::writeImage<itkUCharImageType>(nucleusBinaryMask, "nucleusBinaryMask.png", 0);
-
-      if (foregroundMask) {
-        const itkUCharImageType::PixelType *fgMaskBufferPointer = foregroundMask->GetBufferPointer();
-        itkBinaryMaskImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-
-        for (long it = 0; it < numPixels; ++it) {
-          if (0 == fgMaskBufferPointer[it]) {
-            // for sure glass region
-            nucleusBinaryMaskBufferPointer[it] = 0;
-          }
+namespace ImagenomicAnalytics {
+    namespace TileAnalysis {
+        //--------------------------------------------------------------------------------
+        // Extract hematoxylin channel
+        template<typename TNull>
+        itkUCharImageType::Pointer ExtractHematoxylinChannel(itkRGBImageType::Pointer HAndEImage) {
+            int width = HAndEImage->GetLargestPossibleRegion().GetSize()[0];
+            int height = HAndEImage->GetLargestPossibleRegion().GetSize()[1];
+
+            std::string stainType = "H&E";
+
+            double leng, A, V, C, log255 = log(255.0);
+            int i, j;
+            int channelIndex = 0; ///< 0: Hematoxylin; 1: Eosin
+            double MODx[3];
+            double MODy[3];
+            double MODz[3];
+            double cosx[3];
+            double cosy[3];
+            double cosz[3];
+            double len[3];
+            double q[9];
+            // unsigned char rLUT[256];
+            // unsigned char gLUT[256];
+            // unsigned char bLUT[256];
+
+            //if (!stainType.compare("H&E"))
+            {
+                // GL Haem matrix
+                MODx[0] = 0.644211; //0.650;
+                MODy[0] = 0.716556; //0.704;
+                MODz[0] = 0.266844; //0.286;
+                // GL Eos matrix
+                MODx[1] = 0.092789; //0.072;
+                MODy[1] = 0.954111; //0.990;
+                MODz[1] = 0.283111; //0.105;
+                // Zero matrix
+                MODx[2] = 0.0;
+                MODy[2] = 0.0;
+                MODz[2] = 0.0;
+            }
+
+
+            // start
+            for (i = 0; i < 3; i++) {
+                //normalise vector length
+                cosx[i] = cosy[i] = cosz[i] = 0.0;
+                len[i] = sqrt(MODx[i] * MODx[i] + MODy[i] * MODy[i] + MODz[i] * MODz[i]);
+                if (len[i] != 0.0) {
+                    cosx[i] = MODx[i] / len[i];
+                    cosy[i] = MODy[i] / len[i];
+                    cosz[i] = MODz[i] / len[i];
+                }
+            }
+
+
+            // translation matrix
+            if (cosx[1] == 0.0) { //2nd colour is unspecified
+                if (cosy[1] == 0.0) {
+                    if (cosz[1] == 0.0) {
+                        cosx[1] = cosz[0];
+                        cosy[1] = cosx[0];
+                        cosz[1] = cosy[0];
+                    }
+                }
+            }
+
+            if (cosx[2] == 0.0) { // 3rd colour is unspecified
+                if (cosy[2] == 0.0) {
+                    if (cosz[2] == 0.0) {
+                        if ((cosx[0] * cosx[0] + cosx[1] * cosx[1]) > 1) {
+                            cosx[2] = 0.0;
+                        } else {
+                            cosx[2] = sqrt(1.0 - (cosx[0] * cosx[0]) - (cosx[1] * cosx[1]));
+                        }
+
+                        if ((cosy[0] * cosy[0] + cosy[1] * cosy[1]) > 1) {
+                            cosy[2] = 0.0;
+                        } else {
+                            cosy[2] = sqrt(1.0 - (cosy[0] * cosy[0]) - (cosy[1] * cosy[1]));
+                        }
+
+                        if ((cosz[0] * cosz[0] + cosz[1] * cosz[1]) > 1) {
+                            cosz[2] = 0.0;
+                        } else {
+                            cosz[2] = sqrt(1.0 - (cosz[0] * cosz[0]) - (cosz[1] * cosz[1]));
+                        }
+                    }
+                }
+            }
+
+            leng = sqrt(cosx[2] * cosx[2] + cosy[2] * cosy[2] + cosz[2] * cosz[2]);
+
+            cosx[2] = cosx[2] / leng;
+            cosy[2] = cosy[2] / leng;
+            cosz[2] = cosz[2] / leng;
+
+            for (i = 0; i < 3; i++) {
+                if (cosx[i] == 0.0) cosx[i] = 0.001;
+                if (cosy[i] == 0.0) cosy[i] = 0.001;
+                if (cosz[i] == 0.0) cosz[i] = 0.001;
+            }
+
+            //matrix inversion
+            A = cosy[1] - cosx[1] * cosy[0] / cosx[0];
+            V = cosz[1] - cosx[1] * cosz[0] / cosx[0];
+            C = cosz[2] - cosy[2] * V / A + cosx[2] * (V / A * cosy[0] / cosx[0] - cosz[0] / cosx[0]);
+            q[2] = (-cosx[2] / cosx[0] - cosx[2] / A * cosx[1] / cosx[0] * cosy[0] / cosx[0] +
+                    cosy[2] / A * cosx[1] / cosx[0]) / C;
+            q[1] = -q[2] * V / A - cosx[1] / (cosx[0] * A);
+            q[0] = 1.0 / cosx[0] - q[1] * cosy[0] / cosx[0] - q[2] * cosz[0] / cosx[0];
+            q[5] = (-cosy[2] / A + cosx[2] / A * cosy[0] / cosx[0]) / C;
+            q[4] = -q[5] * V / A + 1.0 / A;
+            q[3] = -q[4] * cosy[0] / cosx[0] - q[5] * cosz[0] / cosx[0];
+            q[8] = 1.0 / C;
+            q[7] = -q[8] * V / A;
+            q[6] = -q[7] * cosy[0] / cosx[0] - q[8] * cosz[0] / cosx[0];
+
+            // initialize 3 output colour stacks
+            itkUCharImageType::Pointer hematoxylinChannel = itkUCharImageType::New();
+            hematoxylinChannel->SetRegions(HAndEImage->GetLargestPossibleRegion());
+            hematoxylinChannel->Allocate();
+            hematoxylinChannel->CopyInformation(HAndEImage);
+
+            itkUCharImageType::PixelType *newpixels = hematoxylinChannel->GetBufferPointer();
+
+            // for (j=0; j<256; j++)
+            //   {
+            //     rLUT[255-j]=static_cast<unsigned char>(255.0 - (double)j * cosx[channelIndex]);
+            //     gLUT[255-j]=static_cast<unsigned char>(255.0 - (double)j * cosy[channelIndex]);
+            //     bLUT[255-j]=static_cast<unsigned char>(255.0 - (double)j * cosz[channelIndex]);
+            //   }
+
+            // translate ------------------
+            int imagesize = width * height;
+
+            itkRGBImageType::PixelType *rgbImagePointer = HAndEImage->GetBufferPointer();
+
+            for (j = 0; j < imagesize; j++) {
+                // log transform the RGB data
+                unsigned char R = rgbImagePointer[j].GetRed();
+                unsigned char G = rgbImagePointer[j].GetGreen();
+                unsigned char B = rgbImagePointer[j].GetBlue();
+                double Rlog = -((255.0 * log((static_cast<double>(R) + 1) / 255.0)) / log255);
+                double Glog = -((255.0 * log((static_cast<double>(G) + 1) / 255.0)) / log255);
+                double Blog = -((255.0 * log((static_cast<double>(B) + 1) / 255.0)) / log255);
+
+                // rescale to match original paper values
+                double Rscaled = Rlog * q[channelIndex * 3];
+                double Gscaled = Glog * q[channelIndex * 3 + 1];
+                double Bscaled = Blog * q[channelIndex * 3 + 2];
+                double output = exp(-((Rscaled + Gscaled + Bscaled) - 255.0) * log255 / 255.0);
+
+                if (output > 255) {
+                    output = 255;
+                }
+
+                unsigned char idx = static_cast<unsigned char>(0xff & static_cast<int>(floor(output + .5)));
+
+                ////////////////////////////////////////////////////////////////////////////////
+                /// Index to rgb to gray
+                ///
+                /// The original ImageJ plugin output the colorful H
+                /// channel as a indexed image using a LUT. Here I first
+                /// use the LUT to convert the index to rgb and then
+                /// convert to gray. The formula below is what we have
+                /// in matlab rgb2gray
+                //newpixels[j] = static_cast<itkUCharImageType::PixelType>(0.2989*rLUT[idx] + 0.5870*gLUT[idx] + 0.1140*bLUT[idx]);
+                newpixels[j] = idx;
+                /// Index to rgb to gray, end
+                ////////////////////////////////////////////////////////////////////////////////
+            }
+
+
+            return hematoxylinChannel;
         }
-      }
-
-      // SEGMENT: ChanVese
-      if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
-        std::cout << "before CV\n" << std::flush;
-
-        //int numiter = 100;
-        time_t start, end;
-        time(&start);
-        CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType> cv;
-        cv.setImage(hemaFloat);
-        cv.setMask(nucleusBinaryMask);
-        cv.setNumIter(levelsetNumberOfIteration);
-        cv.setCurvatureWeight(curvatureWeight);
-        cv.doSegmentation();
-        time(&end);
-        double dif = difftime(end, start);
-        printf("Elasped time is %.2lf seconds.\n", dif);
-
-        std::cout << "after CV\n" << std::flush;
-
-        CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::Pointer phi = cv.mp_phi;
-
-        itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-        CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::PixelType *phiBufferPointer = phi->GetBufferPointer();
-
-        for (long it = 0; it < numPixels; ++it) {
-          nucleusBinaryMaskBufferPointer[it] = phiBufferPointer[it] <= 1.0 ? 1 : 0;
+        //================================================================================
+
+
+        template<typename TNull>
+        cv::Mat normalizeImageColor(cv::Mat image) {
+            float meanT[3] = {-0.632356, -0.0516004, 0.0376543};
+            float stdT[3] = {0.26235, 0.0514831,
+                             0.0114217}; ///< These are learnt from the template GBM image selected by George
+            cv::Mat newImgCV = nscale::Normalization::normalization(image, meanT, stdT);
+
+            return newImgCV;
         }
-      }
-
-
-      typedef itk::BinaryFillholeImageFilter< itkBinaryMaskImageType > fhFilterType;
-      fhFilterType::Pointer fhfilter = fhFilterType::New();
-      fhfilter->SetInput( nucleusBinaryMask );
-      fhfilter->SetForegroundValue( 1 );
-      fhfilter->Update();
-
-
-      typedef itk::ConnectedComponentImageFilter <itkBinaryMaskImageType, itkLabelImageType > ConnectedComponentImageFilterType;
-      ConnectedComponentImageFilterType::Pointer connected = ConnectedComponentImageFilterType::New ();
-      connected->SetInput(nucleusBinaryMask);
-      connected->Update();
-
-      typedef itk::RelabelComponentImageFilter<itkLabelImageType, itkLabelImageType> FilterType;
-      FilterType::Pointer relabelFilter = FilterType::New();
-      relabelFilter->SetInput(connected->GetOutput());
-      relabelFilter->SetMinimumObjectSize(static_cast<FilterType::ObjectSizeType>(sizeThld/mpp/mpp));
-      relabelFilter->Update();
-
-      itkLabelImageType::Pointer tmpImg = relabelFilter->GetOutput();
-
-      itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-      itkLabelImageType::PixelType *tmpImgBufferPointer = tmpImg->GetBufferPointer();
-
-      for (long it = 0; it < nucleusBinaryMask->GetLargestPossibleRegion().GetNumberOfPixels(); ++it)
-        {
-          nucleusBinaryMaskBufferPointer[it] = tmpImgBufferPointer[it] > 0 ? 1 : 0;
+
+
+        template<typename TNull>
+        itkUCharImageType::Pointer extractTissueMask(cv::Mat image) {
+            float mData[8] = {-0.154, 0.035, 0.549, -45.718, -0.057, -0.817, 1.170, -49.887};
+            cv::Mat M = cv::Mat(2, 4, CV_32FC1, &mData);
+
+            cv::Mat maskCV = nscale::Normalization::segFG(image, M);
+            itkUCharImageType::Pointer foregroundMask = itk::OpenCVImageBridge::CVMatToITKImage<itkUCharImageType>(
+                    maskCV);
+
+            return foregroundMask;
         }

-      // SEGMENT: Declumping
-      if (doDeclump) {
-        if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
-          gth818n::BinaryMaskAnalysisFilter binaryMaskAnalyzer;
-          binaryMaskAnalyzer.setMaskImage(nucleusBinaryMask);
-          binaryMaskAnalyzer.setObjectSizeThreshold(sizeThld);
-          binaryMaskAnalyzer.setObjectSizeUpperThreshold(sizeUpperThld);
-          binaryMaskAnalyzer.setMeanshiftSigma(msKernel);
-          binaryMaskAnalyzer.setMPP(mpp);
-          binaryMaskAnalyzer.update();
-
-          std::cout << "after declumping\n" << std::flush;
-
-          itkUIntImageType::Pointer outputLabelImage = binaryMaskAnalyzer.getConnectedComponentLabelImage();
-          itkUCharImageType::Pointer edgeBetweenLabelsMask = ScalarImage::edgesOfDifferentLabelRegion<char>(
-                                                                                ScalarImage::castItkImage<itkUIntImageType, itkUIntImageType>(
-                                                                                binaryMaskAnalyzer.getConnectedComponentLabelImage()));
-          itkUCharImageType::PixelType *edgeBetweenLabelsMaskBufferPointer = edgeBetweenLabelsMask->GetBufferPointer();
-
-          const itkUIntImageType::PixelType *outputLabelImageBufferPointer = outputLabelImage->GetBufferPointer();
-
-          itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-
-          for (long it = 0; it < numPixels; ++it) {
-            nucleusBinaryMaskBufferPointer[it] = outputLabelImageBufferPointer[it] >= 1 ? 1 : 0;
-            nucleusBinaryMaskBufferPointer[it] *= (1 - edgeBetweenLabelsMaskBufferPointer[it]);
-          }
+        template<typename InputImageType>
+        std::vector<typename InputImageType::PixelType>
+        computeMultipleThresholdsForGrayScaleImage(typename InputImageType::Pointer inputImage) {
+            typedef typename InputImageType::PixelType PixelType;
+            std::vector<PixelType> multipleThresholds;
+
+            {
+                typedef itk::HuangThresholdImageFilter<InputImageType, InputImageType> CalculatorType;
+                typename CalculatorType::Pointer calculator = CalculatorType::New();
+                calculator->SetInput(inputImage);
+                calculator->Update();
+                multipleThresholds.push_back(calculator->GetThreshold());
+            }
+
+            /* { */
+            /*   typedef itk::IntermodesThresholdImageFilter<InputImageType, InputImageType> CalculatorType; */
+            /*   typename CalculatorType::Pointer calculator = CalculatorType::New(); */
+            /*   calculator->SetInput(inputImage); */
+            /*   calculator->Update(); */
+            /*   multipleThresholds.push_back(calculator->GetThreshold()); */
+            /* } */
+
+            {
+                typedef itk::IsoDataThresholdImageFilter<InputImageType, InputImageType> CalculatorType;
+                typename CalculatorType::Pointer calculator = CalculatorType::New();
+                calculator->SetInput(inputImage);
+                calculator->Update();
+                multipleThresholds.push_back(calculator->GetThreshold());
+            }
+
+            /* { */
+            /*   typedef itk::KittlerIllingworthThresholdImageFilter<InputImageType, InputImageType> CalculatorType; */
+            /*   typename CalculatorType::Pointer calculator = CalculatorType::New(); */
+            /*   calculator->SetInput(inputImage); */
+            /*   calculator->Update(); */
+            /*   multipleThresholds.push_back(calculator->GetThreshold()); */
+            /* } */
+
+            {
+                typedef itk::LiThresholdImageFilter<InputImageType, InputImageType> CalculatorType;
+                typename CalculatorType::Pointer calculator = CalculatorType::New();
+                calculator->SetInput(inputImage);
+                calculator->Update();
+                multipleThresholds.push_back(calculator->GetThreshold());
+            }
+
+            {
+                typedef itk::MaximumEntropyThresholdImageFilter<InputImageType, InputImageType> CalculatorType;
+                typename CalculatorType::Pointer calculator = CalculatorType::New();
+                calculator->SetInput(inputImage);
+                calculator->Update();
+                multipleThresholds.push_back(calculator->GetThreshold());
+            }
+
+            {
+                typedef itk::MomentsThresholdImageFilter<InputImageType, InputImageType> CalculatorType;
+                typename CalculatorType::Pointer calculator = CalculatorType::New();
+                calculator->SetInput(inputImage);
+                calculator->Update();
+                multipleThresholds.push_back(calculator->GetThreshold());
+            }
+
+            {
+                typedef itk::OtsuThresholdImageFilter<InputImageType, InputImageType, InputImageType> CalculatorType;
+                typename CalculatorType::Pointer calculator = CalculatorType::New();
+                calculator->SetInput(inputImage);
+                calculator->Update();
+                multipleThresholds.push_back(calculator->GetThreshold());
+            }
+
+            {
+                typedef itk::RenyiEntropyThresholdImageFilter<InputImageType, InputImageType> CalculatorType;
+                typename CalculatorType::Pointer calculator = CalculatorType::New();
+                calculator->SetInput(inputImage);
+                calculator->Update();
+                multipleThresholds.push_back(calculator->GetThreshold());
+            }
+
+            {
+                typedef itk::ShanbhagThresholdImageFilter<InputImageType, InputImageType> CalculatorType;
+                typename CalculatorType::Pointer calculator = CalculatorType::New();
+                calculator->SetInput(inputImage);
+                calculator->Update();
+                multipleThresholds.push_back(calculator->GetThreshold());
+            }
+
+            {
+                typedef itk::TriangleThresholdImageFilter<InputImageType, InputImageType> CalculatorType;
+                typename CalculatorType::Pointer calculator = CalculatorType::New();
+                calculator->SetInput(inputImage);
+                calculator->Update();
+                multipleThresholds.push_back(calculator->GetThreshold());
+            }
+
+            {
+                typedef itk::YenThresholdImageFilter<InputImageType, InputImageType> CalculatorType;
+                typename CalculatorType::Pointer calculator = CalculatorType::New();
+                calculator->SetInput(inputImage);
+                calculator->Update();
+                multipleThresholds.push_back(calculator->GetThreshold());
+            }
+
+            return multipleThresholds;
         }
-      }
-
-      // SEGMENT: ChanVese again, with numiter = 50.
-      if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
-        int numiter = 50;
-        CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType> cv;
-        cv.setImage(hemaFloat);
-        cv.setMask(nucleusBinaryMask);
-        cv.setNumIter(numiter);
-        cv.setCurvatureWeight(curvatureWeight);
-        cv.doSegmentation();
-
-        CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::Pointer phi = cv.mp_phi;
-
-        itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-        CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::PixelType *phiBufferPointer = phi->GetBufferPointer();
-
-        for (long it = 0; it < numPixels; ++it) {
-          nucleusBinaryMaskBufferPointer[it] = phiBufferPointer[it] <= 1.0 ? 1 : 0;
+
+
+        template<typename InputImageType, typename OutputImageType>
+        typename OutputImageType::Pointer
+        optimalThresholdImage(typename InputImageType::Pointer inputImage,
+                              typename OutputImageType::PixelType maskValue, float &theThreshold) {
+            itkFloatImageType::Pointer image = ScalarImage::castItkImage<InputImageType, itkFloatImageType>(inputImage);
+
+            std::vector<itkFloatImageType::PixelType> a = computeMultipleThresholdsForGrayScaleImage<itkFloatImageType>(
+                    image);
+            std::sort(a.begin(), a.end());
+
+            float ratio = 0.75;
+            long n = static_cast<long>(ratio * static_cast<float>(a.size()));
+
+            theThreshold = a[n];
+
+            typename OutputImageType::Pointer mask = OutputImageType::New();
+            mask->SetRegions(image->GetLargestPossibleRegion());
+            mask->Allocate();
+            mask->FillBuffer(0);
+            const itkFloatImageType::PixelType *imageBufferPointer = image->GetBufferPointer();
+            typename OutputImageType::PixelType *maskBufferPointer = mask->GetBufferPointer();
+            std::size_t numPixels = mask->GetLargestPossibleRegion().GetNumberOfPixels();
+            for (std::size_t it = 0; it < numPixels; ++it) {
+                maskBufferPointer[it] = imageBufferPointer[it] <= theThreshold ? maskValue : 0;
+            }
+
+            return mask;
         }
-      }
-
-      // FIX hole in object
-      fhFilterType::Pointer fhfilter1 = fhFilterType::New();
-      fhfilter1->SetInput( nucleusBinaryMask );
-      fhfilter1->SetForegroundValue( 1 );
-      fhfilter1->Update();
-
-        //std::cout << "before ConnectedComponent\n" << std::flush;
-        //typedef itk::ConnectedComponentImageFilter <itkUCharImageType, itkUShortImageType > ConnectedComponentImageFilterType;
-        //ConnectedComponentImageFilterType::Pointer connected = ConnectedComponentImageFilterType::New ();
-        //connected->SetInput(nucleusBinaryMask);
-        //connected->Update();
-        //outputLabelImageUShort = connected->GetOutput();
-        //std::cout << "after ConnectedComponent\n" << std::flush;
-
-	// return nucleusBinaryMask;
-
-      return fhfilter1->GetOutput();
-    }
-
-
-    template<typename TNull>
-      itkUCharImageType::Pointer processTileOptimalThreshold(cv::Mat thisTileCV, \
-							     itkUShortImageType::Pointer &outputLabelImageUShort, \
-							     double curvatureWeight = 0.8, \
-							     float sizeThld = 3, \
-							     float sizeUpperThld = 200, \
-							     double mpp = 0.25, \
-							     float msKernel = 20.0, \
-							     int levelsetNumberOfIteration = 100, \
-							     bool doDeclump = false)
-      {
-	std::cout << "normalizeImageColor.....\n" << std::flush;
-	cv::Mat newImgCV = normalizeImageColor<char>(thisTileCV);
-
-	std::cout << "extractTissueMask.....\n" << std::flush;
-	itkUCharImageType::Pointer foregroundMask = extractTissueMask<char>(newImgCV);
-
-	itkRGBImageType::Pointer thisTile = itk::OpenCVImageBridge::CVMatToITKImage<itkRGBImageType>(thisTileCV);
-
-	//IO::writeImage<itkRGBImageType>(thisTile, "thisTile.png", 0);
-
-	std::cout << "ExtractHematoxylinChannel.....\n" << std::flush;
-	itkUCharImageType::Pointer hematoxylinImage = ExtractHematoxylinChannel<char>(thisTile);
-
-	short maskValue = 1;
-
-	itkFloatImageType::Pointer hemaFloat = ScalarImage::castItkImage<itkUCharImageType, itkFloatImageType>(
-													       hematoxylinImage);
-
-	std::cout << "ThresholdImage.....\n" << std::flush;
-
-	float theThreshold = 0;
-	itkUCharImageType::Pointer nucleusBinaryMask            \
-	  = optimalThresholdImage<itkFloatImageType, itkUCharImageType>(hemaFloat,
-									static_cast<itkUCharImageType::PixelType>(maskValue),
-									theThreshold);
-
-	long numPixels = nucleusBinaryMask->GetLargestPossibleRegion().GetNumberOfPixels();
-
-	if (foregroundMask) {
-	  const itkUCharImageType::PixelType *fgMaskBufferPointer = foregroundMask->GetBufferPointer();
-	  itkBinaryMaskImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-
-	  for (long it = 0; it < numPixels; ++it) {
-	    if (0 == fgMaskBufferPointer[it]) {
-	      // for sure glass region
-	      nucleusBinaryMaskBufferPointer[it] = 0;
-	    }
-	  }
-	}
-
-	if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
-	  std::cout << "before CV\n" << std::flush;
-
-	  //int numiter = 100;
-	  time_t start, end;
-	  time(&start);
-	  CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType> cv;
-	  cv.setImage(hemaFloat);
-	  cv.setMask(nucleusBinaryMask);
-	  cv.setNumIter(levelsetNumberOfIteration);
-	  cv.setCurvatureWeight(curvatureWeight);
-	  cv.doSegmentation();
-	  time(&end);
-	  double dif = difftime(end, start);
-	  printf("Elasped time is %.2lf seconds.\n", dif);
-
-	  std::cout << "after CV\n" << std::flush;
-
-	  CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::Pointer phi = cv.mp_phi;
-
-	  itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-	  CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::PixelType *phiBufferPointer = phi->GetBufferPointer();
-
-	  for (long it = 0; it < numPixels; ++it) {
-	    nucleusBinaryMaskBufferPointer[it] = phiBufferPointer[it] <= 1.0 ? 1 : 0;
-	  }
-	}
-
-	if (doDeclump) {
-	  if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
-	    gth818n::BinaryMaskAnalysisFilter binaryMaskAnalyzer;
-	    binaryMaskAnalyzer.setMaskImage(nucleusBinaryMask);
-	    binaryMaskAnalyzer.setObjectSizeThreshold(sizeThld);
-	    binaryMaskAnalyzer.setObjectSizeUpperThreshold(sizeUpperThld);
-	    binaryMaskAnalyzer.setMeanshiftSigma(msKernel);
-	    binaryMaskAnalyzer.setMPP(mpp);
-	    binaryMaskAnalyzer.update();
-
-	    std::cout << "after declumping\n" << std::flush;
-
-	    itkUIntImageType::Pointer outputLabelImage = binaryMaskAnalyzer.getConnectedComponentLabelImage();
-	    itkUCharImageType::Pointer edgeBetweenLabelsMask = ScalarImage::edgesOfDifferentLabelRegion<char>(
-													      ScalarImage::castItkImage<itkUIntImageType, itkUIntImageType>(
-																					    binaryMaskAnalyzer.getConnectedComponentLabelImage()));
-	    itkUCharImageType::PixelType *edgeBetweenLabelsMaskBufferPointer = edgeBetweenLabelsMask->GetBufferPointer();
-
-	    const itkUIntImageType::PixelType *outputLabelImageBufferPointer = outputLabelImage->GetBufferPointer();
-
-	    itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-
-	    for (long it = 0; it < numPixels; ++it) {
-	      nucleusBinaryMaskBufferPointer[it] = outputLabelImageBufferPointer[it] >= 1 ? 1 : 0;
-	      nucleusBinaryMaskBufferPointer[it] *= (1 - edgeBetweenLabelsMaskBufferPointer[it]);
-	    }
-	  }
-	}
-
-
-	if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
-	  int numiter = 50;
-	  CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType> cv;
-	  cv.setImage(hemaFloat);
-	  cv.setMask(nucleusBinaryMask);
-	  cv.setNumIter(numiter);
-	  cv.setCurvatureWeight(curvatureWeight);
-	  cv.doSegmentation();
-
-	  CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::Pointer phi = cv.mp_phi;
-
-	  itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-	  CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::PixelType *phiBufferPointer = phi->GetBufferPointer();
-
-	  for (long it = 0; it < numPixels; ++it) {
-	    nucleusBinaryMaskBufferPointer[it] = phiBufferPointer[it] <= 1.0 ? 1 : 0;
-	  }
-	}
-
-	std::cout << "before ConnectedComponent\n" << std::flush;
-	typedef itk::ConnectedComponentImageFilter <itkUCharImageType, itkUShortImageType> ConnectedComponentImageFilterType;
-	ConnectedComponentImageFilterType::Pointer connected = ConnectedComponentImageFilterType::New();
-	connected->SetInput(nucleusBinaryMask);
-	connected->Update();
-	outputLabelImageUShort = connected->GetOutput();
-	std::cout << "after ConnectedComponent\n" << std::flush;
-
-	return nucleusBinaryMask;
-      }
-
-
-    template<typename TNull>
-      itkUIntImageType::Pointer processTileOutputLabel(cv::Mat thisTileCV, \
-						       itkUShortImageType::Pointer &outputLabelImageUShort, \
-						       float otsuRatio = 1.0, \
-						       double curvatureWeight = 0.8, \
-						       float sizeThld = 3, \
-						       float sizeUpperThld = 200, \
-						       double mpp = 0.25, \
-						       float msKernel = 20.0, \
-						       int levelsetNumberOfIteration = 100)
-      {
-	std::cout << "normalizeImageColor.....\n" << std::flush;
-	cv::Mat newImgCV = normalizeImageColor<char>(thisTileCV);
-
-	std::cout << "extractTissueMask.....\n" << std::flush;
-	itkUCharImageType::Pointer foregroundMask = extractTissueMask<char>(newImgCV);
-
-	itkRGBImageType::Pointer thisTile = itk::OpenCVImageBridge::CVMatToITKImage<itkRGBImageType>(thisTileCV);
-
-	//IO::writeImage<itkRGBImageType>(thisTile, "thisTile.png", 0);
-
-	std::cout << "ExtractHematoxylinChannel.....\n" << std::flush;
-	itkUCharImageType::Pointer hematoxylinImage = ExtractHematoxylinChannel<char>(thisTile);
-
-	short maskValue = 1;
-
-	itkFloatImageType::Pointer hemaFloat = ScalarImage::castItkImage<itkUCharImageType, itkFloatImageType>(
-													       hematoxylinImage);
-
-	std::cout << "otsuThresholdImage.....\n" << std::flush;
-	itkUCharImageType::Pointer nucleusBinaryMask = ScalarImage::otsuThresholdImage<char>(hemaFloat, maskValue,
-											     otsuRatio);
-	long numPixels = nucleusBinaryMask->GetLargestPossibleRegion().GetNumberOfPixels();
-
-	//std::cout<<"output otsuThresholdImage.....\n"<<std::flush;
-	//ImagenomicAnalytics::IO::writeImage<itkUCharImageType>(nucleusBinaryMask, "nucleusBinaryMask.png", 0);
-
-	if (foregroundMask) {
-	  const itkUCharImageType::PixelType *fgMaskBufferPointer = foregroundMask->GetBufferPointer();
-	  itkBinaryMaskImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-
-	  for (long it = 0; it < numPixels; ++it) {
-	    if (0 == fgMaskBufferPointer[it]) {
-	      // for sure glass region
-	      nucleusBinaryMaskBufferPointer[it] = 0;
-	    }
-	  }
-	}
-
-	if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
-	  std::cout << "before CV\n" << std::flush;
-
-	  //int numiter = 100;
-	  time_t start, end;
-	  time(&start);
-	  CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType> cv;
-	  cv.setImage(hemaFloat);
-	  cv.setMask(nucleusBinaryMask);
-	  cv.setNumIter(levelsetNumberOfIteration);
-	  cv.setCurvatureWeight(curvatureWeight);
-	  cv.doSegmentation();
-	  time(&end);
-	  double dif = difftime(end, start);
-	  printf("Elasped time is %.2lf seconds.\n", dif);
-
-	  std::cout << "after CV\n" << std::flush;
-
-	  CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::Pointer phi = cv.mp_phi;
-
-	  itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-	  CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::PixelType *phiBufferPointer = phi->GetBufferPointer();
-
-	  for (long it = 0; it < numPixels; ++it) {
-	    nucleusBinaryMaskBufferPointer[it] = phiBufferPointer[it] <= 1.0 ? 1 : 0;
-	  }
-	}
-
-	itkUIntImageType::Pointer outputLabelImage;
-	if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
-	  gth818n::BinaryMaskAnalysisFilter binaryMaskAnalyzer;
-	  binaryMaskAnalyzer.setMaskImage(nucleusBinaryMask);
-	  binaryMaskAnalyzer.setObjectSizeThreshold(sizeThld);
-	  binaryMaskAnalyzer.setObjectSizeUpperThreshold(sizeUpperThld);
-	  binaryMaskAnalyzer.setMeanshiftSigma(msKernel);
-	  binaryMaskAnalyzer.setMPP(mpp);
-	  binaryMaskAnalyzer.update();
-
-	  std::cout << "after declumping\n" << std::flush;
-
-	  outputLabelImage = binaryMaskAnalyzer.getConnectedComponentLabelImage();
-	  // itkUCharImageType::Pointer edgeBetweenLabelsMask = ScalarImage::edgesOfDifferentLabelRegion<char>(ScalarImage::castItkImage<itkUIntImageType, itkUIntImageType>(binaryMaskAnalyzer.getConnectedComponentLabelImage()));
-	  // itkUCharImageType::PixelType* edgeBetweenLabelsMaskBufferPointer = edgeBetweenLabelsMask->GetBufferPointer();
-
-	  // const itkUIntImageType::PixelType* outputLabelImageBufferPointer = outputLabelImage->GetBufferPointer();
-
-	  // itkUCharImageType::PixelType* nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-
-	  // for (long it = 0; it < numPixels; ++it)
-	  //   {
-	  //     nucleusBinaryMaskBufferPointer[it] = outputLabelImageBufferPointer[it] >= 1?1:0;
-	  //     nucleusBinaryMaskBufferPointer[it] *= (1 - edgeBetweenLabelsMaskBufferPointer[it]);
-	  //   }
-	}
-
-
-	return outputLabelImage;
-      }
-
-
-    cv::Mat processTileCV(cv::Mat thisTileCV, \
+
+        /**
+         * Process Tile
+         * declumpingType:
+         * 0 = No declumping
+         * 1 = Mean Shift
+         * 2 = Watershed
+         */
+        template<typename TNull>
+        itkUCharImageType::Pointer processTile(cv::Mat thisTileCV, \
+                         itkUShortImageType::Pointer &outputLabelImageUShort, \
+                         float otsuRatio = 1.0, \
+                         double curvatureWeight = 0.8, \
+                         float sizeThld = 3, \
+                         float sizeUpperThld = 200, \
+                         double mpp = 0.25, \
+                         float msKernel = 20.0, \
+                         int levelsetNumberOfIteration = 100, \
+                         int declumpingType = 0) {
+            std::cout << "normalizeImageColor.....\n" << std::flush;
+            cv::Mat newImgCV = normalizeImageColor<char>(thisTileCV);
+
+            std::cout << "extractTissueMask.....\n" << std::flush;
+            itkUCharImageType::Pointer foregroundMask = extractTissueMask<char>(newImgCV);
+
+            itkRGBImageType::Pointer thisTile = itk::OpenCVImageBridge::CVMatToITKImage<itkRGBImageType>(thisTileCV);
+
+            //IO::writeImage<itkRGBImageType>(thisTile, "thisTile.png", 0);
+
+            std::cout << "ExtractHematoxylinChannel.....\n" << std::flush;
+            itkUCharImageType::Pointer hematoxylinImage = ExtractHematoxylinChannel<char>(thisTile);
+
+            short maskValue = 1;
+
+            itkFloatImageType::Pointer hemaFloat = ScalarImage::castItkImage<itkUCharImageType, itkFloatImageType>(
+                    hematoxylinImage);
+
+            std::cout << "ThresholdImage.....\n" << std::flush;
+
+            itkUCharImageType::Pointer nucleusBinaryMask = ScalarImage::otsuThresholdImage<char>(hemaFloat, maskValue,
+                                                                                otsuRatio);
+
+            const unsigned long numPixels = nucleusBinaryMask->GetLargestPossibleRegion().GetNumberOfPixels();
+
+            //std::cout<<"output otsuThresholdImage.....\n"<<std::flush;
+            //ImagenomicAnalytics::IO::writeImage<itkUCharImageType>(nucleusBinaryMask, "nucleusBinaryMask.png", 0);
+
+            if (foregroundMask) {
+                const itkUCharImageType::PixelType *fgMaskBufferPointer = foregroundMask->GetBufferPointer();
+                itkBinaryMaskImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+
+                for (unsigned long it = 0; it < numPixels; ++it) {
+                    if (0 == fgMaskBufferPointer[it]) {
+                        // for sure glass region
+                        nucleusBinaryMaskBufferPointer[it] = 0;
+                    }
+                }
+            }
+
+            // SEGMENT: ChanVese
+            if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
+                std::cout << "before CV\n" << std::flush;
+
+                //int numiter = 100;
+                time_t start, end;
+                time(&start);
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType> cv;
+                cv.setImage(hemaFloat);
+                cv.setMask(nucleusBinaryMask);
+                cv.setNumIter(levelsetNumberOfIteration);
+                cv.setCurvatureWeight(curvatureWeight);
+                cv.doSegmentation();
+                time(&end);
+                double dif = difftime(end, start);
+                std::cout << "Elasped time is " << dif << " seconds.\n" << std::flush;
+
+                std::cout << "after CV\n" << std::flush;
+
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::Pointer phi = cv.mp_phi;
+
+                itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::PixelType *phiBufferPointer = phi->GetBufferPointer();
+
+                for (unsigned long it = 0; it < numPixels; ++it) {
+                    nucleusBinaryMaskBufferPointer[it] = phiBufferPointer[it] <= 1.0 ? 1 : 0;
+                }
+            }
+
+
+            typedef itk::BinaryFillholeImageFilter<itkBinaryMaskImageType> fhFilterType;
+            fhFilterType::Pointer fhfilter = fhFilterType::New();
+            fhfilter->SetInput(nucleusBinaryMask);
+            fhfilter->SetForegroundValue(1);
+            fhfilter->Update();
+
+
+            typedef itk::ConnectedComponentImageFilter<itkBinaryMaskImageType, itkLabelImageType> ConnectedComponentImageFilterType;
+            ConnectedComponentImageFilterType::Pointer connected = ConnectedComponentImageFilterType::New();
+            connected->SetInput(nucleusBinaryMask);
+            connected->Update();
+
+            typedef itk::RelabelComponentImageFilter<itkLabelImageType, itkLabelImageType> FilterType;
+            FilterType::Pointer relabelFilter = FilterType::New();
+            relabelFilter->SetInput(connected->GetOutput());
+            relabelFilter->SetMinimumObjectSize(static_cast<FilterType::ObjectSizeType>(sizeThld / mpp / mpp));
+            relabelFilter->Update();
+
+            itkLabelImageType::Pointer tmpImg = relabelFilter->GetOutput();
+
+            itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+            itkLabelImageType::PixelType *tmpImgBufferPointer = tmpImg->GetBufferPointer();
+
+            for (unsigned long it = 0; it < numPixels; ++it) {
+                nucleusBinaryMaskBufferPointer[it] = tmpImgBufferPointer[it] > 0 ? 1 : 0;
+            }
+
+
+            // SEGMENT: Declumping
+            if (declumpingType > 0) {
+                if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
+
+                    // WATERSHED
+                    if (declumpingType == 2) {
+
+                        cv::Mat watershedMask;
+                        cv::Mat seg = itk::OpenCVImageBridge::ITKImageToCVMat<itkUCharImageType>(nucleusBinaryMask);
+
+                        // (img, seg, mask, int minSizePl=30, int watershedConnectivity=8,
+                        // ::cciutils::SimpleCSVLogger *logger = NULL, ::cciutils::cv::IntermediateResultHandler *iresHandler = NULL);
+                        nscale::HistologicalEntities::plSeparateNuclei(newImgCV, seg, watershedMask, 30, 8, NULL, NULL);
+
+                        nucleusBinaryMask = itk::OpenCVImageBridge::CVMatToITKImage<itkUCharImageType>(watershedMask);
+
+                    }
+
+                    // MEAN SHIFT
+                    if (declumpingType == 1) {
+                        gth818n::BinaryMaskAnalysisFilter binaryMaskAnalyzer;
+                        binaryMaskAnalyzer.setMaskImage(nucleusBinaryMask);
+                        binaryMaskAnalyzer.setObjectSizeThreshold(sizeThld);
+                        binaryMaskAnalyzer.setObjectSizeUpperThreshold(sizeUpperThld);
+                        binaryMaskAnalyzer.setMeanshiftSigma(msKernel);
+                        binaryMaskAnalyzer.setMPP(mpp);
+                        // Assumes declumpingType==0
+                        binaryMaskAnalyzer.update();
+
+                        std::cout << "after declumping\n" << std::flush;
+
+                        itkUIntImageType::Pointer outputLabelImage = binaryMaskAnalyzer.getConnectedComponentLabelImage();
+                        itkUCharImageType::Pointer edgeBetweenLabelsMask = ScalarImage::edgesOfDifferentLabelRegion<char>(
+                                ScalarImage::castItkImage<itkUIntImageType, itkUIntImageType>(
+                                        binaryMaskAnalyzer.getConnectedComponentLabelImage()));
+                        itkUCharImageType::PixelType *edgeBetweenLabelsMaskBufferPointer = edgeBetweenLabelsMask->GetBufferPointer();
+
+                        const itkUIntImageType::PixelType *outputLabelImageBufferPointer = outputLabelImage->GetBufferPointer();
+
+                        itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+
+                        for (unsigned long it = 0; it < numPixels; ++it) {
+                            nucleusBinaryMaskBufferPointer[it] = outputLabelImageBufferPointer[it] >= 1 ? 1 : 0;
+                            nucleusBinaryMaskBufferPointer[it] *= (1 - edgeBetweenLabelsMaskBufferPointer[it]);
+                        }
+                    }
+
+                }
+            }
+
+            // SEGMENT: ChanVese again, with numiter = 50.
+            if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
+                int numiter = 50;
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType> cv;
+                cv.setImage(hemaFloat);
+                cv.setMask(nucleusBinaryMask);
+                cv.setNumIter(numiter);
+                cv.setCurvatureWeight(curvatureWeight);
+                cv.doSegmentation();
+
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::Pointer phi = cv.mp_phi;
+
+                itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::PixelType *phiBufferPointer = phi->GetBufferPointer();
+
+                for (unsigned long it = 0; it < numPixels; ++it) {
+                    nucleusBinaryMaskBufferPointer[it] = phiBufferPointer[it] <= 1.0 ? 1 : 0;
+                }
+            }
+
+            // FIX hole in object
+            fhFilterType::Pointer fhfilter1 = fhFilterType::New();
+            fhfilter1->SetInput(nucleusBinaryMask);
+            fhfilter1->SetForegroundValue(1);
+            fhfilter1->Update();
+
+            //std::cout << "before ConnectedComponent\n" << std::flush;
+            //typedef itk::ConnectedComponentImageFilter <itkUCharImageType, itkUShortImageType > ConnectedComponentImageFilterType;
+            //ConnectedComponentImageFilterType::Pointer connected = ConnectedComponentImageFilterType::New ();
+            //connected->SetInput(nucleusBinaryMask);
+            //connected->Update();
+            //outputLabelImageUShort = connected->GetOutput();
+            //std::cout << "after ConnectedComponent\n" << std::flush;
+
+            // return nucleusBinaryMask;
+
+            return fhfilter1->GetOutput();
+        }
+
+
+        /**
+         * NOT USED.
+         */
+        template<typename TNull>
+        itkUCharImageType::Pointer processTileOptimalThreshold(cv::Mat thisTileCV, \
+                                 itkUShortImageType::Pointer &outputLabelImageUShort, \
+                                 double curvatureWeight = 0.8, \
+                                 float sizeThld = 3, \
+                                 float sizeUpperThld = 200, \
+                                 double mpp = 0.25, \
+                                 float msKernel = 20.0, \
+                                 int levelsetNumberOfIteration = 100, \
+                                 int declumpingType = 0) {
+            std::cout << "normalizeImageColor.....\n" << std::flush;
+            cv::Mat newImgCV = normalizeImageColor<char>(thisTileCV);
+
+            std::cout << "extractTissueMask.....\n" << std::flush;
+            itkUCharImageType::Pointer foregroundMask = extractTissueMask<char>(newImgCV);
+
+            itkRGBImageType::Pointer thisTile = itk::OpenCVImageBridge::CVMatToITKImage<itkRGBImageType>(thisTileCV);
+
+            //IO::writeImage<itkRGBImageType>(thisTile, "thisTile.png", 0);
+
+            std::cout << "ExtractHematoxylinChannel.....\n" << std::flush;
+            itkUCharImageType::Pointer hematoxylinImage = ExtractHematoxylinChannel<char>(thisTile);
+
+            short maskValue = 1;
+
+            itkFloatImageType::Pointer hemaFloat = ScalarImage::castItkImage<itkUCharImageType, itkFloatImageType>(
+                    hematoxylinImage);
+
+            std::cout << "ThresholdImage.....\n" << std::flush;
+
+            float theThreshold = 0;
+            itkUCharImageType::Pointer nucleusBinaryMask            \
+ = optimalThresholdImage<itkFloatImageType, itkUCharImageType>(hemaFloat,
+                                                               static_cast<itkUCharImageType::PixelType>(maskValue),
+                                                               theThreshold);
+
+            const unsigned long numPixels = nucleusBinaryMask->GetLargestPossibleRegion().GetNumberOfPixels();
+
+            if (foregroundMask) {
+                const itkUCharImageType::PixelType *fgMaskBufferPointer = foregroundMask->GetBufferPointer();
+                itkBinaryMaskImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+
+                for (unsigned long it = 0; it < numPixels; ++it) {
+                    if (0 == fgMaskBufferPointer[it]) {
+                        // for sure glass region
+                        nucleusBinaryMaskBufferPointer[it] = 0;
+                    }
+                }
+            }
+
+            if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
+                std::cout << "before CV\n" << std::flush;
+
+                //int numiter = 100;
+                time_t start, end;
+                time(&start);
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType> cv;
+                cv.setImage(hemaFloat);
+                cv.setMask(nucleusBinaryMask);
+                cv.setNumIter(levelsetNumberOfIteration);
+                cv.setCurvatureWeight(curvatureWeight);
+                cv.doSegmentation();
+                time(&end);
+                double dif = difftime(end, start);
+                std::cout << "Elasped time is " << dif << " seconds.\n" << std::flush;
+
+                std::cout << "after CV\n" << std::flush;
+
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::Pointer phi = cv.mp_phi;
+
+                itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::PixelType *phiBufferPointer = phi->GetBufferPointer();
+
+                for (unsigned long it = 0; it < numPixels; ++it) {
+                    nucleusBinaryMaskBufferPointer[it] = phiBufferPointer[it] <= 1.0 ? 1 : 0;
+                }
+            }
+
+            if (declumpingType == 1) {
+                if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
+                    gth818n::BinaryMaskAnalysisFilter binaryMaskAnalyzer;
+                    binaryMaskAnalyzer.setMaskImage(nucleusBinaryMask);
+                    binaryMaskAnalyzer.setObjectSizeThreshold(sizeThld);
+                    binaryMaskAnalyzer.setObjectSizeUpperThreshold(sizeUpperThld);
+                    binaryMaskAnalyzer.setMeanshiftSigma(msKernel);
+                    binaryMaskAnalyzer.setMPP(mpp);
+                    binaryMaskAnalyzer.update();
+
+                    std::cout << "after declumping\n" << std::flush;
+
+                    itkUIntImageType::Pointer outputLabelImage = binaryMaskAnalyzer.getConnectedComponentLabelImage();
+                    itkUCharImageType::Pointer edgeBetweenLabelsMask = ScalarImage::edgesOfDifferentLabelRegion<char>(
+                            ScalarImage::castItkImage<itkUIntImageType, itkUIntImageType>(
+                                    binaryMaskAnalyzer.getConnectedComponentLabelImage()));
+                    itkUCharImageType::PixelType *edgeBetweenLabelsMaskBufferPointer = edgeBetweenLabelsMask->GetBufferPointer();
+
+                    const itkUIntImageType::PixelType *outputLabelImageBufferPointer = outputLabelImage->GetBufferPointer();
+
+                    itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+
+                    for (unsigned long it = 0; it < numPixels; ++it) {
+                        nucleusBinaryMaskBufferPointer[it] = outputLabelImageBufferPointer[it] >= 1 ? 1 : 0;
+                        nucleusBinaryMaskBufferPointer[it] *= (1 - edgeBetweenLabelsMaskBufferPointer[it]);
+                    }
+                }
+            }
+
+
+            if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
+                int numiter = 50;
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType> cv;
+                cv.setImage(hemaFloat);
+                cv.setMask(nucleusBinaryMask);
+                cv.setNumIter(numiter);
+                cv.setCurvatureWeight(curvatureWeight);
+                cv.doSegmentation();
+
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::Pointer phi = cv.mp_phi;
+
+                itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::PixelType *phiBufferPointer = phi->GetBufferPointer();
+
+                for (unsigned long it = 0; it < numPixels; ++it) {
+                    nucleusBinaryMaskBufferPointer[it] = phiBufferPointer[it] <= 1.0 ? 1 : 0;
+                }
+            }
+
+            std::cout << "before ConnectedComponent\n" << std::flush;
+            typedef itk::ConnectedComponentImageFilter<itkUCharImageType, itkUShortImageType> ConnectedComponentImageFilterType;
+            ConnectedComponentImageFilterType::Pointer connected = ConnectedComponentImageFilterType::New();
+            connected->SetInput(nucleusBinaryMask);
+            connected->Update();
+            outputLabelImageUShort = connected->GetOutput();
+            std::cout << "after ConnectedComponent\n" << std::flush;
+
+            return nucleusBinaryMask;
+        }
+
+
+        template<typename TNull>
+        itkUIntImageType::Pointer processTileOutputLabel(cv::Mat thisTileCV, \
+                               itkUShortImageType::Pointer &outputLabelImageUShort, \
+                               float otsuRatio = 1.0, \
+                               double curvatureWeight = 0.8, \
+                               float sizeThld = 3, \
+                               float sizeUpperThld = 200, \
+                               double mpp = 0.25, \
+                               float msKernel = 20.0, \
+                               int levelsetNumberOfIteration = 100) {
+            std::cout << "normalizeImageColor.....\n" << std::flush;
+            cv::Mat newImgCV = normalizeImageColor<char>(thisTileCV);
+
+            std::cout << "extractTissueMask.....\n" << std::flush;
+            itkUCharImageType::Pointer foregroundMask = extractTissueMask<char>(newImgCV);
+
+            itkRGBImageType::Pointer thisTile = itk::OpenCVImageBridge::CVMatToITKImage<itkRGBImageType>(thisTileCV);
+
+            //IO::writeImage<itkRGBImageType>(thisTile, "thisTile.png", 0);
+
+            std::cout << "ExtractHematoxylinChannel.....\n" << std::flush;
+            itkUCharImageType::Pointer hematoxylinImage = ExtractHematoxylinChannel<char>(thisTile);
+
+            short maskValue = 1;
+
+            itkFloatImageType::Pointer hemaFloat = ScalarImage::castItkImage<itkUCharImageType, itkFloatImageType>(
+                    hematoxylinImage);
+
+            std::cout << "otsuThresholdImage.....\n" << std::flush;
+            itkUCharImageType::Pointer nucleusBinaryMask = ScalarImage::otsuThresholdImage<char>(hemaFloat, maskValue,
+                                                                                otsuRatio);
+            const unsigned long numPixels = nucleusBinaryMask->GetLargestPossibleRegion().GetNumberOfPixels();
+
+            //std::cout<<"output otsuThresholdImage.....\n"<<std::flush;
+            //ImagenomicAnalytics::IO::writeImage<itkUCharImageType>(nucleusBinaryMask, "nucleusBinaryMask.png", 0);
+
+            if (foregroundMask) {
+                const itkUCharImageType::PixelType *fgMaskBufferPointer = foregroundMask->GetBufferPointer();
+                itkBinaryMaskImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+
+                for (unsigned long it = 0; it < numPixels; ++it) {
+                    if (0 == fgMaskBufferPointer[it]) {
+                        // for sure glass region
+                        nucleusBinaryMaskBufferPointer[it] = 0;
+                    }
+                }
+            }
+
+            if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
+                std::cout << "before CV\n" << std::flush;
+
+                //int numiter = 100;
+                time_t start, end;
+                time(&start);
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType> cv;
+                cv.setImage(hemaFloat);
+                cv.setMask(nucleusBinaryMask);
+                cv.setNumIter(levelsetNumberOfIteration);
+                cv.setCurvatureWeight(curvatureWeight);
+                cv.doSegmentation();
+                time(&end);
+                double dif = difftime(end, start);
+                std::cout << "Elasped time is " << dif << " seconds.\n" << std::flush;
+
+                std::cout << "after CV\n" << std::flush;
+
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::Pointer phi = cv.mp_phi;
+
+                itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+                CSFLSLocalChanVeseSegmentor2D<itkFloatImageType::PixelType>::LSImageType::PixelType *phiBufferPointer = phi->GetBufferPointer();
+
+                for (unsigned long it = 0; it < numPixels; ++it) {
+                    nucleusBinaryMaskBufferPointer[it] = phiBufferPointer[it] <= 1.0 ? 1 : 0;
+                }
+            }
+
+            itkUIntImageType::Pointer outputLabelImage;
+            if (!ScalarImage::isImageAllZero<itkBinaryMaskImageType>(nucleusBinaryMask)) {
+                gth818n::BinaryMaskAnalysisFilter binaryMaskAnalyzer;
+                binaryMaskAnalyzer.setMaskImage(nucleusBinaryMask);
+                binaryMaskAnalyzer.setObjectSizeThreshold(sizeThld);
+                binaryMaskAnalyzer.setObjectSizeUpperThreshold(sizeUpperThld);
+                binaryMaskAnalyzer.setMeanshiftSigma(msKernel);
+                binaryMaskAnalyzer.setMPP(mpp);
+                binaryMaskAnalyzer.update();
+
+                std::cout << "after declumping\n" << std::flush;
+
+                outputLabelImage = binaryMaskAnalyzer.getConnectedComponentLabelImage();
+                // itkUCharImageType::Pointer edgeBetweenLabelsMask = ScalarImage::edgesOfDifferentLabelRegion<char>(ScalarImage::castItkImage<itkUIntImageType, itkUIntImageType>(binaryMaskAnalyzer.getConnectedComponentLabelImage()));
+                // itkUCharImageType::PixelType* edgeBetweenLabelsMaskBufferPointer = edgeBetweenLabelsMask->GetBufferPointer();
+
+                // const itkUIntImageType::PixelType* outputLabelImageBufferPointer = outputLabelImage->GetBufferPointer();
+
+                // itkUCharImageType::PixelType* nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+
+                // for (long it = 0; it < numPixels; ++it)
+                //   {
+                //     nucleusBinaryMaskBufferPointer[it] = outputLabelImageBufferPointer[it] >= 1?1:0;
+                //     nucleusBinaryMaskBufferPointer[it] *= (1 - edgeBetweenLabelsMaskBufferPointer[it]);
+                //   }
+            }
+
+
+            return outputLabelImage;
+        }
+
+        /**
+         * Process Tile CV
+         * declumpingType:
+         * 0 = None
+         * 1 = Mean Shift
+         * 2 = Watershed
+         */
+        cv::Mat processTileCV(cv::Mat thisTileCV, \
                           float otsuRatio = 1.0, \
                           double curvatureWeight = 0.8, \
                           float sizeThld = 3, \
                           float sizeUpperThld = 200, \
                           double mpp = 0.25, \
                           float msKernel = 20.0, \
-                          int levelsetNumberOfIteration = 100)
-      {
-	itkUShortImageType::Pointer outputLabelImage;
-
-	// call regular segmentation function
-	itkUCharImageType::Pointer nucleusBinaryMask = processTile<char>(thisTileCV, \
-									 outputLabelImage, \
-									 otsuRatio, \
-									 curvatureWeight, \
-									 sizeThld, \
-									 sizeUpperThld, \
-									 mpp, \
-									 msKernel, \
-									 levelsetNumberOfIteration);
-
-	// change pixel values for visualization reasons
-	itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
-	long numPixels = nucleusBinaryMask->GetLargestPossibleRegion().GetNumberOfPixels();
-	for (long it = 0; it < numPixels; ++it) {
-	  if (nucleusBinaryMaskBufferPointer[it] == 1) {
-	    nucleusBinaryMaskBufferPointer[it] = 255;
-	  }
-	}
-
-
-	cv::Mat binary = itk::OpenCVImageBridge::ITKImageToCVMat<itkUCharImageType>(nucleusBinaryMask);
-	return binary;
-
-      }
-
-
-  }
+                          int levelsetNumberOfIteration = 100,
+                          int declumpingType = 0) {
+
+            itkUShortImageType::Pointer outputLabelImage;
+
+            // call regular segmentation function
+            itkUCharImageType::Pointer nucleusBinaryMask = processTile<char>(thisTileCV, \
+                                                                       outputLabelImage, \
+                                                                       otsuRatio, \
+                                                                       curvatureWeight, \
+                                                                       sizeThld, \
+                                                                       sizeUpperThld, \
+                                                                       mpp, \
+                                                                       msKernel, \
+                                                                       levelsetNumberOfIteration,
+                                                                             declumpingType);
+
+            // change pixel values for visualization reasons
+            itkUCharImageType::PixelType *nucleusBinaryMaskBufferPointer = nucleusBinaryMask->GetBufferPointer();
+            long numPixels = nucleusBinaryMask->GetLargestPossibleRegion().GetNumberOfPixels();
+            for (long it = 0; it < numPixels; ++it) {
+                if (nucleusBinaryMaskBufferPointer[it] == 1) {
+                    nucleusBinaryMaskBufferPointer[it] = 255;
+                }
+            }
+
+            cv::Mat binary = itk::OpenCVImageBridge::ITKImageToCVMat<itkUCharImageType>(nucleusBinaryMask);
+            return binary;
+
+        }
+
+    }
 }// namespace

-
 #endif


Remove GPIO as the default on the RaspberryPi because of initialization problems.

--- osint_linux.c
+++ osint_linux.c
@@ -59,11 +59,7 @@
 #endif

 /* Normally we use DTR for reset */
-#ifdef RASPBERRY_PI
-static reset_method_t reset_method = RESET_WITH_GPIO;
-#else
 static reset_method_t reset_method = RESET_WITH_DTR;
-#endif

 int use_reset_method(char* method)
 {


storage: Clean up stateFile if refreshPool fails

If the virStoragePoolRefresh fails and we call stopPool, the
code neglected to clean up the state file leading to the next
libvirtd restart attempting to start the pool. For a transient
pool this could make it unexpectedly reappear.

Signed-off-by: John Ferlan <87558058f6f829e5ec976c8ef960720af4ff9c7d@redhat.com>
ACKed-by: Michal Privoznik <83d82aaba2eed257f4814b0c239c260c4caaadf0@redhat.com>

--- src/storage/storage_driver.c
+++ src/storage/storage_driver.c
@@ -1171,8 +1171,13 @@

     virStoragePoolObjClearVols(obj);
     if (backend->refreshPool(obj) < 0) {
+        char *stateFile = virFileBuildPath(driver->stateDir, def->name, ".xml");
+
+        if (stateFile)
+            unlink(stateFile);
         if (backend->stopPool)
             backend->stopPool(obj);
+        VIR_FREE(stateFile);

         event = virStoragePoolEventLifecycleNew(def->name,
                                                 def->uuid,


storage: Replace VIR_ERROR with standard vir*Error in state driver init

Replace VIR_ERROR with virReportError and virReportSystemError

--- src/storage/storage_driver.c
+++ src/storage/storage_driver.c
@@ -88,7 +88,8 @@
         goto error;

     if ((backend = virStorageBackendForType(pool->def->type)) == NULL) {
-        VIR_ERROR(_("Missing backend %d"), pool->def->type);
+        virReportError(VIR_ERR_INTERNAL_ERROR,
+                       _("Missing backend %d"), pool->def->type);
         goto error;
     }

@@ -98,8 +99,9 @@
     active = false;
     if (backend->checkPool &&
         backend->checkPool(pool, &active) < 0) {
-        VIR_ERROR(_("Failed to initialize storage pool '%s': %s"),
-                  pool->def->name, virGetLastErrorMessage());
+        virReportError(VIR_ERR_INTERNAL_ERROR,
+                       _("Failed to initialize storage pool '%s': %s"),
+                       pool->def->name, virGetLastErrorMessage());
         goto error;
     }

@@ -112,8 +114,9 @@
         if (backend->refreshPool(NULL, pool) < 0) {
             if (backend->stopPool)
                 backend->stopPool(NULL, pool);
-            VIR_ERROR(_("Failed to restart storage pool '%s': %s"),
-                      pool->def->name, virGetLastErrorMessage());
+            virReportError(VIR_ERR_INTERNAL_ERROR,
+                           _("Failed to restart storage pool '%s': %s"),
+                           pool->def->name, virGetLastErrorMessage());
             goto error;
         }
     }
@@ -172,8 +175,9 @@
             !virStoragePoolObjIsActive(pool)) {
             if (backend->startPool &&
                 backend->startPool(conn, pool) < 0) {
-                VIR_ERROR(_("Failed to autostart storage pool '%s': %s"),
-                          pool->def->name, virGetLastErrorMessage());
+                virReportError(VIR_ERR_INTERNAL_ERROR,
+                               _("Failed to autostart storage pool '%s': %s"),
+                               pool->def->name, virGetLastErrorMessage());
                 virStoragePoolObjUnlock(pool);
                 continue;
             }
@@ -193,8 +197,9 @@
                     unlink(stateFile);
                 if (backend->stopPool)
                     backend->stopPool(conn, pool);
-                VIR_ERROR(_("Failed to autostart storage pool '%s': %s"),
-                          pool->def->name, virGetLastErrorMessage());
+                virReportError(VIR_ERR_INTERNAL_ERROR,
+                               _("Failed to autostart storage pool '%s': %s"),
+                               pool->def->name, virGetLastErrorMessage());
             } else {
                 pool->active = true;
             }


change MAX_CH_AMP on WiiU

change MAX_CH_AMP on WiiU

--- Core/apu.h
+++ Core/apu.h
@@ -7,7 +7,11 @@

 #ifdef GB_INTERNAL
 /* Divides nicely and never overflows with 4 channels and 8 (1-8) volume levels */
+#ifdef WIIU
+#define MAX_CH_AMP 0x1FE0 / 4
+#else
 #define MAX_CH_AMP 0x1FE0
+#endif
 #define CH_STEP (MAX_CH_AMP/0xF/8)
 #endif


flash_test: test 32bit address region if chip size meet


remove bogus check

remove bogus check

git-svn-id: a2d12f8ba5efd9a6cf770ee2a6d40c767093e4df@15410 3eda493b-6a19-0410-b2e0-ec8ea4dd8fda

--- src/zfs-fuse/zfs_vnops.c
+++ src/zfs-fuse/zfs_vnops.c
@@ -2683,9 +2683,6 @@
 		return (EINVAL);
 	}

-	if (mask & AT_SIZE && mask & AT_SLASH2SIZE)
-		abort();
-
 	/*
 	 * If this is an xvattr_t, then get a pointer to the structure of
 	 * optional attributes.  If this is NULL, then we have a vattr_t.


add .sty file extension in latex

add .sty file extension in latex

git-svn-id: 756506b3b0ea8c31733a8f0a5bb416c7e269da3d@261 28bd50df-7adb-d945-0439-6e466c6a13cc

--- src/Styles.c
+++ src/Styles.c
@@ -1351,7 +1351,7 @@
                      { -1, 00000, L"", L"", L"" } } };

-EDITLEXER lexLATEX = { SCLEX_LATEX, 63281, L"LaTeX Files", L"tex; latex", L"", &KeyWords_NULL, {
+EDITLEXER lexLATEX = { SCLEX_LATEX, 63281, L"LaTeX Files", L"tex; latex; sty", L"", &KeyWords_NULL, {
                        { STYLE_DEFAULT, 63126, L"Default", L"", L"" },
                        { SCE_L_COMMAND, 63236, L"Command", L"fore:#0000FF", L"" },
                        { SCE_L_TAG, 63282, L"Tag", L"fore:#0000FF", L"" },


fixed turn_into_tuple()

fixed turn_into_tuple()

[r14132]

--- ir/ana/cgana.c
+++ ir/ana/cgana.c
@@ -763,10 +763,12 @@
        * eine Bad-Operation. Die Verlinkung muss wiederhergestellt
        * werden! */
       ir_node *mem = get_Call_mem(call);
-      turn_into_tuple (call, 5 /* pn_Call_max */);
+      ir_node *blk = get_nodes_block(call);
+      turn_into_tuple (call, pn_Call_max);
       set_Tuple_pred(call, pn_Call_M_regular       , mem);
       set_Tuple_pred(call, pn_Call_T_result        , new_Bad());
       set_Tuple_pred(call, pn_Call_P_value_res_base, new_Bad());
+      set_Tuple_pred(call, pn_Call_X_regular       , new_r_Jmp(current_ir_graph, blk));
       set_Tuple_pred(call, pn_Call_X_except        , new_Bad());  /* new_Jmp() ?? new_Raise() ?? */
       set_Tuple_pred(call, pn_Call_M_except        , new_Bad());


*** empty log message ***

*** empty log message ***

--- ir/be/benode.c
+++ ir/be/benode.c
@@ -461,7 +461,7 @@
 			fprintf(f, get_mode_name(get_irn_mode(irn)));
 			break;
 		case dump_node_nodeattr_txt:
-			fprintf(f, bo->cls->name);
+			fprintf(f, "%s ", bo->cls->name);
 			break;
 		case dump_node_info_txt:
 			for(i = 0; i < attr->n_regs; ++i) {


Fixed some problems due to refactoring in previous revisions.

[r26548]

--- ir/be/benode.c
+++ ir/be/benode.c
@@ -1279,8 +1279,13 @@
 	case dump_node_nodeattr_txt:
 		break;
 	case dump_node_info_txt:
-		arch_dump_reqs_and_registers(F, node);
+	{
+		backend_info_t *info = be_get_info(node);
+		if (info != NULL && info->out_infos[0].req != NULL) {
+			arch_dump_reqs_and_registers(F, node);
+		}
 		break;
+	}

 	default:
 		break;
@@ -1311,42 +1316,6 @@
  |_| \_|\___/ \__,_|\___| |____/ \__,_|_| |_| |_| .__/|_|_| |_|\__, |
                                                 |_|            |___/
 */
-
-/**
- * Dumps node register requirements to a file.
- */
-static void dump_node_reqs(FILE *F, ir_node *node)
-{
-	int i;
-	be_node_attr_t *a = get_irn_attr(node);
-	int len = ARR_LEN(a->reg_data);
-	const backend_info_t *info = be_get_info(node);
-
-	for (i = 0; i < len; ++i) {
-		const arch_register_req_t *req = a->reg_data[i].in_req;
-		if (req->cls == NULL)
-			continue;
-		fprintf(F, "inreq #%d = ", i);
-		arch_dump_register_req(F, req, node);
-		fputs("\n", F);
-	}
-
-	for (i = 0; i < len; ++i) {
-		const arch_register_req_t *req = info->out_infos[i].req;
-		if (req->cls == NULL)
-			continue;
-		fprintf(F, "outreq #%d = ", i);
-		arch_dump_register_req(F, req, node);
-		fputs("\n", F);
-	}
-
-	fputs("\n", F);
-
-	for (i = 0; i < len; ++i) {
-		const arch_register_t *reg = arch_irn_get_register(node, i);
-		fprintf(F, "reg #%d = %s\n", i, reg != NULL ? reg->name : "n/a");
-	}
-}

 /**
  * ir_op-Operation: dump a be node to file
@@ -1384,7 +1353,7 @@
 			}
 			break;
 		case dump_node_info_txt:
-			dump_node_reqs(f, irn);
+			arch_dump_reqs_and_registers(f, irn);

 			if (be_has_frame_entity(irn)) {
 				be_frame_attr_t *a = (be_frame_attr_t *) at;


Fixed extblock dumper (did not work outside debugger Bug)

[r7484]

--- ir/ir/irdump.c
+++ ir/ir/irdump.c
@@ -561,8 +561,10 @@
   ir_extblk **extbb_list;
 } list_tuple;

-/** Construct lists to walk ir extended block-wise.
+/** Construct lists to walk IR extended block-wise.
  * Free the lists in the tuple with DEL_ARR_F().
+ * Sets the irg link field to NULL in all
+ * graphs not visited.
  */
 static list_tuple *construct_extblock_lists(ir_graph *irg) {
   ir_node **blk_list = construct_block_lists(irg);
@@ -1550,7 +1552,6 @@
   ir_extblk **arr = ird_get_irg_link(irg);
   current_ir_graph = irg;

-  compute_extbb(irg);
   for (i = ARR_LEN(arr) - 1; i >= 0; --i) {
     ir_extblk *extbb = arr[i];
     ir_node *leader = get_extbb_leader(extbb);
@@ -2323,7 +2324,8 @@
   if (!is_filtered_dump_name(get_entity_ident(get_irg_entity(irg))))
     return;

-  compute_extbb(irg);
+  if (get_irg_extblk_state(irg) != extblk_valid)
+    compute_extbb(irg);

   if (get_interprocedural_view()) suffix1 = "-ip";
   else                            suffix1 = "";


Added ASSERT_AND_RET_DBG() macro

Added ASSERT_AND_RET_DBG() macro

[r1597]

--- ir/ir/irvrfy.c
+++ ir/ir/irvrfy.c
@@ -17,9 +17,20 @@
 # include "irgwalk.h"

 #ifdef NDEBUG
-#define ASSERT_AND_RET(expr, string, ret)  if (!(expr)) return (ret)
+/*
+ * in RELEASE mode, returns ret if the expression expr evaluates to zero
+ * in ASSERT mode, asserts the expression expr (and the string string).
+ */
+#define ASSERT_AND_RET(expr, string, ret)  		if (!(expr)) return (ret)
+
+/*
+ * in RELEASE mode, returns ret if the expression expr evaluates to zero
+ * in ASSERT mode, executes blk if the expression expr evaluates to zero and asserts
+ */
+#define ASSERT_AND_RET_DBG(expr, string, ret, blk)  	if (!(expr)) return (ret)
 #else
-#define ASSERT_AND_RET(expr, string, ret)  do { assert((expr) && string); if (!(expr)) return (ret); } while(0)
+#define ASSERT_AND_RET(expr, string, ret)  		do { assert((expr) && string); if (!(expr)) return (ret); } while(0)
+#define ASSERT_AND_RET_DBG(expr, string, ret, blk) 	do { if (!(expr)) { { blk } assert(0 && string); return (ret); } } while(0)
 #endif

 /* @@@ replace use of array "in" by access functions. */
@@ -366,9 +377,25 @@
       }

       for (i = 0; i < get_method_n_params(mt); i++) {
-        ASSERT_AND_RET(
+        ASSERT_AND_RET_DBG(
             get_irn_mode(get_Call_param(n, i)) == get_type_mode(get_method_param_type(mt, i)),
-            "Mode of arg for Call doesn't match mode of arg type.", 0);
+            "Mode of arg for Call doesn't match mode of arg type.", 0,
+	    {
+	      int i;
+
+	      fprintf(stderr, "Assertion for Call type-check failed: %s(", get_type_name(mt));
+	      for (i = 0; i < get_method_n_params(mt); ++i) {
+		fprintf(stderr, "%s ", get_mode_name(get_type_mode(get_method_param_type(mt, i))));
+	      }
+	      fprintf(stderr, ") != CALL(");
+
+	      for (i = 0; i < get_Call_n_params(n); ++i) {
+		fprintf(stderr, "%s ", get_mode_name(get_irn_mode(get_Call_param(n, i))));
+	      }
+	      fprintf(stderr, ")\n");
+
+	    }
+	    );
       }
       break;


Control flow optimization: Merge consecutive blocks.

Merge a block with its only control flow predecessor,
if it contains no phi nodes and the block is the only successor of the predecessor.

--- ir/opt/cfopt.c
+++ ir/opt/cfopt.c
@@ -232,6 +232,24 @@
 non_dispensable:
 	set_Block_removable(predb, false);
 	return 1;
+}
+
+/**
+ * This method merges blocks. A block is applicable to be merged, if it
+ * has only one predecessor with an unconditional jump to this block;
+ * and if this block does not contain any phis.
+ */
+static void merge_blocks(ir_node *b)
+{
+	if (get_Block_n_cfgpreds(b) == 1) {
+		ir_node* pred = get_Block_cfgpred(b, 0);
+		if (is_Jmp(pred)) {
+			ir_node* pred_block = get_nodes_block(pred);
+			if (get_Block_phis(b) == NULL) {
+				exchange(b, pred_block);
+			}
+		}
+	}
 }

 /**
@@ -861,7 +879,7 @@
 	 * blocks, which it finds in a linked list computed before.
 	 * */
 	assure_doms(irg);
-	irg_block_walk_graph(irg, optimize_blocks, NULL, &env);
+	irg_block_walk_graph(irg, optimize_blocks, merge_blocks, &env);

 	new_end = optimize_in_place(end);
 	if (new_end != end) {


Adapt cfopt to Bads with modes

Adapt cfopt to Bads with modes

--- ir/opt/cfopt.c
+++ ir/opt/cfopt.c
@@ -291,11 +291,12 @@
 		/* Find the new predecessors for the Phi */
 		p_preds = 0;
 		for (i = 0, n = get_Block_n_cfgpreds(b); i < n; ++i) {
+			ir_graph *irg = get_irn_irg(b);
 			pred = get_Block_cfgpred_block(b, i);

 			if (is_Bad(pred)) {
 				/* case Phi 1: maintain Bads, as somebody else is responsible to remove them */
-				in[p_preds++] = pred;
+				in[p_preds++] = new_r_Bad(irg, get_irn_mode(phi));
 			} else if (is_Block_removable(pred) && !Block_block_visited(pred)) {
 				/* case Phi 2: It's an empty block and not yet visited. */
 				ir_node *phi_pred = get_Phi_pred(phi, i);
@@ -304,7 +305,7 @@
 					ir_node *pred_pred = get_Block_cfgpred(pred, j);

 					if (is_Bad(pred_pred)) {
-						in[p_preds++] = pred_pred;
+						in[p_preds++] = new_r_Bad(irg, get_irn_mode(phi));
 						continue;
 					}

@@ -425,10 +426,11 @@
 	for (i = 0; i < get_Block_n_cfgpreds(b); i++) {
 		ir_node *pred  = get_Block_cfgpred(b, i);
 		ir_node *predb = get_nodes_block(pred);
+		ir_graph *irg  = get_irn_irg(pred);

 		/* case 1: Do nothing */
 		if (is_Bad(pred)) {
-			in[n_preds++] = pred;
+			in[n_preds++] = new_r_Bad(irg, mode_X);
 			continue;
 		}
 		if (is_Block_removable(predb) && !Block_block_visited(predb)) {
@@ -437,7 +439,7 @@
 				ir_node *predpred = get_Block_cfgpred(predb, j);

 				if (is_Bad(predpred)) {
-					in[n_preds++] = predpred;
+					in[n_preds++] = new_r_Bad(irg, mode_X);
 					continue;
 				}


Add `Mx` to `Patch` in doosabin/doosabin.h

--- doosabin/doosabin.h
+++ doosabin/doosabin.h
@@ -125,6 +125,7 @@
   EVALUATE(Muu, SecondDerivative, Position, MultiplyAndScale<4>);
   EVALUATE(Muv, FirstDerivative, FirstDerivative, MultiplyAndScale<4>);
   EVALUATE(Mvv, Position, SecondDerivative, MultiplyAndScale<4>);
+  EVALUATE(Mx, Position, Position, MultiplyAndRepeat);
   #undef EVALUATE

  private:
@@ -410,6 +411,39 @@
     }
   };

+  class MultiplyAndRepeat {
+   public:
+    template <typename S, typename B, typename TX, typename R>
+    inline void operator()(size_t depth, const S& S, const B& b, const TX& X,
+                           R* r) const {
+      if (S.cols() <= kMaxNNoAlloc) {
+        Scalar StB_data[kMaxNNoAlloc];
+        Eigen::Map<Vector> StB(StB_data, S.cols());
+        StB.noalias() = S.transpose() * b;
+        Repeat(StB, X.rows(), r);
+      } else {
+        Vector StB;
+        StB.noalias() = S.transpose() * b;
+        Repeat(StB, X.rows(), r);
+      }
+    }
+
+   private:
+    template <typename STB, typename R>
+    inline void Repeat(const STB& StB, typename STB::Index d, R* r) const {
+      typedef typename STB::Index Index;
+      const Index n = StB.size();
+      r->resize((d * d) * n);
+      r->setZero();
+
+      for (Index i = 0; i < n; ++i) {
+        for (Index j = 0; j < d; ++j) {
+          (*r)[d * d * i + d * j + j] = StB[i];
+        }
+      }
+    }
+  };
+
  private:
   FaceArray _face_array;
   const Patch<Scalar>* _parent;


retry more

retry more

--- mount_slash/bflush.c
+++ mount_slash/bflush.c
@@ -321,7 +321,8 @@

 	if (rc == -ENOSPC || r->biorq_retries >= SL_MAX_BMAPFLSH_RETRIES ||
 	    ((r->biorq_flags & BIORQ_EXPIRE) &&
-	     (r->biorq_retries >= msl_max_retries + 3))) {
+	     (r->biorq_retries >=
+	     (msl_max_retries < 3 ? 5 : msl_max_retries * 2)))) {

 		bci = bmap_2_bci(r->biorq_bmap);
 		if (rc && !bci->bci_flush_rc)


combo: fix too many nodes becoming undefined

The rule that a rule becomes undefined if it has an undefined input is
only true if the node has no side effects.

This fixes opt/combo7.c

--- ir/opt/combo.c
+++ ir/opt/combo.c
@@ -1790,22 +1790,24 @@
 static void default_compute(node_t *node)
 {
 	ir_node *irn = node->node;
+	if (get_irn_mode(irn) == mode_X)
+		node->type.tv = tarval_reachable;

 	/* if any of the data inputs have type top, the result is type top */
-	for (int i = get_irn_arity(irn); i-- > 0; ) {
-		ir_node *pred = get_irn_n(irn, i);
-		node_t  *p    = get_irn_node(pred);
-
-		if (p->type.tv == tarval_top) {
-			node->type.tv = tarval_top;
-			return;
-		}
-	}
-
-	if (get_irn_mode(node->node) == mode_X)
-		node->type.tv = tarval_reachable;
-	else
-		node->type.tv = computed_value(irn);
+	ir_node *op  = skip_Proj(irn);
+	if (!is_memop(op) || is_Mod(op) || is_Div(op)) {
+		for (int i = get_irn_arity(irn); i-- > 0; ) {
+			ir_node *pred = get_irn_n(irn, i);
+			node_t  *p    = get_irn_node(pred);
+
+			if (p->type.tv == tarval_top) {
+				node->type.tv = tarval_top;
+				return;
+			}
+		}
+	}
+
+	node->type.tv = computed_value(irn);
 }

 /**
@@ -1900,20 +1902,6 @@
 {
 	/* the End node is NOT dead of course */
 	node->type.tv = tarval_reachable;
-}
-
-/**
- * (Re-)compute the type for a Call.
- *
- * @param node  the node
- */
-static void compute_Call(node_t *node)
-{
-	/*
-	 * A Call computes always bottom, even if it has Unknown
-	 * predecessors.
-	 */
-	node->type.tv = tarval_bottom;
 }

 /**
@@ -3356,7 +3344,6 @@
 	set_compute_func(op_Align,   compute_Align);
 	set_compute_func(op_Bad,     compute_Bad);
 	set_compute_func(op_Block,   compute_Block);
-	set_compute_func(op_Call,    compute_Call);
 	set_compute_func(op_Cmp,     compute_Cmp);
 	set_compute_func(op_Confirm, compute_Confirm);
 	set_compute_func(op_End,     compute_End);


Used now get_type_size_bits() and get_type_alignment_bits() instead of using values from the type mode

[r4149]

--- ir/tr/entity.c
+++ ir/tr/entity.c
@@ -761,13 +761,13 @@
     type *node_tp = get_entity_type(node);
     type *owner_tp = get_entity_owner(node);
     if (is_array_type(owner_tp)) {
-      int size  = get_mode_size_bits (get_type_mode(node_tp));
-      int align = get_mode_align_bits(get_type_mode(node_tp));
+      int size  = get_type_size_bits(node_tp);
+      int align = get_type_alignment_bits(node_tp);
       if (size < align)
-    size = align;
+        size = align;
       else {
-    assert(size % align == 0);
-    /* ansonsten aufrunden */
+        assert(size % align == 0);
+        /* ansonsten aufrunden */
       }
       offset += size * get_compound_graph_path_array_index(path, i);
     } else {


cxgb4: Fixed the code to use correct length for part number

Previously it was using the length value of serial number.
Also added macro for VPD unique identifier (0x82).

Signed-off-by: Casey Leedom <dcfbcb54931b10a0f02f8363358ec242f10c17f5@chelsio.com>
Signed-off-by: Hariprasad Shenai <5dd26741d612710d1bda6f7e0b02a31f31113b34@chelsio.com>
Signed-off-by: David S. Miller <fe08d3c717adf2ae63592e4c9aec6e3e404d8e3e@davemloft.net>


More doxygen comments

More doxygen comments

[r732]

--- ir/tr/entity.h
+++ ir/tr/entity.h
@@ -116,6 +116,7 @@
 /* to resolve recursion between entity.h and type.h */
 #ifndef _ENTITY_TYPEDEF_
 #define _ENTITY_TYPEDEF_
+/** the type of an entity */
 typedef struct entity entity;
 #endif


Removed unused code

Removed unused code

Signed-off-by: Nick Avramoussis <ce9ae7fb000f2865db247e53b12753caeda92c74@users.noreply.github.com>

--- openvdb_ax/openvdb_ax/codegen/PointComputeGenerator.h
+++ openvdb_ax/openvdb_ax/codegen/PointComputeGenerator.h
@@ -32,25 +32,6 @@
 ///////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////

-inline const std::map<const char*, uint64_t>& EncoderFlags()
-{
-    static const std::map<const char*, uint64_t> flags {
-        { "uniform", uint64_t(1<<0) },
-        { points::NullCodec::name(), uint64_t(1<<1) },
-        { points::TruncateCodec::name(), uint64_t(1<<2) },
-        { points::FixedPointCodec<false, points::UnitRange>::name(), uint64_t(1<<3) },
-        { points::FixedPointCodec<true, points::UnitRange>::name(), uint64_t(1<<4) },
-        { points::FixedPointCodec<false, points::PositionRange>::name(), uint64_t(1<<5) },
-        { points::FixedPointCodec<true, points::PositionRange>::name(), uint64_t(1<<6) }
-        //{ UnitVecCodec::name(), uint64_t(1<<7) }
-    };
-
-    return flags;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////////////////
-
 struct PointKernelValue
 {
     // The signature of the generated function
@@ -76,24 +57,6 @@

 struct PointKernelAttributeArray
 {
-    enum ArgKey {
-        kCustomData = 0,
-        kOrigin,
-        kValueBuffer,
-        kActive,
-        kPointIndex,
-        kTransforms,
-        kAttributeBuffers,
-        kAttributeFlags,
-        kAttributeSet,
-        kGroupHandles,
-        kLeafData
-    };
-
-    static inline llvm::Value* getArg(llvm::Function* F, const ArgKey key) {
-        return llvm::cast<llvm::Argument>(F->arg_begin() + static_cast<int>(key));
-    }
-
     // The signature of the generated function
     using Signature =
         void(const void* const,


Fixed memory leak in flann KMeansIndex

Fixed memory leak in flann KMeansIndex

--- modules/flann/include/opencv2/flann/kmeans_index.h
+++ modules/flann/include/opencv2/flann/kmeans_index.h
@@ -874,6 +874,8 @@
             computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
             start=end;
         }
+
+        delete[] centers;
     }


Adjust comment following r29182 post-commit feedback.

Put now-unused macros back to how they are upstream.

BUG=24911
TEST=none
Review URL: http://codereview.chromium.org/289003

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@29328 0039d316-1c4b-4281-b951-d872f2087c98

--- base/third_party/nspr/prtypes.h
+++ base/third_party/nspr/prtypes.h
@@ -91,11 +91,10 @@
 #if 1

 /*
-** Chrome-local change: the portions of NSPR used for Chrome are
-** implementation details of Chrome's base module.  NSPR symbols do not need
-** to be exported beyond the module in which they are used.  For all
-** platforms, avoid decorating functions with specific visibility and access
-** keywords.
+** Local change: the portions of NSPR used by the base module are
+** implementation details.  NSPR symbols do not need to be exported beyond
+** the base module.  For all platforms, avoid decorating functions with
+** specific visibility and access keywords.
 */

 #define PR_EXPORT(__type) extern __type
@@ -116,11 +115,11 @@

 #define PR_EXPORT(__type) extern __declspec(dllexport) __type
 #define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPORT(__type) extern __type
+#define PR_IMPORT(__type) __declspec(dllimport) __type
 #define PR_IMPORT_DATA(__type) __declspec(dllimport) __type

 #define PR_EXTERN(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT(__type) __type
+#define PR_IMPLEMENT(__type) __declspec(dllexport) __type
 #define PR_EXTERN_DATA(__type) extern __declspec(dllexport) __type
 #define PR_IMPLEMENT_DATA(__type) __declspec(dllexport) __type


isl_vertices.c: avoid use of unitialized variables on an error path

Signed-off-by: Sven Verdoolaege <e5350bbed4977f5eb8ae1dc6abd9ae59d21ace75@kotnet.org>

--- isl_vertices.c
+++ isl_vertices.c
@@ -392,10 +392,10 @@
 	int level;
 	int init;
 	unsigned nvar;
-	int *selection;
+	int *selection = NULL;
 	int selected;
-	struct isl_tab_undo **snap;
-	isl_mat *facets;
+	struct isl_tab_undo **snap = NULL;
+	isl_mat *facets = NULL;
 	struct isl_vertex_list *list = NULL;
 	int n_vertices = 0;
 	isl_vertices *vertices;