/*
 * Tools related to the MitoPacq, the CBIA time-lapse cell observation simulator.
 *
 * Copyright (C) 2005-2013   Centre for Biomedical Image Analysis (CBIA)
 *
 * 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 <i3d/image3d.h>


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

template <class MT>
void RelabelCellMask(i3d::Image3d<MT> &mask, const MT idFrom, const MT idTo) {
	MT *pm=mask.GetFirstVoxelAddr();
	MT *pmL=mask.GetFirstVoxelAddr() + mask.GetImageSize();

	while (pm != pmL) {
		if (*pm == idFrom) *pm=idTo;
		++pm;
	}
}

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 != 5) {
		cout << "Program relabels given sequence of mask images.\n";
		cout << "Bad number of parameters\nUsage: " << argv[0] << " idFrom idTo countFrom countTo\n" \
	     << "example: " << argv[0] << " 10 20 0 99\n" \
	     << "which will relabel ID 10 to 20 in man_track%03d.tif files from 0 till 99.\n";
		return -2;
	}

	const MV idFrom=atoi(argv[1]);
	const MV idTo=atoi(argv[2]);
	const size_t countFrom=atoi(argv[3]);
	const size_t countTo=atoi(argv[4]);

	for (size_t T=countFrom; T <= countTo; ++T) {
		//open input mask
		char fn[50];
		sprintf(fn,"man_track%.3lu.tif",T);
		cout << "reading: " << fn << endl;

		i3d::Image3d<MV> mask(fn);
		RelabelCellMask(mask,idFrom,idTo);
		mask.SaveImage(fn);
	}

	return(0);
}
