#include "wand_head.h"
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef TOS
#include <keycodes.h>
extern long _stksize = 50000L;
#endif

extern char *playscreen();
extern int rscreen();
extern int savescore();
extern void map();
extern void check_legality();

int debug_disp = 0;
char screen[NOOFROWS][ROWLEN+1];
int edit_mode = 0;
int saved_game = 0;
char *edit_screen = (char *) 0;
char *edit_memory = (char *) 0;
char *memory_end = (char *) 0;
char screen_name[61] ;
int record_file = -1;
long dictsize = 0L;
FILE *dictfp;

int readline(fd, ptr, max)
int fd, max;
char *ptr;
{
    int count = 0;
    while (read(fd,ptr,1) == 1) {
	if (++count == max)
	    break;
	if (*ptr=='\n')
	    break;
	ptr++;
    }
    *ptr = '\0';
    return count;
}

show_credits(opt)
int opt;
{
    int maxlines, linecount;
    FILE *fp;
    char ch, buffer[100];
#ifdef TOS
    long i;	/* index used to approximate half second between scrolls */
#else
    int inp, nul;
    struct timeval tv;
#endif

    sprintf(buffer,"%s/credits",SCREENPATH);
    if ((fp = fopen(buffer,"r")) == NULL) {
	printf("Sorry - credits unavailable!\n");
	exit(1);
    }
    initscr();
    CBON;
    noecho();
    maxlines = tgetnum("li") - 3;
    linecount = 0;
#ifndef TOS
    nul = 0;
    tv.tv_sec = 0;
    tv.tv_usec = 500000L;	/* half second between scrolls */
#endif
    while (fgets(buffer,100,fp)) {
	addstr(buffer);
	if (!opt) {
	    if (++linecount == maxlines) {
		move(maxlines + 2,0);
		addstr("-- More --");
		refresh();
		ch = getch();
		if (ch == 'q') break;
		move(maxlines + 2,0);
		addstr("          ");
		refresh();
		clear();
		linecount = 0;
	    }
	} else {
#ifdef TOS
	    printf("%s",buffer);
	    for (i = 0; i < 110000; i++);
	    if (console_input_status(0)) {	/* if character is available */
		read(0,&ch,1);
		if (ch == 'q') break;
	    }
#else
	    inp = 1;
	    printf("%s",buffer);
	    select(1,&inp,&nul,&nul,&tv);
	    if (inp) {
		read(0,&ch,1);
		if (ch == 'q') break;
	    }
#endif
	}
    }
    CBOFF;
    echo();
    if (!opt) {
	move(maxlines+2,0);
	refresh();
    }
    endwin();
}

extern int optind, opterr;
extern char *optarg;

main(argc, argv)
int  argc;
char **argv;
{
    char (*frow)[ROWLEN+1] = screen;
    long score = 0;
    int fp, num = 1, bell = 0, maxmoves = 0, x, y;
    char howdead[25], buffer[100], *name, *keys, *dead;
    char c, *malloc();
    struct stat *statbuf;

    keys = (char *) 0;
    while ((c = getopt(argc,argv,"01k:et:r:fmCcvs")) != -1)
	switch (c) {
	case '0': bell = 0; break;
	case '1': bell = 1; break;
	case 'k': keys = optarg; break;
	case 'm': erase_scores();
		exit(0);
	case 'c': show_credits(0);
		exit(0);
	case 'C': show_credits(1);
		exit(0);
	case 's': savescore("-",-1L,-1,"-");
		exit(0);
	case 'f': debug_disp = 1; break;
	case 'v': printf("\nWANDERER Copyright (C) 1988 S. Shipway. Version %s.\n\n",VERSION);
		exit (0);
	case 'r':
#ifdef TOS
	    if ((record_file = open(optarg,O_WRONLY | O_CREAT,0600)) < 0) {
#else
	    if ((record_file = open(optarg,O_WRONLY | O_CREAT,0600)) == -1) {
#endif
		printf("Cannot open file %s for recording.\n",optarg);
		exit(-1);
		break;
	    }
	case 'e': edit_mode = 1;
	    memory_end = edit_memory = malloc(EMSIZE * sizeof(char));
	    break;
	case 't': edit_screen = optarg;
	    debug_disp = edit_mode = 1;
	    rscreen(0,&maxmoves);
	    initscr();
	    map(frow);
	    check_legality();
	    move(21,0); refresh();
	    endwin();
	    exit(0);
	default:
	    fprintf(stderr,"Usage: %s [ -e | -m | -C | -c | -s | [ -r file ] [ -f ] | -t file ] [ -0 | -1 ] [ -k keys ] [ file ]\n",argv[0]);
	    exit(1);
	}

    if (optind < argc) edit_screen = argv[optind];

/* bjr@watserv1.waterloo.edu, added the following to fix password searching.
   To properly search the 'words' dictionary, the size of the file
   is needed.  As a result, there are now five conditions (there were
   originally two,) under which passwords will be disabled.
	1. The program was run with flag -e (screen editor)
	2. The file no_pws is present in the screens directory
	3. A stat() call on the dictionary file fails
	4. The dictionary file cannot be opened using fopen()
	5. The dictionary is empty (0 bytes)
   The variable no_passwords has been replaced by dictsize.  If
   dictsize = 0, passwords are disabled. */

    if (!edit_mode) {
	sprintf(buffer,"%s/no_pws",SCREENPATH);
#ifdef TOS
	if ((fp = open(buffer,O_RDONLY)) < 0)	/* if no_pws does not exist */
#else
	if ((fp = open(buffer,O_RDONLY)) = -1)	/* if no_pws does not exist */
#endif
	    if (!stat(DICTIONARY, statbuf))	/* and we can stat dictionary */
		if ((dictfp = fopen(DICTIONARY, "r")) != NULL)	/* and open */
		    dictsize = statbuf->st_size;	/* save size */
	close(fp);
    }

    if ((name = (char *)getenv("NEWNAME")) == NULL)
	if ((name = (char *)getenv("NAME")) == NULL)
	    if ((name = (char *)getenv("FULLNAME")) == NULL)
		if ((name = (char *)getenv("USER")) == NULL)
		    if ((name = (char *)getenv("LOGNAME")) == NULL)
#ifdef	ASKNAME	/* M001 */
		    {
			name = malloc(80L);
			if (name == NULL) {
			    printf("malloc error\n");
			    exit(1);
			}
			printf("Name? "); fflush(stdout);
			gets(name);
			if (name[0] == '\0')
			    name = "noname";
		    }
#else
			name = "noname";
#endif

    if (!keys)
	if ((keys = (char *)getenv("NEWKEYS")) == NULL) {
	    keys = malloc(5);
	    strcpy(keys,"kjhl");
	}

#ifdef TOS
/* bind the cursor keys to the movement keys.  Also, bind */
/* the HELP key to the '?' command. */
    {
    char key[2] = "?";
    key[0] = keys[0]; console_set_key(CURS_UP, key, NULL, NULL);
    key[0] = keys[1]; console_set_key(CURS_DN, key, NULL, NULL);
    key[0] = keys[2]; console_set_key(CURS_LF, key, NULL, NULL);
    key[0] = keys[3]; console_set_key(CURS_RT, key, NULL, NULL);
    console_set_key(K_HELP, "?", NULL, NULL);
    }
#endif

    initscr();

/* MAIN PROGRAM HERE */

    CBON; noecho();

    if (!edit_mode) {
	for (;;) {
	    if (rscreen(num,&maxmoves)) {
		strcpy(howdead,"a non-existant screen");
		break;
	    }
	    dead = playscreen(&num,&score,&bell,maxmoves,keys);
	    if ((dead != NULL) && (*dead == '~')) {
		num = (int)(dead[1]) - 1;
		dead = NULL;
	    }
	    if (dead != NULL) {
		strcpy(howdead,dead);
		break;
	    }
	    num++;
	}

	printf("\n\n%s killed by %s with a score of %ld on level %d.\n",name,howdead,score,num);
    } else {
	if (rscreen(num,&maxmoves)) {
	    for (x = 0; x < ROWLEN; x++)
		for (y = 0; y < NOOFROWS; y++)
		    screen[y][x] =  ' ';
	}
	editscreen(num,&score,&bell,maxmoves,keys);
    }
/* END OF MAIN PROGRAM */

/* SAVE ROUTINES FOR SCORES */

    if (!edit_mode) {
	if ((savescore(howdead,score,num,name) == 0) && (score != 0))
	    printf("\nWARNING: %s : score not saved!\n",argv[0]);
    }

    echo();
    CBOFF;
    endwin();
    printf("WANDERER (C) 1988 S. Shipway                                \n");
    if (record_file != -1) close(record_file);
    if (!dictsize) fclose(dictfp);	/* bjr */
#ifdef TOS
    if (!strcmp(argv[0], "")) {		/* probably run from the desktop */
	printf("Press any key to end...");
	c = getch();
    }
#endif	/* TOS */
}
