/* WS.C		a WordStar-like editor 				31 Oct 1987 */

#include <ws.h>					/* Constants		*/
#include <wg.h>					/* External variables	*/
#include <stdio.h>


main(argc, argv)
int argc;	
char *argv[];	
{
	extern INDEX	t_begin, t_end;		/* text begin, end	*/
	extern INDEX	t_max;			/* max. text index	*/
	extern char	*t_name;		/* text name		*/

	INDEX	alloc();			/* memory allocation	*/
	FLAG	load_text();			/* load text from disk	*/
	FLAG	edit_text();			/* edit text in memory	*/
	FLAG	save_text();			/* save text to disk	*/

	if (argc != 2) {
		printf("Usage: WS filename\n");
		exit(-1);
	}
	if ((t_begin = alloc(MAX_TEXT)) == NULL) {
		printf("Not enough memory\n");
		exit(1);
	}
	t_name = argv[1];
	t_max = t_begin + MAX_TEXT - 1;
	if (load_text() && edit_text() && save_text()) exit(0);
	exit(1);
}


FLAG load_text()	/* loads text file (if exists) into memory	*/
			/* returns FALSE iff buffer full 		*/
{
	extern char	*t_name;	/* name of text file		*/
	extern INDEX	t_max;		/* max. text index		*/
	extern INDEX	t_begin, t_end;	/* text begin, end		*/

	void		pmpt_ack();	/* prompt for acknowledge	*/

	INDEX	tp;			/* current text end		*/
	FILE	*fp;			/* input file pointer		*/
	int	c;			/* input character from file	*/

	t_end = t_begin;
	if (fp = fopen(t_name, "r")) {
		printf("Loading %s", t_name);
		for (; (c = getc(fp)) != EOF; t_end++) { 
			*t_end = ((c=='\n') ? '\0' : c);   /* replace CRs */
			if (t_end>=t_max) {
				pmpt_ack("Text buffer full");
				break;
			}
		}
		fclose(fp);
	}
	else
		printf("New file %s\n", t_name);
	*t_end = '\0';				/* append closing newline */
	return (t_end<t_max);
}


FLAG save_text()		/* saves text to disk			*/
				/* returns FALSE iff text can't be saved */
{
	extern char	*t_name;		/* name of text file	*/
	extern INDEX	t_begin, t_end;		/* text begin, end	*/
	extern unsigned	n_lines;		/* no of text lines	*/

	INDEX	p;				/* text pointer		*/
	FILE	*fp;				/* text file pointer	*/
	char	c;				/* output char		*/

/* 
	Rename input file fname to .BAK 
*/

	if ((fp = fopen(t_name,"w")) == NULL) {
		printf("Cannot open output file %s\n", t_name);
		return FALSE;
	}
	if (*(t_end-1)) {
		t_end++;			/* include missing newline */
		n_lines++;
	}
	printf("%s   %d lines, %d characters", t_name,n_lines,t_end-t_begin);
	for (p=t_begin; p<t_end; p++) {
		c = (*p=='\0') ? '\n' : *p;
		if (putc(c,fp) == EOF) {
			printf(" - Error writing file %s\n", t_name);
			fclose(fp);
			return FALSE;
		}
	}
	fclose(fp);
	printf("\n");
	return TRUE;
}
