/* ansied.c */    /** NOTE: use COMPACT memory model to compile! **/
/* ANSI screen editor for creating BBS bulletins and menus */

#include <conio.h>
#include <ctype.h>
#include <process.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "iolib.h"
#include "ioedc.h"

#define     TRUE    1
#define     FALSE   0

char    ch,
        blank[]=
  "                                                                          ",
        keyhelp[10][9] = {       /* function key labels: */
			"1Help",
			"2Symbol",
			"3Color",
			"4 UNDO",
			"5SelCol",
			"6SelBox",
			"7MkBox",
			"8UnBox",
			"9HzLin",
			"0VrLin" },
		screen[25][81],
		colormap[25][81],
		infname[81],
		otfname[81],
        line[101],
		temp[101];

int     x,y,
        i,j,o,
        p,q,z,n,r,
		lines,
		defaultattrib,
        video;

FILE    *infile, *otfile;

void funkey_help(void);
void getfile(char *infname);

/*=======================================================================*/

main(int argc,char *argv[])
{
	int     i,rcode,xp,yp;
    char    choice,*p;

	/* init stuff */
    textcolor(YELLOW);
    textbackground(BLACK);
    bfore=YELLOW;
    bback=BLACK;
	insertx=30;
	inserty=24;
	trimblanks=FALSE;
	nobeep=TRUE;
	defaultattrib=(BLACK<<4)+WHITE;  /* default color map */
	memset(colormap,defaultattrib,25*81);
	clrscr();
	cprintf("                            ANSI Editor\r\n\n");

    if (argc>1) strcpy(infname,argv[1]);
    else {
		cprintf("Input file (CR for none)? ");
        gets(infname);
    }
	if (infname[0] != 0) getfile(infname);
    xp=yp=0;
    trimblanks=FALSE;  /* avoid constant trim/untrim during loop */

	funkey_help();
	/* rcode = */
	edit((char *)screen,(char *)colormap,1,1,&xp,&yp,80,22);
	/* edit doesn't exit back until finished */

	savefile();
}

/*=======================================================================*/

void funkey_help(void)
/* display function key help */
{
    int     i;

    textcolor(BLUE);
    textbackground(LIGHTGRAY);
    for (i=0; i<10; i++) {
		gotoxy(i*8+1,25);
        cprintf("%s",keyhelp[i]);
    }
    textcolor(YELLOW);
    textbackground(BLACK);
}

/*=======================================================================*/

void ctrim(int i)
/* find the last significant change in line i (color or text), and put
   the null terminator just past that point */
{
	int j;

	j=strlen(screen[i])-1;
	while (((colormap[i][j] & 0x70) == 0) /* black bkgnd */
	  && (screen[i][j]==' ') && (j>=0)) j--;
	screen[i][j+1]=0;

}

/*=======================================================================*/

void changecolor(int attrib)
{
	int fore,back,bright,blink;
						/*  0   1   2   3   4   5   6   7 */
						/* bk  bl  gr  cy  rd  mg  br  lg */
	static				/*--------------------------------*/
	int colorcode[8] = {  30, 34, 32, 36, 31, 35, 33, 37 };


	/*
	if ((attrib & 0x80)==0) blink=FALSE;
	else blink=TRUE;
	*/

	if ((attrib & 0xf) > 7) bright=1;
	else bright=0;

	fore=colorcode[attrib & 0x7];
	back=colorcode[(attrib & 0x70)>> 4] + 10;

	/* if blink... ??? */

	fprintf(otfile,"\33[%d;%d;%dm",bright,fore,back);
}

/*=======================================================================*/

int savefile(void)
/* save text as an ANSI text file */
{
    char    *p;
	int     i,j,col,last,lastcolor;

    col=0;
	gotoxy(1,25);
    clreol();
	cprintf("Output file [.ANS]? ");
	strcpy(otfname,infname);
    p=otfname+strlen(otfname)-1;
	while (*p==' ') *(p--)=0;
    p=strstr(otfname,".");
    if (p!=NULL) *p=0;
	getstring(25,25,&col,otfname,14);
    p=otfname+strlen(otfname)-1;
	while (*p==' ') *(p--)=0;
	if (otfname[0]==0) return(1);
    p=strstr(otfname,".");
	if (p==NULL) strcat(otfname,".ans");
	otfile=fopen(otfname,"w");
	if (otfile== NULL) {
		gotoxy(1,25);
		clreol();
		cprintf("Can't create %s. Press key...",otfname);
		getch();
		return(0);
	}

	for (i=0;i<22; i++) ctrim(i);  /* trim lines */
	last=21;
	while (screen[last][0]==0) last--;

	lastcolor=colormap[0][0];
	changecolor(lastcolor);
	for (i=0; i<=last; i++) {
		/* output line i */
		for (j=0; j<strlen(screen[i]); j++) {
			if (colormap[i][j]!=lastcolor) {
				changecolor(colormap[i][j]);
				lastcolor=colormap[i][j];
			}
			fputc(screen[i][j],otfile);
		}
		if (strlen(screen[i])<80) fputc('\n',otfile);
	}
	if (lastcolor==0) changecolor(7);  /* don't leave black-on-black */

	fclose(otfile);
	return(1);
}

/*=======================================================================*/

void getfile(char *infname)
/* load input file (if desired) */
{
	int     i,j;
	char	*buff,*cptr;

	clrscr();
	if (strstr(infname,".") == NULL) strcat(infname,".ans");
    infile = fopen(infname,"r");
    if (infile==NULL) {
		printf("\nNew file.\n");
		delay(500);
		clrscr();
		return;
	}

	/* NOTE: the allocation below may have to be increased for a
	   complex screen; a normal screen contains 2000 (max) characters;
	   ANSI commands can expand this significantly--and, if you are
	   using 80-wide pictures, this will all appear as a single "line".
	   If you are having trouble with ANSIED distorting the picture when
	   it reads it back in, try increasing this buffer size--both here,
	   and in the fgets() statement just below. */

	buff=malloc(6000);
	if (buff==NULL) {
		printf("Unable to allocate storage for input buffer.\n");
		exit(1);
	}
	while (fgets(buff,6000,infile) != NULL) {
		trim(buff);
		puts(buff);
	}

	/* copy the displayed screen into our buffer */
	save2buff(buff);

	/* now copy the buffer's data into screen[] and colormap[] */
	cptr=buff;
	for (i=0;i<24; i++) {
		for (j=0; j<80; j++) {
			screen[i][j]=*(cptr++);
			colormap[i][j]=*(cptr++);
		}
	}

	fclose(infile);
	free(buff);
}

