// file: $isip/doc/examples/class/dstr/dstr_example_04/example.cc
// version: $Id: example.cc 6023 2000-12-20 04:06:28Z duncan $
//

// isip include files
//
#include <DiGraph.h>

boolean printPaths(DiGraph<String>& grammar_a, GraphVertex<String>* src_a,
		   String& output) {

  // concatenate the word contained in the current node onto the end
  // of the output string.
  //
  output.concat(*src_a->getItem());

  // if this is the terminal node, print the string and return
  //
  if (src_a == grammar_a.getTerm()) {
    output.concat(L".");
    Console::put(output);
    return true;
  }
  
  // loop over all nodes starting from this node
  //
  for (boolean more = src_a->gotoFirst(); more; more = src_a->gotoNext()) {

    // src_a is a GraphVertex*
    // src_a->getCurr() is a GraphArc*
    // src_a->getCurr()->getVertex() is the target vertex of the arc
    //
    GraphVertex<String>* dest = src_a->getCurr()->getVertex();

    // if this is not an epsilon transition, add a space to the output
    // to delimit the words.
    //
    String new_output(output);
    if (!src_a->getCurr()->getEpsilon()) {
      new_output.concat(L" ");
    }
    
    // recursively call printPaths with the new node
    //
    printPaths(grammar_a, dest, new_output);
  }

  // exit gracefully
  //
  return true;
}

// main program starts here:
//
int main () {

  // we will read the grammar from this file
  //
  String file(L"graph_grammar.sof");
  
  // create a DiGraph of our simple grammar
  //
  DiGraph<String> grammar;

  // read the DiGraph from a text Sof file
  //
  Sof text_file;
  text_file.open(file);
  if (!grammar.read(text_file, 0)) {
    return Error::handle(Sof::name(), L"read", Error::READ, __FILE__,
			 __LINE__);
  }
  text_file.close();

  // print out all the paths in the grammar with our recursive
  // function.
  //
  String output;
  printPaths(grammar, grammar.getStart(), output);
  
  // exit gracefully
  //
  Integral::exit();
}
