package net.imglib2.histogram;

import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Paths;

import ij.IJ;
import net.imglib2.IterableInterval;
import net.imglib2.RandomAccess;
import net.imglib2.converter.Converter;
import net.imglib2.converter.Converters;
import net.imglib2.filter.MaskedIterableFilter;
import net.imglib2.filter.MaskedIterableFilter.MaskedIterator;
import net.imglib2.img.display.imagej.ImageJFunctions;
import net.imglib2.type.logic.BoolType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.LongType;
import net.imglib2.type.numeric.real.FloatType;


public class BuildHistogram {

	public static void main(String[] args)
	{
		final String outF = args[ 0 ];
		final String imF = args[ 1 ];
		final float histmin = Float.parseFloat( args[ 2 ]);
		final float histmax = Float.parseFloat( args[ 3 ]);
		final int numBins = Integer.parseInt( args[ 4 ]);
		final String maskF = args[ 5 ];
		final float maskthresh = Float.parseFloat( args[ 6 ]);
		
		boolean tailBins = false;
		if( args.length >= 8 )
			tailBins = Boolean.parseBoolean( args[ 7 ] );

		System.out.println( "tailBins: " + tailBins );
		Real1dBinMapper<FloatType> binMapper = new Real1dBinMapper<FloatType>(
				histmin, histmax, numBins, tailBins );

		IterableInterval<FloatType> img = ImageJFunctions.convertFloat( IJ.openImage( imF ));
		IterableInterval<FloatType> maskRaw = null;
		if( maskF.equals( imF ))
		{
			System.out.println( "mask is same as input image");
			maskRaw = img;
		}
		else
			maskRaw = ImageJFunctions.convertFloat( IJ.openImage( maskF ));
		
		Converter<FloatType,BoolType> maskConv = new Converter<FloatType,BoolType>()
		{
			@Override
			public void convert(FloatType input, BoolType output) {
				if( input.get() < maskthresh )
				{
					output.set( false );
				}
				else
				{
					output.set( true );
				}
			}
		};
		IterableInterval<BoolType> mask = Converters.convert( maskRaw, maskConv, new BoolType());
		
		final Histogram1d<FloatType> hist = new Histogram1d<>( binMapper );
		MaskedIterableFilter<FloatType,BoolType> mit = 
				new MaskedIterableFilter<FloatType,BoolType>( mask.iterator() );
		mit.set( img );
		hist.countData( mit );
		MaskedIterator<FloatType,BoolType> mi = (MaskedIterator<FloatType,BoolType>)mit.iterator();

		System.out.println( "MI total   : " + mi.getNumTotal() );
		System.out.println( "mi valid   : " + mi.getNumValid() );
		System.out.println( "mi invalid : " + mi.getNumInvalid() );
		System.out.println( "hist total : " + hist.totalCount() );

		writeHistogram( outF, hist );
	}
	
	public static <T extends RealType<T>> boolean writeHistogram( String outPath, Histogram1d<T> hist )
	{
		T t = hist.firstDataValue().copy();
		RandomAccess<LongType> hra = hist.randomAccess();
		try
		{
			BufferedWriter writer = Files.newBufferedWriter(Paths.get(outPath));
			for( int i = 0; i < hist.getBinCount(); i++ )
			{
				hist.getCenterValue( i, t );
				hra.setPosition( i, 0 );
				String line = Double.toString( t.getRealDouble() ) + "," + 
						Long.toString( hra.get().get() );
				writer.write( line + "\n" );
			}
			writer.close();
		} catch( Exception e )
		{
			e.printStackTrace();
			return false;
		}
        return true;
	}

}

@@ -52,24 +52,73 @@
 eredWriter;%0A
+import java.io.File;%0Aimport java.io.IOException;%0A
 import java.
@@ -176,16 +176,76 @@
  ij.IJ;%0A
+import io.nii.NiftiIo;%0Aimport loci.formats.FormatException;%0A
 import n
@@ -805,16 +805,52 @@
 %5B%5D args)
+ throws FormatException, IOException
 %0A%09%7B%0A%09%09fi
@@ -1439,36 +1439,255 @@
 %0A%0A%09%09
-IterableInterval%3CFloatType%3E 
+System.out.println( %22imF   : %22 + imF );%0A%09%09System.out.println( %22maskF : %22 + maskF );%0A%09%09IterableInterval%3CFloatType%3E img;%0A%09%09if( imF.endsWith( %22nii%22 ))%0A%09%09%7B%0A%09%09%09img = ImageJFunctions.convertFloat( NiftiIo.readNifti( new File( imF )));%0A%09%09%7D%0A%09%09else%0A%09%09%7B%0A%09%09%09
 img 
@@ -1737,18 +1737,27 @@
 e( imF )
+ 
 );
+%09%0A%09%09%7D%0A%09%09
 %0A%09%09Itera
@@ -1910,16 +1910,160 @@
 %0A%09%09else%0A
+%09%09%7B%0A%09%09%09if( maskF.endsWith( %22nii%22 ))%0A%09%09%09%7B%0A%09%09%09%09maskRaw = ImageJFunctions.convertFloat( NiftiIo.readNifti( new File( maskF )));%0A%09%09%09%7D%0A%09%09%09else%0A%09%09%09%7B%0A%09
 %09%09%09maskR
@@ -2118,18 +2118,29 @@
  maskF )
+ 
 );
+%09%0A%09%09%09%7D%0A%09%09%7D
 %0A%09%09%0A%09%09Co

add nii support to BuildHistogram