/*
 * i/o and file creation routines.
 */

#include		<stdio.h>
#include		<ctype.h>
#define FALSE	0
#define TRUE	1
#define	EOS	'\0'

extern char	line[];			/* general scratch (input line)	*/
extern double	atof();
extern char	*strchr();

/*
 * Prompt and read (integer/real/complex/string)
 */
getint(prompt, result, def_value, max_value)
char *prompt;
int *result;
int def_value, max_value;
{
	*result = def_value;
	if (isatty(fileno(stdin))) {
		printf("%s (0:%d) <%d>: ", prompt, max_value, def_value);
		fflush(stdout);
	}
	if (gets(line) == NULL)
		return (FALSE);
	if (line[0] != EOS)
		*result = atoi(line);
	if (*result < 0 || *result > max_value) {
		printf("\nvalue %d out of range 0 .. %d, try again", *result,
								max_value);
		return(getint(prompt, result, def_value, max_value));
	}
	return (TRUE);
}

int
getdouble(prompt, result)
char *prompt;
double *result;
{
	if (isatty(fileno(stdin))) {
		printf("%s: ", prompt);
		fflush(stdout);
	}
	if (gets(line) == NULL)
		return (FALSE);
	if (line[0] == EOS) {
		printf("No default permitted, try again\n");
		return(getdouble(prompt, result));
	}
	*result = atof(line);
	return (TRUE);
}

getcomplex(prompt, real, imag)
char *prompt;
double *real, *imag;
{
	register char	*lp;

	if (isatty(fileno(stdin))) {
		printf("%s: ", prompt);
		fflush(stdout);
	}
	if (gets(line) == NULL) {
		return (FALSE);
	} else if (line[0] == EOS) {
		printf("No default permitted, try again\n");
		return(getcomplex(prompt, real, imag));
	} else if ((lp = strchr(line, ',')) == NULL) {
		printf("Need two values, separated by a comma\n");
		return(getcomplex(prompt, real, imag));
	}
	*lp = EOS;
	*real = atof(line);
	*imag = atof(lp + 1);
	return (TRUE);
}

getstring(prompt, result, def_value)
char *prompt;
char *result;
char *def_value;
{
	strcpy(result, def_value);
	if (isatty(fileno(stdin))) {
		printf("%s <%s>: ", prompt, result);
		fflush(stdout);
	}
	if (gets(line) == NULL)
		return (FALSE);
	if (line[0] != EOS)
		strcpy(result, line);
	return (TRUE);
}

/*
 * Create a text file
 */
FILE *
fcreate(fname)
char *fname;
{
	register FILE *fd;

	if ((fd = fopen(fname, "w")) == NULL) {
		perror(fname);
		return (NULL);
	}
	return (fd);
}
