/*
 * ToGrammarRightRG.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: 9. 2. 2014
 *      Author: Tomas Pecka
 */

#ifndef __TO_GRAMMAR_RIGHT_RG_H__
#define __TO_GRAMMAR_RIGHT_RG_H__

#include <grammar/Regular/RightRG.h>

#include <automaton/FSM/NFA.h>
#include <automaton/FSM/DFA.h>

#include <common/createUnique.hpp>

namespace automaton {

namespace convert {

/**
 * Converts a finite automaton to a right regular grammar (Melichar: Jazyky a překlady 2.104).
 */
class ToGrammarRightRG {
public:
	/**
	 * Performs the conversion of the finite automaton to right regular grammar.
	 *
	 * \tparam T the converted automaton
	 *
	 * \param automaton a finite automaton to convert
	 *
	 * \return right regular grammar equivalent to the source @p automaton.
	 */
	template < class T >
	static ext::require < isDFA < T > || isNFA < T >, grammar::RightRG < typename T::SymbolType, typename T::StateType > > convert ( const T & automaton );
};

template < class T >
ext::require < isDFA < T > || isNFA < T >, grammar::RightRG < typename T::SymbolType, typename T::StateType > > ToGrammarRightRG::convert ( const T & automaton ) {
	using SymbolType = typename T::SymbolType;
	using StateType = typename T::StateType;

	// step 3 - set start symbol of G
	grammar::RightRG < SymbolType, StateType > grammar ( automaton.getInitialState ( ) );

	grammar.setTerminalAlphabet ( automaton.getInputAlphabet ( ) );
	grammar.setNonterminalAlphabet ( automaton.getStates ( ) );

	// step 2 - create set of P in G
	for(const auto& transition : automaton.getTransitions()) {
		const auto & from = transition.first.first;
		const auto & input = transition.first.second;
		const auto & to = transition.second;

		grammar.addRule(from, ext::make_pair(input, to)); // 2a
		if(automaton.getFinalStates().count(to)) // 2b
			grammar.addRule(from, input);
	}

	// step 4
	if ( automaton.getFinalStates ( ).count ( automaton.getInitialState ( ) ) )
		grammar.setGeneratesEpsilon(true); // okay this feature makes the algorithm a bit different but at the same time it simplifies the code :))

	return grammar;
}

} /* namespace convert */

} /* namespace automaton */

#endif /* __TO_GRAMMAR_RIGHT_RG_H__ */
