#include </lib/ascii.h>

/* Convert WordStar files to Mate. Removes hard returns. */

char ibuff[2000];
char obuff[2000];
int ifile,ofile,in,on;

char lastc;		/* last character output to the file */
main(argc,argv)
int argc;
char *argv[];
{

int i,state;
char name[80],c;

	allmem();
	fastfile(2);

	printf("WordStar to Pmate Converter\r\n");
	if (argc < 2) {
		printf("What file?\r\n");
		exit(1);
	}

	cpyarg(name,argv[1]);
	ifile= open(name,0);
	if (ifile == -1) {
		printf("Cannot find %s\r\n",name);
		exit(2);
	}
	ofile= creat("wspm.$$$",1);
	if (ofile == -1) {
		printf("Cannot create work file wspm.$$$\r\n");
		exit(2);
	}

	state= 0;
	on= 0;
	lastc= -1;

	while (in= read(ifile,ibuff,sizeof(ibuff))) {
		for (i= 0; i < in; i++) {
			c= ibuff[i];

/* Processing for characters with the high bit set. */

			if (c >= 127) switch(c) {

/* rare */			case DEL:
/* softCR: delete */		case CR + 128: 
/* WS soft space */		case 224: c= '\0'; break;

				default: c &= 0x7f;
					if (c < ' ') c= '\0';
					break;

/* Filter out all control characters except "universal" ones. */

			} else if (c < ' ') switch (c) {
				case FF: break;
				case CR: break;
				case TAB: break;
				default: c= '\0'; break;
			}

/* If the character is null, ignore it. */

			if (! c) continue;

/* Convert runs of spaces to single spaces. */

			if ((c == ' ') && (lastc == ' ')) continue;

/* Look for CR, CR sequences and preserve them; remove single CRs, or convert
to a single space if the preceeding character is not a space. */

			switch (state) {

/* Look for the first CR. */

			case 0: if (c == CR) state= 1; 
				else {
					putc(c);
					lastc= c;
				}
				break;

/* Last character was a CR */

			case 1: if (c == CR) {
					putc(CR);	/* two in a row */
					putc(LF);	/* write them out */
					putc(CR);	/* two in a row */
					putc(LF);	/* write them out */

				} else {
					if (lastc != ' ') putc(' '); 
					putc(c);
				}
				lastc= c;
				state= 0;
				break;
			}
		}
	}

	close(ifile);
	putc(SUB);
	oflush();
	close(ofile);
	delete("wspm.bak");
	rename(name,"wspm.bak");
	rename("wspm.$$$",name);
	exit(0);
}

/* Put a character into the buffer; if its full, flush to disk. */

putc(c)
char c;
{
	if (on >= sizeof(obuff)) oflush();
	obuff[on++]= c;
}
/* Flush the output buffer. */

oflush() {

	if (write(ofile,obuff,on) != on) {
		printf("Disk full!\r\n");
		close(ofile);
		close(ifile);
		exit(1);
	}
	on= 0;
}

