/*
 * DPDA.h
 *
 * This file is part of Algorithms library toolkit.
 * Copyright (C) 2017 Jan Travnicek (jan.travnicek@fit.cvut.cz)

 * Algorithms library toolkit is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * Algorithms library toolkit 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 General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with Algorithms library toolkit.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  Created on: Apr 10, 2013
 *      Author: Jan Travnicek
 */

#ifndef DPDA_H_
#define DPDA_H_

#include <sstream>

#include <alib/set>
#include <alib/map>
#include <alib/vector>
#include <alib/algorithm>

#include <core/components.hpp>

#include <common/DefaultStateType.h>
#include <common/DefaultSymbolType.h>

#include <automaton/AutomatonException.h>

#include <core/normalize.hpp>
#include <alphabet/common/SymbolNormalize.h>
#include <automaton/common/AutomatonNormalize.h>

namespace automaton {

class InputAlphabet;
class PushdownStoreAlphabet;
class InitialSymbol;
class States;
class FinalStates;
class InitialState;

/**
 * \brief
 * Deterministic pushdown automaton. Accepts subset of context free languages.

 * \details
 * Definition
 * A = (Q, T, G, I, Z, \delta, F),
 * Q (States) = nonempty finite set of states,
 * T (TerminalAlphabet) = finite set of terminal symbols - having this empty won't let automaton do much though,
 * G (PushdownStoreAlphabet) = finite set of pushdown store symbol - having this empty makes the automaton equivalent to DFA
 * I (InitialState) = initial state,
 * Z (InitialPushdownStoreSymbol) = initial pushdown store symbol
 * \delta = transition function of the form A \times a \times \alpha -> B \times \beta, where A, B \in Q, a \in T \cup { \eps }, and \alpha, \beta \in G*,
 * F (FinalStates) = set of final states
 *
 * The transition functions must meet following criteria. Othervise adding conflicting transition will cause exception.
 * $|\delta (q, a, \gamma)| \leq 1$, $\forall q, a, \gamma, q \in Q, a \in (T \cup \{\varepsilon\}), \gamma \in G^*.$
 * if $\delta (q, a, \alpha) \neq \emptyset$, $\delta (q, a, \beta) \neq \emptyset$ and $\alpha \neq \beta$, then $\alpha$ is not suffix of $\beta$ and $\beta$ is not suffix of $\alpha$ (formally $\gamma \alpha \neq \beta and \alpha \neq \gamma \beta$).
 * if $\delta(q, a, \alpha) \neq \emptyset$, $\delta (q, \varepsilon, \beta) \neq \emptyset$, then $\alpha$ is not suffix of $\beta$ and $\beta$ is not suffix of $\alpha$ (fornally $\gamma \alpha \neq \beta and \alpha \neq \gamma \beta$).
 *
 * \tparam InputSymbolTypeT used for the terminal alphabet
 * \tparam PushdownSymbolTypeT used for the pushdown store alphabet
 * \tparam StateTypeT used to the states, and the initial state of the automaton.
 */
template < class InputSymbolTypeT = DefaultSymbolType, class PushdownStoreSymbolTypeT = DefaultSymbolType, class StateTypeT = DefaultStateType >
class DPDA final : public ext::CompareOperators < DPDA < InputSymbolTypeT, PushdownStoreSymbolTypeT, StateTypeT > >, public core::Components < DPDA < InputSymbolTypeT, PushdownStoreSymbolTypeT, StateTypeT >, ext::set < InputSymbolTypeT >, component::Set, InputAlphabet, ext::set < PushdownStoreSymbolTypeT >, component::Set, PushdownStoreAlphabet, PushdownStoreSymbolTypeT, component::Value, InitialSymbol, ext::set < StateTypeT >, component::Set, std::tuple < States, FinalStates >, StateTypeT, component::Value, InitialState > {
public:
	typedef InputSymbolTypeT InputSymbolType;
	typedef PushdownStoreSymbolTypeT PushdownStoreSymbolType;
	typedef StateTypeT StateType;

private:
	/**
	 * Transition function as mapping from a state times an input symbol or epsilon times string of pushdown store symbols on the left hand side to a state times string of pushdown store symbols.
	 */
	ext::map < ext::tuple < StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector < PushdownStoreSymbolType > >, ext::pair < StateType, ext::vector < PushdownStoreSymbolType > > > transitions;

public:
	/**
	 * \brief Creates a new instance of the automaton with a concrete set of states, input alphabet, pushdown store alphabet, initial state, initial pushdown symbol and a set of final states.
	 *
	 * \param states the initial set of states of the automaton
	 * \param inputAlphabet the initial input alphabet
	 * \param pushdownStoreAlphabet the initial set of symbols used in the pushdown store by the automaton
	 * \param initialState the initial state of the automaton
	 * \param initialPushdownSymbol the initial pushdown symbol of the automaton
	 * \param finalStates the initial set of final states of the automaton
	 */
	explicit DPDA ( ext::set < StateType > states, ext::set < InputSymbolType > inputAlphabet, ext::set < PushdownStoreSymbolType > pushdownStoreAlphabet, StateType initialState, PushdownStoreSymbolType initialSymbol, ext::set < StateType > finalStates );

	/**
	 * \brief Creates a new instance of the automaton with a concrete initial state and initial pushdown store symbol.
	 *
	 * \param initialState the initial state of the automaton
	 * \param initialPushdownSymbol the initial pushdown symbol of the automaton
	 */
	explicit DPDA ( StateType initialState, PushdownStoreSymbolType initialPushdownSymbol );

	/**
	 * Getter of the initial state.
	 *
	 * \returns the initial state of the automaton
	 */
	const StateType & getInitialState ( ) const & {
		return this-> template accessComponent < InitialState > ( ).get ( );
	}

	/**
	 * Getter of the initial state.
	 *
	 * \returns the initial state of the automaton
	 */
	StateType && getInitialState ( ) && {
		return std::move ( this-> template accessComponent < InitialState > ( ).get ( ) );
	}

	/**
	 * Setter of the initial state.
	 *
	 * \param state new initial state of the automaton
	 *
	 * \returns true if the initial state was indeed changed
	 */
	bool setInitialState ( StateType state ) {
		return this-> template accessComponent < InitialState > ( ).set ( std::move ( state ) );
	}

	/**
	 * Getter of states.
	 *
	 * \returns the states of the automaton
	 */
	const ext::set < StateType > & getStates ( ) const & {
		return this-> template accessComponent < States > ( ).get ( );
	}

	/**
	 * Getter of states.
	 *
	 * \returns the states of the automaton
	 */
	ext::set < StateType > && getStates ( ) && {
		return std::move ( this-> template accessComponent < States > ( ).get ( ) );
	}

	/**
	 * Adder of a state.
	 *
	 * \param state the new state to be added to a set of states
	 *
	 * \returns true if the state was indeed added
	 */
	bool addState ( StateType state ) {
		return this-> template accessComponent < States > ( ).add ( std::move ( state ) );
	}

	/**
	 * Setter of states.
	 *
	 * \param states completely new set of states
	 */
	void setStates ( ext::set < StateType > states ) {
		this-> template accessComponent < States > ( ).set ( std::move ( states ) );
	}

	/**
	 * Remover of a state.
	 *
	 * \param state a state to be removed from a set of states
	 *
	 * \returns true if the state was indeed removed
	 */
	void removeState ( const StateType & state ) {
		this-> template accessComponent < States > ( ).remove ( state );
	}

	/**
	 * Getter of final states.
	 *
	 * \returns the final states of the automaton
	 */
	const ext::set < StateType > & getFinalStates ( ) const & {
		return this-> template accessComponent < FinalStates > ( ).get ( );
	}

	/**
	 * Getter of final states.
	 *
	 * \returns the final states of the automaton
	 */
	ext::set < StateType > && getFinalStates ( ) && {
		return std::move ( this-> template accessComponent < FinalStates > ( ).get ( ) );
	}

	/**
	 * Adder of a final state.
	 *
	 * \param state the new state to be added to a set of final states
	 *
	 * \returns true if the state was indeed added
	 */
	bool addFinalState ( StateType state ) {
		return this-> template accessComponent < FinalStates > ( ).add ( std::move ( state ) );
	}

	/**
	 * Setter of final states.
	 *
	 * \param states completely new set of final states
	 */
	void setFinalStates ( ext::set < StateType > states ) {
		this-> template accessComponent < FinalStates > ( ).set ( std::move ( states ) );
	}

	/**
	 * Remover of a final state.
	 *
	 * \param state a state to be removed from a set of final states
	 *
	 * \returns true if the state was indeed removed
	 */
	void removeFinalState ( const StateType & state ) {
		this-> template accessComponent < FinalStates > ( ).remove ( state );
	}

	/**
	 * Getter of the pushdown store alphabet.
	 *
	 * \returns the pushdown store alphabet of the automaton
	 */
	const ext::set < PushdownStoreSymbolType > & getPushdownStoreAlphabet ( ) const & {
		return this->template accessComponent < PushdownStoreAlphabet > ( ).get ( );
	}

	/**
	 * Getter of the pushdown store alphabet.
	 *
	 * \returns the pushdown store alphabet of the automaton
	 */
	ext::set < PushdownStoreSymbolType > && getPushdownStoreAlphabet ( ) && {
		return std::move ( this->template accessComponent < PushdownStoreAlphabet > ( ).get ( ) );
	}

	/**
	 * Adder of a pushdown store symbol.
	 *
	 * \param symbol the new symbol to be added to a pushdown store alphabet
	 *
	 * \returns true if the symbol was indeed added
	 */
	bool addPushdownStoreSymbol ( PushdownStoreSymbolType symbol ) {
		return this->template accessComponent < PushdownStoreAlphabet > ( ).add ( std::move ( symbol ) );
	}

	/**
	 * Adder of pushdown store symbols.
	 *
	 * \param symbols new symbols to be added to a pushdown store alphabet
	 */
	void addPushdownStoreSymbols ( ext::set < PushdownStoreSymbolType > symbols ) {
		this->template accessComponent < PushdownStoreAlphabet > ( ).add ( std::move ( symbols ) );
	}

	/**
	 * Setter of a pushdown store alphabet.
	 *
	 * \param symbols completely new pushdown store alphabet
	 */
	void setPushdownStoreAlphabet ( ext::set < PushdownStoreSymbolType > symbols ) {
		this->template accessComponent < PushdownStoreAlphabet > ( ).set ( std::move ( symbols ) );
	}

	/**
	 * Remover of an pushdown store symbol.
	 *
	 * \param symbol a symbol to be removed from a pushdown store alphabet
	 *
	 * \returns true if the symbol was indeed removed
	 */
	void removePushdownStoreSymbol ( const PushdownStoreSymbolType & symbol ) {
		this->template accessComponent < PushdownStoreAlphabet > ( ).remove ( symbol );
	}

	/**
	 * Getter of the initial pushdown store symbol.
	 *
	 * \returns the initial pushdown store symbol of the automaton
	 */
	const PushdownStoreSymbolType & getInitialSymbol ( ) const & {
		return this->template accessComponent < InitialSymbol > ( ).get ( );
	}

	/**
	 * Getter of the initial pushdown store symbol.
	 *
	 * \returns the initial pushdown store symbol of the automaton
	 */
	PushdownStoreSymbolType && getInitialSymbol ( ) && {
		return std::move ( this->template accessComponent < InitialSymbol > ( ).get ( ) );
	}

	/**
	 * Setter of the initial pushdown store symbol.
	 *
	 * \param symbol new initial pushdown store symbol of the automaton
	 *
	 * \returns true if the initial pushdown store symbol was indeed changed
	 */
	bool setInitialSymbol ( PushdownStoreSymbolType symbol ) {
		return this->template accessComponent < InitialSymbol > ( ).set ( std::move ( symbol ) );
	}

	/**
	 * Getter of the input alphabet.
	 *
	 * \returns the input alphabet of the automaton
	 */
	const ext::set < InputSymbolType > & getInputAlphabet ( ) const & {
		return this-> template accessComponent < InputAlphabet > ( ).get ( );
	}

	/**
	 * Getter of the input alphabet.
	 *
	 * \returns the input alphabet of the automaton
	 */
	ext::set < InputSymbolType > && getInputAlphabet ( ) && {
		return std::move ( this-> template accessComponent < InputAlphabet > ( ).get ( ) );
	}

	/**
	 * Adder of a input symbol.
	 *
	 * \param symbol the new symbol to be added to an input alphabet
	 *
	 * \returns true if the symbol was indeed added
	 */
	bool addInputSymbol ( InputSymbolType symbol ) {
		return this-> template accessComponent < InputAlphabet > ( ).add ( std::move ( symbol ) );
	}

	/**
	 * Adder of input symbols.
	 *
	 * \param symbols new symbols to be added to an input alphabet
	 */
	void addInputSymbols ( ext::set < InputSymbolType > symbols ) {
		this-> template accessComponent < InputAlphabet > ( ).add ( std::move ( symbols ) );
	}

	/**
	 * Setter of input alphabet.
	 *
	 * \param symbols completely new input alphabet
	 */
	void setInputAlphabet ( ext::set < InputSymbolType > symbols ) {
		this-> template accessComponent < InputAlphabet > ( ).set ( std::move ( symbols ) );
	}

	/**
	 * Remover of an input symbol.
	 *
	 * \param symbol a symbol to be removed from an input alphabet
	 *
	 * \returns true if the symbol was indeed removed
	 */
	void removeInputSymbol ( const InputSymbolType & symbol ) {
		this-> template accessComponent < InputAlphabet > ( ).remove ( symbol );
	}

	/**
	 * \brief Adds a transition to the automaton.
	 *
	 * \details The transition is in a form A \times a \times \alpha -> B \times \beta, where A, B \in Q, a \in T \cup { \eps }, and \alpha, \beta \in G*
	 *
	 * \param from the source state (A)
	 * \param input the input symbol or epsilon (a)
	 * \param pop symbols to be poped from pushdown store on the transition use (\alpha)
	 * \param to the target state (B)
	 * \param push symbols to be pushed to the pushdown store on the transition use (\beta)
	 *
	 * \throws AutomatonException when transition contains state or symbol not present in the automaton components or when the transition would cause nondeterminism
	 *
	 * \returns true if the transition was indeed added
	 */
	bool addTransition ( StateType from, common::symbol_or_epsilon < InputSymbolType > input, ext::vector < PushdownStoreSymbolType > pop, StateType to, ext::vector < PushdownStoreSymbolType > push );

	/**
	 * \brief Adds a transition to the automaton.
	 *
	 * \details The transition is in a form A \times a \times \alpha -> B \times \beta, where A, B \in Q, a \in T, and \alpha, \beta \in G*
	 *
	 * \param from the source state (A)
	 * \param input the input symbol (a)
	 * \param pop symbols to be poped from pushdown store on the transition use (\alpha)
	 * \param to the target state (B)
	 * \param push symbols to be pushed to the pushdown store on the transition use (\beta)
	 *
	 * \throws AutomatonException when transition contains state or symbol not present in the automaton components or when the transition would cause nondeterminism
	 *
	 * \returns true if the transition was indeed added
	 */
	bool addTransition ( StateType from, InputSymbolType input, ext::vector < PushdownStoreSymbolType > pop, StateType to, ext::vector < PushdownStoreSymbolType > push );

	/**
	 * \brief Adds a transition to the automaton.
	 *
	 * \details The transition is in a form A \times \eps \times \alpha -> B \times \beta, where A, B \in Q, and \alpha, \beta \in G*
	 *
	 * \param from the source state (A)
	 * \param pop symbols to be poped from pushdown store on the transition use (\alpha)
	 * \param to the target state (B)
	 * \param push symbols to be pushed to the pushdown store on the transition use (\beta)
	 *
	 * \throws AutomatonException when transition contains state or symbol not present in the automaton components or when the transition would cause nondeterminism
	 *
	 * \returns true if the transition was indeed added
	 */
	bool addTransition ( StateType from, ext::vector < PushdownStoreSymbolType > pop, StateType to, ext::vector < PushdownStoreSymbolType > push );

	/**
	 * \brief Removes a transition from the automaton.
	 *
	 * \details The transition is in a form A \times a \times \alpha -> B \times \beta, where A, B \in Q, a \in T \cup { \eps }, and \alpha, \beta \in G*
	 *
	 * \param from the source state (A)
	 * \param input the input symbol or epsilon (a)
	 * \param pop symbols poped from pushdown store on the transition use (\alpha)
	 * \param to the target state (B)
	 * \param push symbols pushed to the pushdown store on the transition use (\beta)
	 *
	 * \throws AutomatonException when removed transition left hand side was found but the right hand side did not match.
	 *
	 * \returns true if the transition was indeed removed
	 */
	bool removeTransition ( const StateType & from, const common::symbol_or_epsilon < InputSymbolType > & input, const ext::vector < PushdownStoreSymbolType > & pop, const StateType & to, const ext::vector < PushdownStoreSymbolType > & push );

	/**
	 * \brief Removes a transition from the automaton.
	 *
	 * \details The transition is in a form A \times a \times \alpha -> B \times \beta, where A, B \in Q, a \in T, and \alpha, \beta \in G*
	 *
	 * \param from the source state (A)
	 * \param input the input symbol (a)
	 * \param pop symbols poped from pushdown store on the transition use (\alpha)
	 * \param to the target state (B)
	 * \param push symbols pushed to the pushdown store on the transition use (\beta)
	 *
	 * \throws AutomatonException when removed transition left hand side was found but the right hand side did not match.
	 *
	 * \returns true if the transition was indeed removed
	 */
	bool removeTransition ( const StateType & from, const InputSymbolType & input, const ext::vector < PushdownStoreSymbolType > & pop, const StateType & to, const ext::vector < PushdownStoreSymbolType > & push );

	/**
	 * \brief Removes a transition from the automaton.
	 *
	 * \details The transition is in a form A \times \eps \times \alpha -> B \times \beta, where A, B \in Q and \alpha, \beta \in G*
	 *
	 * \param from the source state (A)
	 * \param pop symbols poped from pushdown store on the transition use (\alpha)
	 * \param to the target state (B)
	 * \param push symbols pushed to the pushdown store on the transition use (\beta)
	 *
	 * \throws AutomatonException when removed transition left hand side was found but the right hand side did not match.
	 *
	 * \returns true if the transition was indeed removed
	 */
	bool removeTransition ( const StateType & from, const ext::vector < PushdownStoreSymbolType > & pop, const StateType & to, const ext::vector < PushdownStoreSymbolType > & push );

	/**
	 * Get the transition function of the automaton in its natural form.
	 *
	 * \returns transition function of the automaton
	 */
	const ext::map < ext::tuple < StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector < PushdownStoreSymbolType > >, ext::pair < StateType, ext::vector < PushdownStoreSymbolType > > > & getTransitions ( ) const &;

	/**
	 * Get the transition function of the automaton in its natural form.
	 *
	 * \returns transition function of the automaton
	 */
	ext::map < ext::tuple < StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector < PushdownStoreSymbolType > >, ext::pair < StateType, ext::vector < PushdownStoreSymbolType > > > && getTransitions ( ) &&;

	/**
	 * Get a subset of the transition function of the automaton, with the source state fixed in the transitions natural representation.
	 *
	 * \param from filter the transition function based on this state as a source state
	 *
	 * \returns a subset of the transition function of the automaton with the source state fixed
	 */
	ext::map < ext::tuple < StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector < PushdownStoreSymbolType > >, ext::pair < StateType, ext::vector < PushdownStoreSymbolType > > > getTransitionsFromState ( const StateType & from ) const;

	/**
	 * Get the transition function of the automaton, with the target state fixed in the transitions natural representation.
	 *
	 * \param to filter the transition function based on this state as a source state
	 *
	 * \returns a subset of the transition function of the automaton with the target state fixed
	 */
	ext::map < ext::tuple < StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector < PushdownStoreSymbolType > >, ext::pair < StateType, ext::vector < PushdownStoreSymbolType > > > getTransitionsToState ( const StateType & to ) const;

	/**
	 * The actual compare method
	 *
	 * \param other the other instance
	 *
	 * \returns the actual relation between two by type same automata instances
	 */
	int compare ( const DPDA & other ) const;

	/**
	 * Print this object as raw representation to ostream.
	 *
	 * \param out ostream where to print
	 * \param instance object to print
	 *
	 * \returns modified output stream
	 */
	friend std::ostream & operator << ( std::ostream & out, const DPDA & instance ) {
		return out << "(DPDA "
			   << "states = " << instance.getStates ( )
			   << "inputAlphabet = " << instance.getInputAlphabet ( )
			   << "initialState = " << instance.getInitialState ( )
			   << "finalStates = " << instance.getFinalStates ( )
			   << "pushdownStoreAlphabet = " << instance.getPushdownStoreAlphabet ( )
			   << "initialSymbol = " << instance.getInitialSymbol ( )
			   << "transitions = " << instance.getTransitions ( )
			   << ")";
	}

	/**
	 * Casts this instance to as compact as possible string representation.
	 *
	 * \returns string representation of the object
	 */
	explicit operator std::string ( ) const;
};

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::DPDA ( ext::set < StateType > states, ext::set < InputSymbolType > inputAlphabet, ext::set < PushdownStoreSymbolType > pushdownStoreAlphabet, StateType initialState, PushdownStoreSymbolType initialSymbol, ext::set < StateType > finalStates ) : core::Components < DPDA, ext::set < InputSymbolType >, component::Set, InputAlphabet, ext::set < PushdownStoreSymbolType >, component::Set, PushdownStoreAlphabet, PushdownStoreSymbolType, component::Value, InitialSymbol, ext::set < StateType >, component::Set, std::tuple < States, FinalStates >, StateType, component::Value, InitialState > ( std::move ( inputAlphabet ), std::move ( pushdownStoreAlphabet ), std::move ( initialSymbol ), std::move ( states ), std::move ( finalStates ), std::move ( initialState ) ) {
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::DPDA ( StateType initialState, PushdownStoreSymbolType initialPushdownSymbol) : DPDA ( ext::set < StateType > { initialState }, ext::set < InputSymbolType > { }, ext::set < PushdownStoreSymbolType > { initialPushdownSymbol }, initialState, initialPushdownSymbol, ext::set < StateType > { }) {
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
bool DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::addTransition(StateType from, common::symbol_or_epsilon < InputSymbolType > input, ext::vector < PushdownStoreSymbolType > pop, StateType to, ext::vector < PushdownStoreSymbolType > push) {
	if (! getStates().count(from)) {
		throw AutomatonException("State \"" + ext::to_string ( from ) + "\" doesn't exist.");
	}

	if (! input.is_epsilon ( ) && ! getInputAlphabet().count ( input.getSymbol ( ) ) ) {
		throw AutomatonException("Input symbol \"" + ext::to_string ( input ) + "\" doesn't exist.");
	}

	if (! getStates().count(to)) {
		throw AutomatonException("State \"" + ext::to_string ( to ) + "\" doesn't exist.");
	}

	for(const PushdownStoreSymbolType & popSymbol : pop) {
		if (! getPushdownStoreAlphabet().count(popSymbol)) {
			throw AutomatonException("Pushdown store symbol \"" + ext::to_string ( popSymbol ) + "\" doesn't exist.");
		}
	}

	for(const PushdownStoreSymbolType & pushSymbol : push) {
		if (! getPushdownStoreAlphabet().count(pushSymbol)) {
			throw AutomatonException("Pushdown store symbol \"" + ext::to_string ( pushSymbol ) + "\" doesn't exist.");
		}
	}

	ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> > key(std::move(from), std::move(input), std::move(pop));
	ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > value = ext::make_pair(std::move(to), std::move(push));

	if (transitions.find(key) != transitions.end()) {
		if(transitions.find(key)->second == value)
			return false;
		else
			throw AutomatonException ( "Transition (\"" + ext::to_string ( std::get<0>(key) ) + "\", \"" + ext::to_string ( std::get<1>(key) ) + "\", \"pop\") -> ?? already exists.");
	}

	if(std::get<1>(key).is_epsilon()) {
		if(std::any_of(transitions.begin(), transitions.end(), [&](const std::pair<const ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > > & transition) {
				if(std::get<0>(transition.first) == std::get<0>(key)) {
					const ext::vector<PushdownStoreSymbolType>& alpha = std::get<2>(transition.first);
					const ext::vector<PushdownStoreSymbolType>& beta = std::get<2>(key);

					const ext::vector<PushdownStoreSymbolType>& shorter = (alpha.size() < beta.size()) ? alpha : beta;
					const ext::vector<PushdownStoreSymbolType>& longer = (alpha.size() < beta.size()) ? beta : alpha;

					for(auto itS = shorter.begin(), itL = longer.begin(); itS != shorter.end(); ++itS, ++itL) {
						if(*itS != *itL) return false;
					}
					return true;
				}
				return false;
			}))
				throw AutomatonException("Conflicting transition");
	} else {
		if(std::any_of(transitions.begin(), transitions.end(), [&](const std::pair<const ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > > & transition) {
				if(std::get<0>(transition.first) == std::get<0>(key) && ( std::get<1>(transition.first) == std::get<1>(key) || std::get<1>(transition.first).is_epsilon() )) {
					const ext::vector<PushdownStoreSymbolType>& alpha = std::get<2>(transition.first);
					const ext::vector<PushdownStoreSymbolType>& beta = std::get<2>(key);

					const ext::vector<PushdownStoreSymbolType>& shorter = (alpha.size() < beta.size()) ? alpha : beta;
					const ext::vector<PushdownStoreSymbolType>& longer = (alpha.size() < beta.size()) ? beta : alpha;

					for(auto itS = shorter.begin(), itL = longer.begin(); itS != shorter.end(); ++itS, ++itL) {
						if(*itS != *itL) return false;
					}
					return true;
				}
				return false;
			}))
				throw AutomatonException("Conflicting transition");
	}

	transitions.insert ( std::move(key), std::move(value) );
	return true;
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
bool DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::addTransition(StateType from, InputSymbolType input, ext::vector < PushdownStoreSymbolType > pop, StateType to, ext::vector < PushdownStoreSymbolType > push) {
	common::symbol_or_epsilon < InputSymbolType > inputVariant(std::move(input));
	return addTransition(std::move(from), std::move(inputVariant), std::move(pop), std::move(to), std::move(push));
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
bool DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::addTransition(StateType from, ext::vector < PushdownStoreSymbolType > pop, StateType to, ext::vector < PushdownStoreSymbolType > push) {
	auto inputVariant = common::symbol_or_epsilon < InputSymbolType > ( );
	return addTransition(std::move(from), std::move(inputVariant), std::move(pop), std::move(to), std::move(push));
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
bool DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::removeTransition(const StateType& from, const common::symbol_or_epsilon < InputSymbolType >& input, const ext::vector < PushdownStoreSymbolType > & pop, const StateType& to, const ext::vector < PushdownStoreSymbolType > & push) {
	ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector < PushdownStoreSymbolType > > key(from, input, pop);
	ext::pair<StateType, ext::vector < PushdownStoreSymbolType > > value = ext::make_pair(to, push);

	if (transitions.find(key) == transitions.end())
		return false;

	if(transitions.find(key)->second != value)
		throw AutomatonException( "Transition (\"" + ext::to_string ( from ) + "\", \"" + ext::to_string ( input ) + "\") -> \"to\" doesn't exist.");

	transitions.erase(key);
	return true;
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
bool DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::removeTransition(const StateType& from, const InputSymbolType& input, const ext::vector < PushdownStoreSymbolType > & pop, const StateType& to, const ext::vector < PushdownStoreSymbolType > & push) {
	common::symbol_or_epsilon < InputSymbolType > inputVariant(input);
	return removeTransition(from, inputVariant, pop, to, push);
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
bool DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::removeTransition(const StateType& from, const ext::vector < PushdownStoreSymbolType > & pop, const StateType& to, const ext::vector < PushdownStoreSymbolType > & push) {
	auto inputVariant = common::symbol_or_epsilon < InputSymbolType > ( );
	return removeTransition(from, inputVariant, pop, to, push);
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
const ext::map<ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > > & DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::getTransitions ( ) const & {
	return transitions;
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
ext::map<ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > > && DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::getTransitions ( ) && {
	return std::move ( transitions );
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
ext::map<ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > > DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::getTransitionsFromState(const StateType& from) const {
	if( ! getStates().count(from) )
		throw AutomatonException("State \"" + ext::to_string ( from ) + "\" doesn't exist");

	ext::map<ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > > transitionsFromState;
	for ( const std::pair<const ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > >& transition : transitions) {
		if (std::get<0>(transition.first) == from) {
			transitionsFromState.insert ( transition.first, transition.second );
		}
	}

	return transitionsFromState;
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
ext::map<ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > > DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::getTransitionsToState(const StateType& to) const {
	if( ! getStates().count(to))
		throw AutomatonException("State \"" + ext::to_string ( to ) + "\" doesn't exist");

	ext::map<ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > > transitionsToState;
	for ( const std::pair<const ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > >& transition : transitions) {
		if (transition.second.first == to) {
			transitionsToState.insert ( transition.first, transition.second );
		}
	}

	return transitionsToState;
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
int DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::compare(const DPDA& other) const {
	auto first = ext::tie(getStates(), getInputAlphabet(), getInitialState(), getFinalStates(), getPushdownStoreAlphabet(), getInitialSymbol(), transitions);
	auto second = ext::tie(other.getStates(), other.getInputAlphabet(), other.getInitialState(), other.getFinalStates(), other.getPushdownStoreAlphabet(), other.getInitialSymbol(), other.transitions);

	static ext::compare<decltype(first)> comp;
	return comp(first, second);
}

template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >::operator std::string ( ) const {
	std::stringstream ss;
	ss << *this;
	return ss.str();
}

} /* namespace automaton */

namespace core {

/**
 * Helper class specifying constraints for the automaton's internal input alphabet component.
 *
 * \tparam InputSymbolType used for the terminal alphabet of the automaton.
 * \tparam PushdownSymbolType used for the pushdown store alphabet of the automaton.
 * \tparam StateType used for the terminal alphabet of the automaton.
 */
template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
class SetConstraint< automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >, InputSymbolType, automaton::InputAlphabet > {
public:
	/**
	 * Returns true if the symbol is still used in some transition of the automaton.
	 *
	 * \param automaton the tested automaton
	 * \param symbol the tested symbol
	 *
	 * \returns true if the symbol is used, false othervise
	 */
	static bool used ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > & automaton, const InputSymbolType & symbol ) {
		for ( const std::pair<const ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > >& transition : automaton.getTransitions())
			if ( ! std::get<1>(transition.first).is_epsilon() && symbol == std::get<1>(transition.first).getSymbol())
				return true;

		return false;
	}

	/**
	 * Returns true as all symbols are possibly available to be elements of the input alphabet.
	 *
	 * \param automaton the tested automaton
	 * \param symbol the tested symbol
	 *
	 * \returns true
	 */
	static bool available ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > &, const InputSymbolType & ) {
		return true;
	}

	/**
	 * All symbols are valid as input symbols.
	 *
	 * \param automaton the tested automaton
	 * \param symbol the tested symbol
	 */
	static void valid ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > &, const InputSymbolType & ) {
	}
};

/**
 * Helper class specifying constraints for the automaton's internal pushdown store alphabet component.
 *
 * \tparam InputSymbolType used for the terminal alphabet of the automaton.
 * \tparam PushdownSymbolType used for the pushdown store alphabet of the automaton.
 * \tparam StateType used for the terminal alphabet of the automaton.
 */
template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
class SetConstraint< automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >, PushdownStoreSymbolType, automaton::PushdownStoreAlphabet > {
public:
	/**
	 * Returns true if the symbol is still used in some transition of the automaton.
	 *
	 * \param automaton the tested automaton
	 * \param symbol the tested symbol
	 *
	 * \returns true if the symbol is used, false othervise
	 */
	static bool used ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > & automaton, const PushdownStoreSymbolType & symbol ) {
		if(automaton.getInitialSymbol() == symbol)
			return true;

		for ( const std::pair<const ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > >& transition : automaton.getTransitions()) {
			const auto & popSymbols = std::get<2>(transition.first);
			const auto & pushSymbols = transition.second.second;
			if(ext::contains(popSymbols.begin(), popSymbols.end(), symbol ) || ext::contains(pushSymbols.begin(), pushSymbols.end(), symbol))
				return true;
		}

		return false;
	}

	/**
	 * Returns true as all symbols are possibly available to be elements of the pushdown store alphabet.
	 *
	 * \param automaton the tested automaton
	 * \param symbol the tested symbol
	 *
	 * \returns true
	 */
	static bool available ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > &, const PushdownStoreSymbolType & ) {
		return true;
	}

	/**
	 * All symbols are valid as pushdown store symbols.
	 *
	 * \param automaton the tested automaton
	 * \param symbol the tested symbol
	 */
	static void valid ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > &, const PushdownStoreSymbolType & ) {
	}
};

/**
 * Helper class specifying constraints for the automaton's internal pushdown store initial element.
 *
 * \tparam InputSymbolType used for the terminal alphabet of the automaton.
 * \tparam PushdownSymbolType used for the pushdown store alphabet of the automaton.
 * \tparam StateType used for the terminal alphabet of the automaton.
 */
template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
class ElementConstraint< automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >, PushdownStoreSymbolType, automaton::InitialSymbol > {
public:
	/**
	 * Determines whether the initial pushdown store symbol is available in the automaton's pushdown store alphabet.
	 *
	 * \param automaton the tested automaton
	 * \param symbol the tested symbol
	 *
	 * \returns true if the pushdown store symbol is already in the pushdown store alphabet of the automaton
	 */
	static bool available ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > & automaton, const PushdownStoreSymbolType & symbol ) {
		return automaton.template accessComponent < automaton::PushdownStoreAlphabet > ( ).get ( ).count ( symbol );
	}

	/**
	 * All pushdown store symbols are valid as an initial pusdown store symbol of the automaton.
	 *
	 * \param automaton the tested automaton
	 * \param symbol the tested symbol
	 */
	static void valid ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > &, const PushdownStoreSymbolType & ) {
	}
};

/**
 * Helper class specifying constraints for the automaton's internal states component.
 *
 * \tparam InputSymbolType used for the terminal alphabet of the automaton.
 * \tparam PushdownSymbolType used for the pushdown store alphabet of the automaton.
 * \tparam StateType used for the terminal alphabet of the automaton.
 */
template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
class SetConstraint< automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >, StateType, automaton::States > {
public:
	/**
	 * Returns true if the state is still used in some transition of the automaton.
	 *
	 * \param automaton the tested automaton
	 * \param state the tested state
	 *
	 * \returns true if the state is used, false othervise
	 */
	static bool used ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > & automaton, const StateType & state ) {
		if ( automaton.getInitialState ( ) == state )
			return true;

		if ( automaton.getFinalStates ( ).count ( state ) )
			return true;

		for ( const std::pair<const ext::tuple<StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector<PushdownStoreSymbolType> >, ext::pair<StateType, ext::vector<PushdownStoreSymbolType> > >& transition : automaton.getTransitions())
			if ( state == std::get<0>(transition.first) || transition.second.first == state )
				return true;

		return false;
	}

	/**
	 * Returns true as all states are possibly available to be elements of the states.
	 *
	 * \param automaton the tested automaton
	 * \param state the tested state
	 *
	 * \returns true
	 */
	static bool available ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > &, const StateType & ) {
		return true;
	}

	/**
	 * All states are valid as a state of the automaton.
	 *
	 * \param automaton the tested automaton
	 * \param state the tested state
	 */
	static void valid ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > &, const StateType & ) {
	}
};

/**
 * Helper class specifying constraints for the automaton's internal final states component.
 *
 * \tparam InputSymbolType used for the terminal alphabet of the automaton.
 * \tparam PushdownSymbolType used for the pushdown store alphabet of the automaton.
 * \tparam StateType used for the terminal alphabet of the automaton.
 */
template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
class SetConstraint< automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >, StateType, automaton::FinalStates > {
public:
	/**
	 * Returns false. Final state is only a mark that the automaton itself does require further.
	 *
	 * \param automaton the tested automaton
	 * \param state the tested state
	 *
	 * \returns false
	 */
	static bool used ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > &, const StateType & ) {
		return false;
	}

	/**
	 * Determines whether the state is available in the automaton's states set.
	 *
	 * \param automaton the tested automaton
	 * \param state the tested state
	 *
	 * \returns true if the state is already in the set of states of the automaton
	 */
	static bool available ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > & automaton, const StateType & state ) {
		return automaton.template accessComponent < automaton::States > ( ).get ( ).count ( state );
	}

	/**
	 * All states are valid as a final state of the automaton.
	 *
	 * \param automaton the tested automaton
	 * \param state the tested state
	 */
	static void valid ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > &, const StateType & ) {
	}
};

/**
 * Helper class specifying constraints for the automaton's internal initial state element.
 *
 * \tparam InputSymbolType used for the terminal alphabet of the automaton.
 * \tparam PushdownSymbolType used for the pushdown store alphabet of the automaton.
 * \tparam StateType used for the terminal alphabet of the automaton.
 */
template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
class ElementConstraint< automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType >, StateType, automaton::InitialState > {
public:
	/**
	 * Determines whether the state is available in the automaton's states set.
	 *
	 * \param automaton the tested automaton
	 * \param state the tested state
	 *
	 * \returns true if the state is already in the set of states of the automaton
	 */
	static bool available ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > & automaton, const StateType & state ) {
		return automaton.template accessComponent < automaton::States > ( ).get ( ).count ( state );
	}

	/**
	 * All states are valid as an initial state of the automaton.
	 *
	 * \param automaton the tested automaton
	 * \param state the tested state
	 */
	static void valid ( const automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > &, const StateType & ) {
	}
};

/**
 * Helper for normalisation of types specified by templates used as internal datatypes of symbols and states.
 *
 * \returns new instance of the automaton with default template parameters or unmodified instance if the template parameters were already the default ones
 */
template < class InputSymbolType, class PushdownStoreSymbolType, class StateType >
struct normalize < automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > > {
	static automaton::DPDA < > eval ( automaton::DPDA < InputSymbolType, PushdownStoreSymbolType, StateType > && value ) {
		ext::set < DefaultSymbolType > alphabet = alphabet::SymbolNormalize::normalizeAlphabet ( std::move ( value ).getInputAlphabet ( ) );
		ext::set < DefaultSymbolType > pushdownAlphabet = alphabet::SymbolNormalize::normalizeAlphabet ( std::move ( value ).getPushdownStoreAlphabet ( ) );
		DefaultSymbolType initialSymbol = alphabet::SymbolNormalize::normalizeSymbol ( std::move ( value ).getInitialSymbol ( ) );
		ext::set < DefaultStateType > states = automaton::AutomatonNormalize::normalizeStates ( std::move ( value ).getStates ( ) );
		DefaultStateType initialState = automaton::AutomatonNormalize::normalizeState ( std::move ( value ).getInitialState ( ) );
		ext::set < DefaultStateType > finalStates = automaton::AutomatonNormalize::normalizeStates ( std::move ( value ).getFinalStates ( ) );

		automaton::DPDA < > res ( std::move ( states ), std::move ( alphabet ), std::move ( pushdownAlphabet ), std::move ( initialState ), std::move ( initialSymbol ), std::move ( finalStates ) );

		for ( std::pair < ext::tuple < StateType, common::symbol_or_epsilon < InputSymbolType >, ext::vector < PushdownStoreSymbolType > >, ext::pair < StateType, ext::vector < PushdownStoreSymbolType > > > && transition : ext::make_mover ( std::move ( value ).getTransitions ( ) ) ) {
			ext::vector < DefaultSymbolType > pop = alphabet::SymbolNormalize::normalizeSymbols ( std::move ( std::get < 2 > ( transition.first ) ) );
			DefaultStateType from = automaton::AutomatonNormalize::normalizeState ( std::move ( std::get < 0 > ( transition.first ) ) );
			common::symbol_or_epsilon < DefaultSymbolType > input = automaton::AutomatonNormalize::normalizeSymbolEpsilon ( std::move ( std::get < 1 > ( transition.first ) ) );

			DefaultStateType to = automaton::AutomatonNormalize::normalizeState ( std::move ( transition.second.first ) );
			ext::vector < DefaultSymbolType > push = alphabet::SymbolNormalize::normalizeSymbols ( std::move ( transition.second.second ) );

			res.addTransition ( std::move ( from ), std::move ( input ), std::move ( pop ), std::move ( to ), std::move ( push ) );
		}

		return res;
	}
};

} /* namespace core */

extern template class automaton::DPDA < >;

#endif /* DPDA_H_ */
