/*
 * File:	utf7encode.c
 *
 * Author:	Ulli Horlacher (framstag@rus.uni-stuttgart.de)
 * 
 * Contrib.:	Christoph 'GNUish' Goern (goern@janus.beuel.rhein.de)
 *
 * History:	
 * 
 *   1995-03-24 Framstag	initial version
 *   1997-01-20 GNUish		modified to move to the gnu-style
 *   1997-02-23 Framstag	modified str_* function names
 *   1998-10-29 Framstag	new option -S
 *
 * Filter to encode or decode UTF-7.
 *
 * Copyright © 1995-1998 Ulli Horlacher
 * This file is covered by the GNU General Public License
 */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>

#include "message.h"	/* information, warning and error messages */
#include "io.h"         /* misc IO routines */
#include "utf7.h"	/* UTF-7 coding */
#include "string.h"     /* extended string functions */

#if defined(HAVE_GETOPT_H)
  #include <getopt.h>
#else
  int getopt(int, char * const *, const char *);
  extern int opterr;
  extern int optind;
  extern int optopt;
  extern char *optarg;
#endif

#if defined(SOLARIS2) 
  FILE *fdopen(int, const char *);
#endif

int usage();

char *prg; 	/* program name */


int main(int argc, char *argv[]) {
  extern int
    optind;
  int
    withspace,
    opt;
  char
    *cp,
    line[MAXLEN],
    tmp[MAXLEN],
    utf_line[LEN_UTF],
    iso_line[LEN_ISO];
  int
    decode;
  FILE *inf;

  withspace=1;
  decode=0;
  prg=argv[0];

  if (str_eq(prg,"utf7decode")) decode=1;

  while ((opt=getopt(argc,argv,"Sh?d")) > 0) {
    switch (opt) {
      case ':':
      case 'h':
      case '?': exit(usage());
      case 'S': withspace=0; break;
      case 'd': decode=1; break;
    }
  }

  if (argc-optind==0)
    inf=fdopen(0,"r");
  else {
    inf=rfopen(argv[optind],"r");
    if (inf==NULL) {
      sprintf(tmp,"cannot open %s",argv[optind]);
      message(prg,'F',tmp);
    }
  }

  while (fgetl(line,inf)) {
    if ((cp=strchr(line,'\n'))) *cp=0;
    if (decode) {
      utf2iso(0,iso_line,tmp,tmp,line);
      printf("%s\n",iso_line);
    }
    else {
      iso2utf7(utf_line,line,withspace);
      printf("%s\n",utf_line);
    }
  }

  exit(0);
}


/* void function for message() */
void cleanup() { }


/*
 * usage - print short help usage text
 */
int usage() {
  fprintf(stderr,"usage:  %s [-S] [-d] [text-file]\n",prg);
  fprintf(stderr,"option: -S  encode single spaces, too\n");
  fprintf(stderr,"        -d  decode\n");
  return(2);
}


syntax highlighted by Code2HTML, v. 0.9.1