#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include "myc_str.h"
#include "myc_fortran.h"

static char *last_line = NULL;

char *readline (char *prompt);
void add_history(const char *line);

void F_FUN(sys_rd_line)(F_CHAR(cmd), int *retlen, F_CHAR(prompt) F_CLEN(cmd) F_CLEN(prompt))
{
  char *line_read;
  char p0[64], p[64];

  STR_TO_C(p0, prompt);
  str_copy(p, "\n");
  str_append(p, p0);
  if (strlen(p0) < F_LEN(prompt)) {
    str_append(p, " ");
  }
  if (last_line == NULL) { last_line =malloc(1); last_line[0] = '\0';};

  line_read = readline(p);

  if (line_read)
  {  
    if (*line_read && strcmp(last_line, line_read)!=0)
      add_history (line_read);
    free (last_line);
    STR_TO_F(cmd, line_read);
    *retlen=strlen(line_read);
    last_line = line_read;
    if (*retlen>F_LEN(cmd)) *retlen=F_LEN(cmd);
  } else {
    *retlen=-1;
  }
}
