/*********************************************************************
 * This file is part of the PRAPI library.
 *
 * Copyright (C) 2002 Topi Mäenpää
 * All rights reserved.
 *
 * This program is free software. You can redistribute and/or modify
 * it under the terms of the free software licence found in the
 * accompanying file "COPYING". The licence terms must always be
 * redistributed with this source file. The above copyright notice
 * must be reproduced in all modified and unmodified copies of this
 * source file.
 *
 * $Revision: 1.2 $
 *********************************************************************/

#include <Math.h>
#include <functional>

#include "Component.h"

using namespace util;

namespace prapi { namespace binary {

	Component Component::getComponent(const Matrix<int>& labels, int index)
	{
		const int* data = labels.getData();
		Component result;
		int r,c;
		AllItems(r,c,labels)
			{
				if (*data)
					{
						result.comR += r;
						result.comC += c;
						result.mass++;
					}
				data++;
			}

		if (result.mass)
			{
				result.comR /= result.mass;
				result.comC /= result.mass;
			}
		result.labelIndex = index;
		return result;
	}

	List<Component> Component::getComponents(const Matrix<int>& labels)
	{
		List<Component> result(256);
		const int* data = labels.getData();
		int r,c;
		AllItems(r,c,labels)
			{
				if (*data)
					{
						if (*data > result.getLength())
							result.setLength(*data);
						int index = *data-1;
						result[index].comR += r;
						result[index].comC += c;
						result[index].mass++;
					}
				data++;
			}
		for (int i=result.getLength();i--;)
			{
				if (result[i].mass)
					{
						result[i].comR /= result[i].mass;
						result[i].comC /= result[i].mass;
					}
				result[i].labelIndex = i+1;
			}
		return result;
	}
}}
