/*
 * AutomatonIteration.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: 29. 11. 2014
 *	  Author: Tomas Pecka
 */

#pragma once

#include <automaton/FSM/EpsilonNFA.h>

namespace automaton {

namespace transform {

/**
 * Iteration of a finite automaton.
 * For finite automaton A1, we create automaton A such that L(A) = L(A1)*
 * This method utilizes epsilon transitions in finite automata (Melichar: Jazyky a překlady, 2.82).
 */
class AutomatonIteration {
public:
	/**
	 * Iteration of a finite automaton.
	 * @tparam SymbolType Type for input symbols.
	 * @tparam StateType Type for states.
	 * @param automaton automaton to iterate
	 * @return nondeterministic FA accepting the iteration of language that @p automaton accepted" );
	 */
	template < class Automaton >
	static ext::require < isDFA < Automaton > || isNFA < Automaton >, automaton::NFA < typename Automaton::SymbolType, typename Automaton::StateType > > iteration ( const Automaton & automaton );
};

template < class Automaton >
ext::require < isDFA < Automaton > || isNFA < Automaton >, automaton::NFA < typename Automaton::SymbolType, typename Automaton::StateType > > AutomatonIteration::iteration ( const Automaton & automaton ) {
	automaton::NFA < typename Automaton::SymbolType, typename Automaton::StateType > res(automaton);

	typename Automaton::StateType newInitialState = common::createUnique(automaton.getInitialState(), automaton.getStates());
	res.addState(newInitialState);

	for(const auto& t : automaton.getTransitionsFromState(automaton.getInitialState())) {
		res.addTransition(newInitialState, t.first.second, t.second);
		if (automaton.getFinalStates().contains(t.second)) {
			res.addTransition(newInitialState, t.first.second, automaton.getInitialState());
		}
	}

	for(const auto& qf : res.getFinalStates())
		for(const auto& t : res.getTransitionsToState(qf))
			res.addTransition(t.first.first, t.first.second, res.getInitialState());

	res.setInitialState(newInitialState);
	res.addFinalState(newInitialState);

	return res;
}

} /* namespace transform */

} /* namespace automaton */

