char *(*dfmt)(time_t);
FILE *in, *out;
docfmt fmt;
int c, i, opt_index, n, wd;
const char *s,*t, *ext;
int verbose=0, name_alloced, res;
struct
{
unsigned new_pages:1;
} flags={ 0 };
res=0; // Return code 0
fmt=*(formats[0].fmt); // Set default format
dfmt=dates[0].fmt; // Set default date format
wd=fmt.maxline; // Set default width
ext=formats[0].ext; // Set default extension
while ((c=getopt_long(argc, (char *const *) argv, "Vhpvqf:w:d:",
lopts, &opt_index))!=-1)
{
switch(c)
{
case 'V': // Print version and exit
fputs("word2x 0.005\n", stderr);
return 0;
case 'p':
flags.new_pages=1;
break;
case 'h': // Help
fputs("Usage: word2x [-f <output format>] [--dates <date format>]"
" [-w <line length>]\n"
" <infile> [<outfile>]\n"
"Supported date formats: ", stderr);
for (i=0; i<(int) N(dates); i++)
{
if (i!=0)
fputs(", ", stderr);
fputs(dates[i].name, stderr);
}
fputs("\nSupported output formats: ", stderr);
for (i=0; i<(int) N(formats); i++)
{
if (i!=0)
fputs(", ", stderr);
fputs(formats[i].name, stderr);
}
fputc('\n', stderr);
return 0;
case 'v': // Verbose mode
verbose=1;
break;
case 'q': // Queit mode
verbose=0;
break;
case 'w': // Width
n=0;
if (*optarg=='\0')
{
fputs("-w requires a number\n", stderr);
break;
}
for (s=optarg; *s; s++)
{
if (!isdigit(*s))
{
res=1;
fputs("-w requires a number\n", stderr);
break;
}
n=n*10+(*s-'0');
}
if (*s=='\0')
wd=n;
break;
case 'd': // Date format
for (n=-1, i=0; i<(int) N(dates); i++)
{
if (strcasecmp(dates[i].name, optarg)==0)
{
n=i;
break;
}
}
if (n==-1)
{
res=1;
fprintf(stderr, "%s is not a known date format\n", optarg);
}
else
dfmt=dates[i].fmt;
break;
case 'f': // Output format
for (n=-1, i=0; i<(int) N(formats); i++)
{
if (strcasecmp(formats[i].name, optarg)==0)
{
n=i;
break;
}
}
if (n==-1)
{
res=1;
fprintf(stderr, "%s is not a known output format\n", optarg);
}
else
{
fmt=*(formats[i].fmt);
ext=formats[i].ext;
}
break;
case '?':
break;
default:
abort();
}
}
/* Make sure we have a filename */
if (optind==argc)
{
fputs("word2x: filename required (can not handle stdin)\n", stderr);
return 1;
}
/* Stop if invalid switches */
if (res!=0)
return res;
/* Set line width and date format */
fmt.date=dfmt;
fmt.maxline=wd;
fmt.flags.new_pages=flags.new_pages;
/* Loop through files */
for (i=optind; i<argc; i++)
{
s=argv[i];
if (i==argc-1 || postfix(argv[i+1],".doc"))
{
/* Generate output file name */
if ((t=outname(argv[i], ext))==NULL)
{
fprintf(stderr,
"word2x: skipping %s due to allocation failure\n",
s);
continue;
}
name_alloced=1;
}
else
{
t=argv[++i];
name_alloced=0;
}
/* Open input file */
if ((in=open_file(s))==NULL)
{
if (name_alloced)
free((void *) t);
fprintf(stderr, "Could not open %s\n", s);
res=1;
continue;
}
/* Open output file */
if (strcmp(t,"-")==0)
{
out=stdout;
t="standard output";
}
else
{
if ((out=fopen(t, "w"))==NULL)
{
fprintf(stderr, "Could not open %s\n", t);
if (name_alloced)
free((void *) t);
fclose(in);
res=1;
continue;
}
}