#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

/* printing chars by pixels
 printer moves to graphics mode after issuing 1b,4b and number of chars
 to print (in packet) */

#define STDIN	0
#define STDOUT	1
#define STDERR	2
#define FALSE   0
#define TRUE    1

void main(int argc, char *argv[]){
	unsigned char chartable[256*6],c;
	int readed,i,j,handle;
	int PacketSize;
	unsigned char Packet[90];	/* max string length */
        int isMoreChars;
        int EachChar;
        int EachVertical;

	fprintf(stderr,"Matrix printer font filter by Penn (penn@usa.net)\n");
	fprintf(stderr,"GPL, april 1998\n");
	if (argc==1){		/* no parameters */
		fprintf(stderr,"Usage:\n");
		fprintf(stderr,"\t<stdin> | lpfont [font file name] | <stdout>\n");
		exit(1);
	}
/*** in future to use memset here */
	for(i=0;i<32*6;i++) chartable[i]=0;
	handle=open(argv[1],O_RDONLY);
	if (handle==-1){
		perror(argv[1]);
		exit(1);
	}
    read(handle,&chartable[32*6],224*6);
    close(handle);

    PacketSize=0;
    isMoreChars=TRUE;
    while(isMoreChars)
    {
        readed=read(0,&c,1);
        if (readed==0 || readed==-1) { isMoreChars=FALSE; continue; }
        if (c<128)
        {
            if (PacketSize!=0)
            {
                /* parsing packet */
                putchar(0x1b);putchar(0x4b);
                /* number of vertical rows to print */
                putchar((PacketSize*6)%256);putchar((PacketSize*6)/256);
                for(EachChar=0;EachChar<PacketSize;EachChar++)
                   for(EachVertical=0;EachVertical<6;EachVertical++)
                       putchar(chartable[Packet[EachChar]*6+EachVertical]);
                PacketSize=0;
            }
            if (c==0x0a)
            {
              putchar(0x0d);putchar(0x0a);
            }
            else
            {
                putchar(c);
            }
        }
        else
            Packet[PacketSize++]=c;
    }while(readed!=0);
}

