/* $Id: ert.c,v 1.3 1998/11/20 10:51:12 nari Exp $ */

#include <stdio.h>

/*
 * EPSON Remoteのコマンドを出力するコマンド
 *
 *  標準入力の前後をEPSON Remoteのコマンドではさむ。
 */

printUsageAndExit()
{
  char **pp;
  static char *usage[] =
    {
      "Usage: ert [options] set_parameters ...",
      "  options",
      "    -lang lang          default lang=ESC/PAGE",
      "    -f input file       default stdin",
      "    -h                  show this",
      "",
      "  parameters",
      "    PU=1|2|3|AUTO",
      "    PS=A3|B4|A4|B5|A5|POSTCARD|LT|LGL|...",
      "    ZOOM=80",
      "    COPIES=10",
      "    RS=QK                quick-mode (300dpi)",
      "    RS=FN                fine-mode  (600dpi)",
      NULL,
    };

  for(pp=usage; *pp!=NULL; pp++)
    fprintf(stderr,"%s\n",*pp);
  exit(1);
}

static char *start="\033\001@EJL \r\n";

main(argc,argv)
    int argc;
    char *argv[];
{
  int i,n,ac,c,num;
  char **av;
  FILE *ifp = stdin;
  FILE *ofp = stdout;
  char *lang = "ESC/PAGE";
  int noMoreOptions = 0;
  
  if(argc < 2) printUsageAndExit();
  
  av = (char **)malloc(sizeof(char *) * argc);
  if(av == NULL){
    fprintf(stderr,"Memory allocation failed.\n");
    exit(1);
  }
  ac = 0;
  
  /* オプションをスキャン */

  for(i=1; i<argc; i++){
    if(argv[i][0] == '-' && !noMoreOptions){
      n = strlen(argv[i]);
      if(strcmp("--",argv[i])==0) noMoreOptions = 1;
      else if(strncmp("-h",argv[i],n)==0 && n > 1)
	printUsageAndExit();
      else if(strncmp("-language",argv[i],n)==0 && n > 1){
	if(i+1 < argc)
	  lang = argv[i+1];
	else {
	  fprintf(stderr,"%s needs argument  ESC/PAGE, ESC/P ,ESC/PS or EP-GL\n",
		  argv[i]);
	  exit(1);
	}
	i++;
      }
      else if(strncmp("-f",argv[i],n)==0 && n > 1){
	if(i+1 < argc){
	  ifp = fopen(argv[i+1],"r");
	  if(ifp == NULL){
	    fprintf(stderr,"file \"%s\" not found.\n",argv[i+1]);
	    exit(1);
	  }
	}
	else {
	  fprintf(stderr,"%s needs filename.\n",argv[i]);
	  exit(1);
	}
	i++;
      }
    }
    else 
      av[ac++] = argv[i];
  }
  
  /* EPSON Remote モード開始 */

  fputs(start, ofp);
  fprintf(ofp,"@EJL SELECT LANGUAGE=%s\r\n",lang);
  fprintf(ofp,"@EJL SET");
  for(i=0;i<ac;i++)
    fprintf(ofp," %s",av[i]);
  fprintf(ofp,"\r\n");
  fprintf(ofp,"@EJL ENTER LANGUAGE=%s\r\n",lang);

  /* 中身出力 */

  while((c = getc(ifp))!=EOF)
    putc(c,ofp);

  /* EPSON Remote モード終了  */
  
  fputs(start, ofp);
  fputs(start, ofp);
  
  exit(0);
}
