/* separate.c; Epson color seperator - (c) 1987 DJH

	Use this program with files grabbed with PARSNAG to perform color
separations on dithered color prints. Separate claims only to work on files
created using Mike Paul's JX-80.12a printer driver. Quick hack; assumes all
Epson cmds are 2-bytes except for the SET_GRAPHICS cmd, which is always
preceded by a SET_COLOR.

*/

#define ESC 0x1b
#define SET_COLOR 0x72
#define SET_GRAPHICS 0x4c

main(argc,argv)
int argc;
char *argv[];
{
  FILE *input,*output;
  unsigned char buf,color;
  short i;

  if (argc<3) { puts("Separate color[0,1,2,4] <input> <output>"); exit(0); }

  color=argv[1][0]-'0';

  input=fopen(argv[2],"r"); output=fopen(argv[3],"w");

  if (!input) { puts("input error!"); exit(0); }
  if (!output) { puts("output error!"); fclose(input); exit(0); }

  while (fread(&buf,1,1,input)) { /* any characters left? */
    if (buf!=ESC) {
      fwrite(&buf,1,1,output);
      continue;
    }

    fread(&buf,1,1,input); /* ESC found, fetch command */

    if (buf!=SET_COLOR) {
      putc(ESC,output); /* restore consumed ESC */

      fwrite(&buf,1,1,output); /* copy command */

      fread(&buf,1,1,input);   /* copy command's args */
      fwrite(&buf,1,1,output); /* done, stream sync intact */

      continue;
    }

   fread(&buf,1,1,input); /* ESC & SET_COLOR found, fetch argument */

   if (buf!=color) { /* filter this color? */
     fread(&buf,1,1,input); /* skip over ESC */
     fread(&buf,1,1,input); /* skip over SET_GRAPHICS */

     fread(&buf,1,1,input); /* fetch count lsb */

     i=buf;

     fread(&buf,1,1,input); /* fetch count msb */

     i+=(buf*256);

     fseek(input,i,1); /* skip graphics dump */
   }
   else { /* color found! */
     putc(ESC,output); /* restore consumed chars */
     putc(SET_COLOR,output);
     putc(color,output);

     /* copy following ESC/SET_GRAPHICS/LSB */

     for (i=0;i<3;i++) { fread(&buf,1,1,input); fwrite(&buf,1,1,output); }

     i=buf; /* fetch lsb */

     fread(&buf,1,1,input); fwrite(&buf,1,1,output); /* fetch msb */

     for (i+=(buf*256);i;--i) { /* copy graphics dump */
       fread(&buf,1,1,input); fwrite(&buf,1,1,output);
     }
   }
  }

  fclose(input); fclose(output);
}
