/*****************************************************************************
 *	Add escape sequence to documents.				     *
 * 	Update:  Closed the seqpt file				  	     *
 *	Date: 	16 January 87	    					     *
 *									     *
 *	Revision 1.4 - Added the printer sequences for the "R" cartiage.     *
 *		Since the first character sent to the printer cannot be      *
 *		a escape sequence when there are margins a space had to      *
 * 		printed as the first character of the line.  Also, spaces    *
 *		will vary in size depending on the font choosen.  To  	     *
 *		prevent uneven margins the font has to be set to the defaut  *
 *	 	at the end of the line, a space printed as the first 	     *
 *		character of the line, and the font is set back.	     *
 *									     *
 *	Revision 1.5 - Change the way the space is printed at the beginning  *
 *		of each line.  If the file contains any font command         *
 *		requiring the R Cartridge, the space is printed with a       *
 *		default font. If the file does not require the R Cartridge   *
 *		then the font is not changed.				     *
 *									     *
 *	Revision 1.6 - In the MODTXT function the way to check for the end   *
 *		of file is to get a character from the beginning of the      *
 *		line, if the character is an end of line character return.   *
 *		If it if not return the character (ungetc) to the file and   *
 *		continue to get the whole line.  When the first character of *
 * 		the line is and escape sequence, in an easyform format, the  *
 *		unget function does not return the character; therefore, the *
 *		the character gets lost or is not written to the output      *
 *		file. Changed the defined symbol NULL to ENULL because it    *
 *		conflicted with the stdio defined symbol NULL.		     *
 *									     *
 *****************************************************************************/

#include <stdio>
#include <ctype>
#define VERSION "1.6"
#define	MAXCHAR	80 
#define MAXSEQ  25
#define MAXLEN	255
#define MAXNAME 40
#define PRTDEF  "dra0:[tools]aloff.def"
#define DPITCH	"\033(s0p10H"
#define ENULL	"NULL"			/* Null field in PRTDEF	*/
#define R_CART  'R'                                                        

int tabwidth = 8;
char dfont[MAXLEN], cfont[MAXLEN];

/* Print sequence structure.  If and of the elements in the structure is not  */
/* applicable the word "NULL" is entered in the aloff.def file.		      */

struct prt{
	char command[MAXCHAR];  /* pseudo command found in the file           */
	char on[MAXCHAR];	/* escape sequence to activate the function   */
	char off[MAXCHAR];	/* escape sequence to inactivate the function */
	char font[MAXCHAR];     /* name of the font cartridge		      */
	char flag;		/* determines whether to use the on or off    */
}seq[MAXSEQ];			/* function				      */
int cntseq = 0;

main(argc,argv) 
int argc;
char **argv;
{
	char temp[MAXNAME], file[MAXNAME], dfile[MAXNAME], tab[MAXNAME], *tabpt;
	int i, tablen;
	FILE *fopen(), *inpt, *outpt;
	                  
	loadprt();      
	printf("Format file for LaserJet output - Version %s\n\n",VERSION);
	while (TRUE){
		if ( argc == 1 ){
			printf("Usage: aloff [filename.ext] [-tn]\n");
			printf("       -tn (n number of spaces per tab)\n\n");
			printf("Enter Filename > ");
			gets(file,MAXNAME);
		}
    		else
			strcpy(file,argv[1]);
		if ( argc == 3 ){
			strcpy(tab,argv[2]);
			tabpt = tab;
			if ( (*tabpt++ == '-') && (toupper(*tabpt++) == 'T') )
			     tabwidth = atoi(tabpt);
			else{
			     fprintf(stderr,"Usage: aloff [filename.ext] [-tn]\n");
			     exit(1);
			}                   
		}
		if ( !(inpt = fopen(file,"r")) ){
			fprintf(stderr,"Cannot open file : %s\n",file);
			exit(1);
		}
		else{
			makename(dfile,file,".LASER");
			if ( !(outpt = fopen(dfile,"w","rat = cr","rfm = var")) )
				printf("Cannot open file: %s\n",dfile);
			break;
		}
	}
	check_r_cart(inpt);
	modtxt(inpt,outpt);	
	fclose(inpt);
	fclose(outpt);
}

loadprt()
{
	FILE *seqpt;
	char temp[MAXLEN], cmd[MAXNAME], *tempt, *cmdpt;
	char c;
	int i;

	if ( !( seqpt = fopen(PRTDEF,"r") ) )
		abort("Cannot open printer sequence file");

	for ( i = 0; (c = fgetc(seqpt)) != EOF; i++ ){
		ungetc(c,seqpt);
		tempt = fgets(temp,MAXLEN,seqpt);
		while ( (*tempt == ' ') || (*tempt == '\t') )
			*tempt++;
		cmdpt = seq[i].command;
		while ( !(isspace(*tempt)) )
			*cmdpt++ = *tempt++;
 		*cmdpt = '\0';
		while ( *tempt == ' ' || (*tempt == '\t') )
			*tempt++;
		cmdpt = cmd;		
    		while ( !(isspace(*tempt)) )
			*cmdpt++ = *tempt++;
		*cmdpt = '\0';
		ptrseq(seq[i].on,cmd);		
                           
		while ( *tempt == ' ' || (*tempt == '\t') )
			*tempt++;
		cmdpt = cmd;
		while ( !(isspace(*tempt)) )
			*cmdpt++ = *tempt++;
		*cmdpt = '\0';
		ptrseq(seq[i].off,cmd);

		while ( *tempt == ' ' || (*tempt == '\t') )
			*tempt++;
		cmdpt = cmd;
		while ( !(isspace(*tempt)) )
			*cmdpt++ = *tempt++;
		*cmdpt = '\0';
		strcpy(seq[i].font,cmd);

		seq[i].flag = FALSE;
		cntseq++;
	}	
	fclose(seqpt);
} 

ptrseq(d,s)
char *d, *s;
{                               
	int num;

	while ( *s != '\0' ){
		if ( *s == '\\' ){       
			sscanf(++s,"%o",&num);
			*d++ = (char)num;
			while ( (*s >= '0') && (*s <= '7') )
				s++;
		}
		else
			*d++ = *s++;
	}
	*d = '\0';
}

getans(s)
char *s;
{
	if ( toupper(*s) == 'Y' )
		return(TRUE);
	else
		return(FALSE);
}

/** Modify the buffer text by replacing the flag characters       **/
/** with control characters. 			   		  **/

modtxt(inpt,outpt)           
FILE *inpt, *outpt;
{
    int i = 0, result;
    int blanks = 0, j, seqfound;               
    char *tptr, *buffp, *codept, c;
    char temp[2 * MAXLEN], buff[MAXLEN], code[MAXLEN];
   
    while ( fgets(buff,MAXLEN,inpt) != NULL ){         
	temp[0] = '\0';
	tptr = temp;                
  	buffp = buff;

/* Print all leading tabs and spaces.  					*/

	while ( (*buffp == '\t') || (*buffp == ' ') ){
	     if (*buffp == '\t'){
	          *tptr = '\0';
	          blanks = (tabwidth - (strlen(temp) % tabwidth) );
	          for ( j = 0; j < blanks; j++ )
	 	       *tptr++ = ' ';
	          *buffp++;
	     }           
	     while (  *buffp  == ' ' )
	           *tptr++ = *buffp++;
	}                      
                                                                              
/* Offset the first line by a space.  The reason is, if there an escape */
/* sequence in the first column and a margin is used when printing the  */
/* escape sequence is separated by spaces (the indent) causing 		*/
/* undesireable results.						*/

	*tptr++ = ' ';
	stradd(tptr,cfont);
	tptr += strlen(cfont);

/* Check if any of the functions were turned off at the end of the line   */
/* and need to be turned back on until the command specified to turn if   */
/* off is found in the input file.					  */

	for ( i = 0; i < cntseq; i++ ){
	     if ( seq[i].flag == TRUE ){
	          stradd( tptr,seq[i].on );
	          tptr += strlen(seq[i].on);
	     }
	}         

	while (  *buffp  != '\n' ){
	    if ( *buffp != '^' ){
		if ( *buffp == '\t' ){
		     *tptr = '\0';
		     /* Subtract one from string length of temp to account 
		  	for the space added at the beginning of the line  */
		     blanks = (tabwidth - ((strlen(temp) -1) % tabwidth) );
		     for ( j = 0; j < blanks; j++ )
			  *tptr++ = ' ';
		     *buffp++;     
		}
	        else{
	  	     *tptr++ = *buffp++;
		}
	    }
	    else{
         	strcpy(code,buffp);
		seqfound = 0;
		for ( i = 0; i < cntseq; i++ ){
		   result = strncmp(seq[i].command,code,strlen(seq[i].command));
		   if ( result == 0 ){
		      seqfound = 1;
		      if ( seq[i].flag == TRUE ){
			 stradd ( tptr,seq[i].off );
			 tptr += strlen(seq[i].off);
			 seq[i].flag = FALSE;
		      }
		      else{
			 stradd ( tptr,seq[i].on );
			 tptr += strlen(seq[i].on);
			 result = strncmp(seq[i].off,ENULL,strlen(seq[i].off));
			 if ( result )
			      seq[i].flag = TRUE;
		      }
		      buffp += strlen(seq[i].command);
		      result = strncmp(seq[i].font,ENULL,strlen(seq[i].font));
	              if ( result )		/* Save the last font used */
			 strcpy(cfont,seq[i].on);
		      break;       
		   }
	        }
		if ( seqfound == 0 )  	/* print the ^ if not sequence in    */
		   *tptr++ = *buffp++;  /* definition file		     */
	    }
	}
	for ( i = 0; i < cntseq; i++ ){
	     if ( seq[i].flag == TRUE ){
	         stradd ( tptr,seq[i].off );
	         tptr += strlen(seq[i].off);
	     }
	}                                                                
	stradd(tptr,dfont);
	tptr += strlen(dfont);
	*tptr++ = '\n';
	*tptr = '\0';
	fputs(temp,outpt);
    }
}                        

                              

/* This function will replace a "\n" with a "\0" at the end of 	*/
/* a character string.						*/

remnl(s)
char *s;
{
	s[strlen(s) - 1] = '\0';
}

/**  Make a string upper case.   		**/

strupr(s)
char *s;
{
    char c;
    
    while ( (c = *s) )
	*s++ = toupper(c);
    *s = '\0';
}

stradd(s1,s2)
char *s1, *s2;
{
	while ( (*s1++ = *s2++) )
		;
}
/**  								  **/
/**  Get the file Review Item name from standard in and checks to **/
/**  see if it has a prefix '.XXX' . If it does not have a prefix **/
/**  a prefix of '.ITM' will be added.				  **/
/**								  **/
/**  Variables:
 **	f	file name
 ** 	s	input stream
 **	ext	default extension given to an input file
 **/


makename(f,s,ext)
char *f, *s, *ext;
{
    int length = 0, i;
    char *fp;

    strcpy(f,s);
    strupr(f);
    fp = f;
    length = strlen(f);
    
    if (length > MAXNAME){
	printf("Bad file name, you will now exit.\n");
	exit();
    }
    else if (length == NULL){
	printf("No file name entered, you will now exit.\n");
	exit();
    }
    
    for (i = 0; i < length; i++){
	if (*fp == '.')
            break;
        else
            fp++;
    }
  
    *fp = '\0';
    strcat(fp,ext);    
}

/*  Check to see if any of the R cartridge is used, if it is then the   */
/*  beginning of each line has to print the space in the default font.  */
/*  In this way if there are various font used throughout the file the  */
/*  space at the beginning will always be the same size. If not then    */
/*  the defaut font is set to null.  If the R Cartridge is used then    */
/*  the file cannot be printed in compressed mode.			*/

check_r_cart(filept)
FILE *filept;
{
     char c, temp[MAXLEN]; 
     int result, i;

     while (  (c = fgetc(filept)) != EOF ){         
	if ( c == '^' ){
	     ungetc(c,filept);
	     fgets(temp,MAXLEN,filept);
	     for ( i = 0; i < cntseq; i++ ){
		 result = strncmp(seq[i].command,temp,strlen(seq[i].command));
	     	 if ( (result == 0) && (seq[i].font[0] == R_CART) ){
     		      ptrseq(dfont,DPITCH);	/* default font - pitch	*/
     		      ptrseq(cfont,DPITCH);	/* current font - pitch	*/
     		      rewind(filept);
		      return;
	         }
	     }
	 }
     }
     *dfont = '\0';	/* default font - pitch		*/
     *cfont = '\0';	/* current font - pitch		*/
     rewind(filept);
}
	          	
	 


