/*
 * Tools related to the MitoPacq, the CBIA time-lapse cell observation simulator.
 *
 * This library-related tools is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <iostream>
#include <stdlib.h>
#include <i3d/image3d.h>

using std::cout;
using std::endl;

template <class VT>
void Relabel(i3d::Image3d<VT> &img,const VT Lout,const VT Lin) {
	VT *p=img.GetFirstVoxelAddr();
	const VT *pL=img.GetFirstVoxelAddr() + img.GetImageSize();

	while (p != pL) {
		if (*p == Lout) *p=Lin;
		++p;
	}
}

int main(int argc,char **argv) {
    cout << argv[0] << " - part of the tools set of the OpticalFlow library \n"
         "Copyright (C) 2005-2013 Centre for Biomedical Image Analysis (CBIA)\n"
         "This is free software; see the source for copying conditions. "
         "There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR "
         "A PARTICULAR PURPOSE.\n\n";

	//type of mask images
	typedef i3d::GRAY16 MV;

	if (argc == 1) {
		cout << "Usage: " << argv[0] << " image ID_to_be_removed\n";
		return(-1);
	}

	//read the image
	i3d::Image3d<MV> img(argv[1]);
	//MV maxID=img.GetMaxValue();

	MV id=(MV)atoi(argv[2]);
	Relabel(img,id,(MV)0);


/*
	//go over all IDs to be removed
	//SUPPLY IN INCREASING ORDER !!
	MV lastRemovedID=0;
	MV lastUsedID=0;

	int i=2;
	while (i < argc) {
		//remove this ID
		MV id=(MV)atoi(argv[i]);
		Relabel(img,id,(MV)0);

		if (lastRemovedID == 0) {
			lastRemovedID=id;
			lastUsedID=id-1;
		} else {
			//lastRemovedID introduced a hole in list of IDs
			//shift the interleaving interval right after the lastUsedID
			for (MV j=lastRemovedID+1; j < id; ++j)
				Relabel(img,j,++lastUsedID);

			lastRemovedID=id;
		}

		++i;
	}

	//finish relabeling
	if (lastRemovedID != 0) { //optimization :)
		for (MV j=lastRemovedID+1; j <= maxID; ++j)
			Relabel(img,j,++lastUsedID);
	}
*/

	//save the result
	img.SaveImage(argv[1]);

	return(0);
}
