/*
 * File:	getline.c
 *
 * Author:	Ulli Horlacher (framstag@rus.uni-stuttgart.de)
 *
 * History:	
 * 
 *   1997-06-23	   Framstag       initial version
 *   1997-06-24	   Framstag       better handling of EOF
 *   1997-09-23	   Framstag       fixed idiotic prompting bug 
 *   1997-12-14	   Framstag       renamed getline() to getpromptline()
 *
 * Reads a single line of text from stdin.
 *
 * Copyright © 1997 Ulli Horlacher
 * This file is covered by the GNU General Public License
 */

#include <stdio.h>

#include "config.h"
#include "string.h"
#include "getline.h"

#if defined(SOLARIS2) || defined(LINUX)
  #ifndef fileno
    int fileno(FILE *);
  #endif
#endif

#ifdef HAVE_LIBREADLINE

  #include <unistd.h>
  #include <stdlib.h>

  char *readline(const char *);

  /*
   * getpromptline  - get one line of text from stdin
   * 
   * INPUT:  line  - prompt
   * 
   * OUTPUT: line  - input text line
   * 
   * RETURN: input text line
   */
  char *getpromptline(char *line, int len) {
    char *cp;

    /* is stdin a tty? */
    if (isatty(fileno(stdin))) {
      
      cp=readline(line);
  
      if (!cp || strlen(cp) > len) {
	if (cp) free(cp);
	*line=0;
	return(NULL);
      }
  
      strcpy(line,cp);
      free(cp);
      return(line);
      
    } else /* no tty */
      return(sfgetl(line,len,stdin));
      
  }

#else

  char *getpromptline(char *line, int len) {
    printf("%s",line);
    return(sfgetl(line,len,stdin));
  }

#endif
