/* C K L D E F
 *    Process command line arguments, and produce a C-language header file
 *    with the arguments #defined in it.  Can be used in lieu of the "normal"
 *    -DSYMBOL construct found in most C compilers.
 */

#include <string.h>
#include <stdio.h>

#define CV char_varying

extern void s$parse_command (CV(32) *name, short *status, ...);

static CV(32) caller = "make_defines";
static CV(40) file_def = "output:pathname,required";
static CV(40) read_def = "switch(-read),=1";
static CV(40) symb_def = "symbols:string(*)";
static CV(3)  end_def = "end";

void
ckldef (void)
{
  short status;
  CV(256) out_path_cv;
  char    out_path[257];
  FILE    *out_file;
  char    in_name[L_tmpnam];
  FILE    *in_file;
  short   i;
  short   read_sw;
  CV(256) *cvp;
  char    buff[BUFSIZ];
  char    *cp;

  struct arglist
  {
    short num_args;
    short arg_length;
    short array_bound;
    CV(256) args[1];
  } *arglistp;

  s$parse_command (&caller, &status,
                   &file_def, &out_path_cv,
                   &read_def, &read_sw,
                   &symb_def, &arglistp,
                   &end_def);

  if (status)
    return;

  strcpy (out_path, &out_path_cv);
  if (read_sw)
  {
    tmpnam (in_name);
    rename (out_path, in_name);
    in_file = fopen (in_name, "r");
  }
  out_file = fopen (out_path, "w+");
  if (out_file == NULL)
  {
    fprintf (stderr, "Cannot open %s for write/create\n", out_path);
    return;
  }

  if (in_file)
  {
    while (NULL != (cp = fgets (buff, sizeof buff, in_file)))
    {
      if (buff[0] != '#')
      {
        fputs (buff, out_file);
      }
    }
    fclose (in_file);
    remove (in_name);
  }

  if (arglistp && arglistp->num_args)
    for (i = 0; i < arglistp->num_args; i++)
      fprintf (out_file, "#define %v\n", &arglistp->args[i]);

  fclose (out_file);
}
