/*
 * print a ASCII file with small format using a EPSON LQ printer
 * written by Jens Mueller, Jan 14, 1994
 */

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

#ifndef FILENAME_MAX
#define FILENAME_MAX   128
#endif

#define LINE_DIST      7         /* n/60 inches               */
#define LEFT_MARGIN    9         /* left margin in characters */
#define RIGHT_MARGIN   119       /* column of right margin    */


char *dflt_prn = "PRN:";         /* default printer device    */
char buf[FILENAME_MAX + 1];


void prn_init (fp)
   FILE *fp;
{
   fprintf (fp, "\033@");                   /* init           */
   fprintf (fp, "\033g");                   /* width: 15 cpi  */
   fprintf (fp, "\033S0");                  /* small height   */
   fprintf (fp, "\033A%c", LINE_DIST);      /* line distant   */
   fprintf (fp, "\033l%c", LEFT_MARGIN);    /* left margin    */
   fprintf (fp, "\033Q%c", RIGHT_MARGIN);   /* right margin   */
}


void prn_exit (fp)
   FILE *fp;
{
   fprintf (fp, "\033@");                   /* init           */
}


int add_file (fp, fname)
   FILE *fp;
   char *fname;
{
   FILE *infile;
   char c;
   int  status = 0;

   infile = fopen (fname, "r");
   if (infile == NULL)
   {
      fprintf (stderr, "cannot open file '%s'\n", fname);
      return (-1);
   }

   c = fgetc (infile);
   while (!feof (infile) && !ferror (infile))
   {
      fputc (c, fp);
      c = fgetc (infile);
   }

   if (ferror (infile))
   {
      fprintf (stderr, "cannot read file '%s'\n", fname);
      status = -1;
   }
   fclose (infile);
   return (status);
}


main (argc, argv)
   int  argc;
   char **argv;
{
   int  i, status = 0;
   char *outname;
   FILE *outfile;

   if (argc < 2)
   {
      printf ("usage: eqsmall filename [...]\n");
      exit (-1);
   }

   printf ("output stream (%s) ? ", dflt_prn);
   fgets (buf, FILENAME_MAX, stdin);
   putchar ('\n');
   outname = strtok (buf, "\r\n");
   if ((outname == NULL) || (strlen (outname) < 1))
      outname = dflt_prn;

   outfile = fopen (outname, "w");
   if (outfile == NULL)
   {
      fprintf (stderr, "cannot open output stream '%s'\n",
               outname);
      exit (-1);
   }

   if ( !isatty (fileno (outfile)))
      printf ("writing to file...\n");

   prn_init (outfile);

   for (i = 1; i < argc; i++)
   {
      if (i > 1)
         fputc (12, outfile);               /* new page       */
      status |= add_file (outfile, argv[i]);
   }

   prn_exit (outfile);
   if (ferror (outfile))
   {
      fprintf (stderr, "cannot write to output stream '%s'\n",
               outname);
      status = -1;
   }
   fclose (outfile);
   exit (status);
}

