#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) {
	//type of mask images
	typedef i3d::GRAY16 MV;

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

	//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);
}
