Index: trunk/psModules/src/camera/pmFPABin.c
===================================================================
--- trunk/psModules/src/camera/pmFPABin.c	(revision 24906)
+++ trunk/psModules/src/camera/pmFPABin.c	(revision 34800)
@@ -43,4 +43,8 @@
     }
 
+    int Nbits = (int) (ceil(log(maskVal)/log(2)) + 1);
+    int *bitcounter = malloc(sizeof(int) * Nbits);
+    int pxlcount;
+
     int xLast = numColsIn - 1, yLast = numRowsIn - 1; // Last index
     int yStart = psImageBinningGetFineY(binning, 0); // Starting input y for binning
@@ -55,6 +59,21 @@
             float sum = 0.0;            // Sum of pixels
             int numPix = 0;             // Number of pixels
+
+	    for (int j = 0; j < Nbits; j++) { // Reset bit counter
+	      bitcounter[j] = 0;
+	    }
+	    pxlcount = 0;
+	    
             for (int y = yStart; y < yStop; y++) {
                 for (int x = xStart; x < xStop; x++) {
+		  if (inMask && (inMask->data.PS_TYPE_IMAGE_MASK_DATA[y][x] != 0)) {
+		      for (int j = 0; j < Nbits; j++) {
+			psImageMaskType M = (psImageMaskType) pow(2,j);
+			if (inMask->data.PS_TYPE_IMAGE_MASK_DATA[y][x] & M) {
+			  bitcounter[j]++;
+			}
+		      }
+		    }
+		  
                     if (inMask && (inMask->data.PS_TYPE_IMAGE_MASK_DATA[y][x] & maskVal)) {
                         continue;
@@ -65,7 +84,10 @@
                     sum += inImage->data.F32[y][x];
                     numPix++;
+
+
                 }
             }
-
+	    
+	    
 	    // Values to set
             float imageValue;
@@ -79,5 +101,11 @@
             }
             outImage->data.F32[yOut][xOut] = imageValue;
-            outMask->data.PS_TYPE_IMAGE_MASK_DATA[yOut][xOut] = maskValue;
+	    //            outMask->data.PS_TYPE_IMAGE_MASK_DATA[yOut][xOut] = maskValue;
+	    outMask->data.PS_TYPE_IMAGE_MASK_DATA[yOut][xOut] = 0;
+	    for (int j = 0; j < Nbits; j++) {
+	      if (bitcounter[j] > 0.5 * pxlcount) {
+		outMask->data.PS_TYPE_IMAGE_MASK_DATA[yOut][xOut] |= (int) pow(2,j);
+	      }
+	    }
             xStart = xStop;
         }
