#ifndef APS_HPP_
#define APS_HPP_

#include "print.hpp"
#include "aps.h"

template<class T>
T sort(const T &src)
{
	T dst;

	dst = src;
	std::sort(dst.begin(), dst.end());
	return (dst);
}

template<class T>
T set_difference(const T &set, const T &subset)
{
	T dst(set.size());
	T sortedset = sort(set);
	T sortedsubset = sort(subset);

	dst.resize(std::set_difference(
			sortedset.begin(), sortedset.end(),
			sortedsubset.begin(), sortedsubset.end(),
			dst.begin()) - dst.begin());
	return (dst);
}

template<class IT>
IT next_permutation(IT first, IT last)
{
	IT a, b;

	if (first == last) return (last);
	for (a = last, b = --a; b != first; b = a)
		if (*--a < *b) break;
	if (b == first) return (last);
	while (b != last && *a < *b) b++;
	std::iter_swap(a, --b);
	std::reverse(++a, last);
	return (--a);
}

template<class RECORD, class KEY>
Db<RECORD,KEY>::Db(KEY anextkey) : nextkey(anextkey)
{
}

template<class RECORD, class KEY>
KEY Db<RECORD,KEY>::getnextkey(void) const
{
	return (nextkey);
}

template<class RECORD, class KEY>
KEY Db<RECORD,KEY>::set(const RECORD &record)
{
	KEY key;

	key = dbmap.insert(std::pair<RECORD,KEY>(record, nextkey)).first->second;
	if (key == nextkey) nextkey++;
	return (key);
}

template<class RECORD, class KEY>
bool Db<RECORD,KEY>::isnew(const RECORD &record)
{
	KEY key;

	key = nextkey;
	return (set(record) == key);
}

template<class RECORD, class KEY>
std::ostream &operator<<(std::ostream &output, const Db<RECORD,KEY> &db)
{
	output << db.nextkey << ':' << db.dbmap;
	return (output);
}

template<class InputIterator>
Pos::Pos(InputIterator first, InputIterator last)
	: vector<LocId>(first, last)
{
}

template<class InputIterator>
Map::Map(InputIterator first, InputIterator last)
	: vector<LocId>(first, last)
{
}

template<class T>
T Map::operator*(const T &rhs) const
{
	T lhs(rhs.size());
	typename T::const_iterator irhs;
	typename T::iterator ilhs;

	ilhs = lhs.begin();
	for (irhs = rhs.begin(); irhs != rhs.end(); irhs++)
		*ilhs++ = (*this)[*irhs];
	return (lhs);
}

template<class T>
bool Map::issymmetric(const T &rhs) const
{
	return (sort(rhs) == sort(operator*(rhs)));
}

template<class T>
T Maps::operator*(const T &rhs) const
{
	T lhs(size() * rhs.size());
	typename T::const_iterator irhs;
	typename T::iterator ilhs;
	typename Maps::const_iterator i;

	ilhs = lhs.begin();
	for (i = begin(); i != end(); i++)
		for (irhs = rhs.begin(); irhs != rhs.end(); irhs++)
			*ilhs++ = *i * *irhs;
	return (lhs);
}

template<class T>
Maps Maps::symmetric(const T &rhs) const
{
	Maps maps;
	typename T::const_iterator irhs;
	typename T::iterator ilhs;
	typename Maps::const_iterator i;

	for (i = begin(); i != end(); i++) {
		for (irhs = rhs.begin(); irhs != rhs.end(); irhs++)
			if (!i->issymmetric(*irhs)) break;
		if (irhs == rhs.end()) maps.push_back(*i);
	}
	return (maps);
}

#endif // end APS_HPP_
