#include "common.h"
#include <cstring>
#include <cstdlib>
#include <cctype>
#include <vector>

#ifndef _DEBUG_INCLUDE
#define _DEBUG_INCLUDE

namespace debug
{  
  
void split_line ( char *line, std::vector<char*> &exp )
{
//   char* curchar = new char[sizeof ( line ) ];
  char buffer[10000];
  char *curchar = buffer;
  strcpy ( curchar, line );

  while ( 1 )
  {

    /* saute les espaces */
    while ( *curchar && *curchar == ' ' )
      curchar++;

    /* fin de ligne ? */
    if ( *curchar == '\0' || *curchar == '\n' )
      break;

    /* on se souvient du début de ce mot */
    exp.push_back ( curchar );

    /* cherche la fin du mot */
    while ( *curchar && !isspace ( *curchar ) )
    {
      curchar++; /* saute le mot */
    }

    /* termine le mot par un \0 et passe au suivant */
    if ( *curchar )
    {
      *curchar = '\0';
      curchar++;
    }
  }
}

bool ask_binary_question ( char *question )
{
  char answer[1000];
  while ( 1 )
  {
    printf ( "%s : y/n\n", question );
    fflush ( stdout );
    if ( fgets ( answer,sizeof ( answer )-1,stdin ) )
    {
      if ( answer[0] == 'y' )
        return true;
      if ( answer[0] == 'n' )
        return false;
    }
  }
}

int debug_shell ( char *question, int *intarray, double *doublearray )
{
  printf ( "#################################\n" );
  printf ( "### Vorosweep debug MiniShell ###\n" );
  printf ( "###    \"h\" + ENTER for help   ###\n" );
  printf ( "#################################\n" );
  
  char line[4096];

  while ( 1 )
  {
    // affiche invite
    printf ( "%s ? > ", question);
    fflush ( stdout );

    // get the line
    if ( !fgets ( line,sizeof ( line )-1,stdin ) )
    {
      /* ^D ou fin de fichier => on quitte */
      printf ( "\n" );
      break;
    }

    // compute and dump
    std::vector<char*> exp;

    split_line ( line, exp );
    
//     printf("size --> %d\n", (int)exp.size());

    if ( exp.size() )
    {
      if ( !strcmp ( exp[0], "help" ) )
      {
        printf ( "Available commands :\n" );
        printf ( "get int + INTEGER\n" );
        printf ( "get double + DOUBLE\n" );
        printf ( "c(ontinue)\n" );
        printf ( "q(uit)\n" );
      }
      if ( !strcmp ( exp[0], "get" ) && !strcmp ( exp[1], "int" ) )
      {
        intarray[0] = atoi(exp[2]);
        return 1;
      }
      if ( !strcmp ( exp[0], "get" ) && !strcmp ( exp[1], "double" ) )
      {
        doublearray[0] = atof(exp[2]);
        return 1;
      }
      if ( !strcmp ( exp[0], "c" ) )
      {
        return 0;
      }
      if ( !strcmp ( exp[0], "q" ) )
      {
        exit ( 0 );
      }
    }
    else
    {
      return 0;
    }
  }
  return -1;
}

};

#endif