/* This file is part of Lcrzo.
*/

int lcrzo_stdin_char(const char *message,
		     const lcrzo_uint8 caracautorises[],
		     lcrzo_uint8 caracdefaut, lcrzo_uint8 *pcarac)
{ char prompt;
  lcrzo_uint8 carac;
  lcrzo_int16 language;
#if defined LCRZODEF_SYSTEM_Unix
  struct termios old_termios, new_termios;
#elif defined LCRZODEF_SYSTEM_Windows
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif

  /*parameters verification*/
  if (caracautorises==NULL) return(LCRZO_ERR_PANULLPTR);
  if (!strchr((const char*)caracautorises, caracdefaut)) 
    return(LCRZO_ERR_PADEFAULTNOTINRANGE);

#if defined LCRZODEF_SYSTEM_Unix
  /*change de mode*/
  if (tcgetattr(STDIN_FILENO, &old_termios)) return(LCRZO_ERR_FUTCGETATTR);
  new_termios=old_termios;
  new_termios.c_lflag &= (~ICANON); /*desactive le mode canonique*/
  new_termios.c_cc[VMIN] = 1; /*passe si au moins un caractere*/
  new_termios.c_cc[VTIME] = 0; /*attend indefiniment l'appui*/
  if (tcsetattr(STDIN_FILENO, TCSANOW, &new_termios))
    return(LCRZO_ERR_FUTCSETATTR);
#elif defined LCRZODEF_SYSTEM_Windows
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif

  /* just for the compiler warning */
  carac=0;

  /*boucle pour demander a l'utilisateur*/
  prompt=':';
  lcrzo_er(lcrzo_global_get_language(&language));
  while(LCRZO_TRUE)
  { if (message!=NULL) if (message[0]!='\0') 
    { printf((language==LCRZO_GLOBAL_LANG_FR)?
	     "%s (touche %s)[%c]%c ":"%s (key %s)[%c]%c ", 
	     message, caracautorises, caracdefaut, prompt);
    }
    prompt='>'; /*si erreur, utilise ce prompt*/
    /*saisie du caractere de l'utilisateur*/
  lcrzo_er(lcrzo_stream_flush(stdin));
#if defined LCRZODEF_SYSTEM_Unix
    carac=(lcrzo_uint8)fgetc(stdin);
#elif defined LCRZODEF_SYSTEM_Windows
    carac=(lcrzo_uint8)_getche();
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif
    /*si rien n'a ete entre, on prend le defaut*/
    if ( carac==0x0D || carac==0x0A )
    { carac=caracdefaut;
#if defined LCRZODEF_SYSTEM_Unix
#elif defined LCRZODEF_SYSTEM_Windows
      /* because the newline is suppressed */
      printf("\n");
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif
      break;
    }
    else
    { if (message!=NULL) if (message[0]!='\0') printf("\n");
    }

    /*on verifie que le caractere soit autorise*/
    if (strchr((const lcrzo_int8 *)caracautorises, carac)) break;
  }

#if defined LCRZODEF_SYSTEM_Unix
  /*remet le mode d'origine*/
  if (tcsetattr(STDIN_FILENO, TCSANOW, &old_termios))
    return(LCRZO_ERR_FUTCSETATTR);
#elif defined LCRZODEF_SYSTEM_Windows
  lcrzo_err_purge();
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif

  if (pcarac!=NULL) *pcarac=carac;
  return(LCRZO_ERR_OK);
}


