#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<getopt.h>
#include"context.h"
#include"movement_parser.h"
#include"oracle_parser.h"
#include"feat_fct.h"
#include"config2feat_vec.h"
#include"feature_table.h"
#include"dico.h"

void simple_decoder_buffer_forrest(context *ctx, FILE *f, feature_table *ft, int root_label)
{
  int mvt_code;
  int mvt_type;
  int mvt_label;
  float max;
  feat_vec *fv = feat_vec_new(feature_types_nb);
  config *c = config_initial(f, ctx->mcd_struct, 0);
  
  /* read a sentence and put it in the buffer */
  while(queue_read_sentence(c->bf, f, ctx->mcd_struct)){
    while(!config_is_terminal(c)){
      /* config2feat_vec_cff(ctx->features_model, c, ctx->d_perceptron_features, fv, LOOKUP_MODE); */
      config2feat_vec_fann(ctx->features_model, c, fv, LOOKUP_MODE);

      /* FORREST : this is where the DNN should be called */
      /* fv is the feature vector that contains the values of the features extracted from configuration c */
      /* the function returns the code of a movement (mvt_code), that is used to yield a new configuration */
      mvt_code = feature_table_argmax(fv, ft, &max);


      mvt_type = movement_type(mvt_code);
      mvt_label = movement_label(mvt_code);

      if(mvt_type == MVT_LEFT)
	if(movement_left_arc(c, mvt_label, max))
	  continue;
      
      if(mvt_type == MVT_RIGHT)
	if(movement_right_arc(c, mvt_label, max))
	  continue;
      
      movement_shift(c, 0, max);
    }

    /* config_print(stdout, c);    */
    
    config_connect_subtrees(c, root_label); 
    depset_print2(stdout, c->ds, ctx->dico_labels);
    
    /* config_free(c);  */
    c = config_initial(f, ctx->mcd_struct, 0);
  }

  feat_vec_free(fv);
}


void simple_decoder_forrest(context *ctx)
{
  FILE *f = (ctx->input_filename)? myfopen(ctx->input_filename, "r") : stdin;
  /* feature_table *ft = feature_table_load(ctx->perc_model_filename, ctx->verbose); */
  feature_table *ft = NULL;
  int root_label;

  root_label = dico_string2int(ctx->dico_labels, ctx->root_label);
  if(root_label == -1) root_label = 0;

  simple_decoder_buffer_forrest(ctx, f, ft, root_label);

  feature_table_free(ft);
  if(ctx->input_filename)
    fclose(f);

}