//
// File        : nfalgo_det.hh
// Date        : Thu Oct 29 17:58:32 MET 1998
// Author      : Vincent Le Maout
// Description : NFA determinisation
//               ASTL 1.1 (g++ 2.8.0)
//

#ifndef ASTL_ALGO_DETERMINIZE
#define ASTL_ALGO_DETERMINIZE

#include <queue>
#include <vector>
#include <set>
#include <map>
#include <inserter.h>
#include <iterator>      // back_inserter
#include <algorithm>        // copy
#include <tag.h>

// template <class NFA, class DFA>
// void determinize(NFA_async<NFA> &nfa, DFA &result)
// {
//   vector<NFA::State> I;
//   I.reserve(16);
//   nfa.epsilon_closure(nfa.initial().begin(), nfa.initial().end(), back_inserter(I));
//   _determinize(nfa, result, I);
// }

// template <class NFA, class DFA>
// void determinize(NFA &nfa, DFA &result)
// {
//   _determinize(nfa, result, nfa.initial());
// }

template <class NFA, class DFA>
void determinize(NFA &nfa, DFA &result)
{
  if (! nfa.initial().empty())
  {
    typedef map<set<typename NFA::State>, typename DFA::State> parts_type; // P(Q) x Q
    typedef typename NFA::Sigma Sigma;
    parts_type parts;
    pair<set<typename NFA::State>, typename DFA::State> qi;  // qi is in P(Q) x Q
    qi.first.insert(nfa.initial().begin(), nfa.initial().end());
    qi.second = result.new_state();
    result.initial(qi.second);
    tag_traits<typename NFA::Tag>::tag_determinize(nfa.initial().begin(), 
						   nfa.initial().end(),
						   result.tag(qi.second));
    
    // A queue of parts::iterator to store path
    queue<parts_type::iterator> path;
    parts_type::iterator where, where_to; 
    path.push(parts.insert(qi).first);    // queue-in the initial state

    // Width-first iteration
    do 
    {
      where = path.front();
      path.pop();

      typename NFA::Sigma::const_iterator letter;
      for (letter = Sigma::begin(); letter != Sigma::end(); ++letter)
      {
	qi.first.clear();
	nfa.delta1((*where).first.begin(), (*where).first.end(), 
		   *letter, associative_inserter(qi.first));
	if (! qi.first.empty())
	{
	  where_to = parts.find(qi.first);
	  if (where_to != parts.end())
	    result.set_trans((*where).second, *letter, (*where_to).second);
	  else
	  {
	    qi.second = result.new_state();
	    tag_traits<typename NFA::Tag>::tag_determinize(qi.first.begin(), 
							   qi.first.end(),
							   result.tag(qi.second));
	    result.final(qi.second) = nfa.final(qi.first.begin(), qi.first.end());
	    result.set_trans((*where).second, *letter, qi.second);
	    path.push(parts.insert(qi).first);
	  }
	}
      }
    } while (!path.empty());
  }
}

#endif // ASTL_NFALGO_DET




