#include <stdio.h>
#include <string.h>
#include <ctype.h>

#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE (!0)
#endif
typedef struct scrap_node {
  struct scrap_node *next;
  int scrap;
} Scrap_Node;
typedef struct name {
  char *spelling;
  struct name *llink;
  struct name *rlink;
  Scrap_Node *defs;
  Scrap_Node *uses;
  int mark;
  char tab_flag;
  char indent_flag;
  char debug_flag;
} Name;

int tex_flag;      /* if FALSE, don't emit the .tex file */
int output_flag;   /* if FALSE, don't emit the output files */
int compare_flag;  /* if FALSE, overwrite without comparison */
char *command_name;
char *source_name;  /* name of the current file */
int source_line;    /* current line in the source file */
Name *file_names;
Name *macro_names;
Name *user_names;

void pass1();
void write_tex();
void write_files();
void source_open(); /* pass in the name of the source file */
int source_get();   /* no args; returns the next char or EOF */
void init_scraps();
int collect_scrap();
int write_scraps();
Name *collect_file_name();
Name *collect_macro_name();
Name *collect_scrap_name();
Name *name_add();
Name *prefix_add();
char *save_string();
void reverse_lists();
void *arena_getmem();
void arena_free();


void write_files(files)
     Name *files;
{
  while (files) {
    write_files(files->llink);
    {
      FILE *temp_file;
      char temp_name[12]="nuweb~~~.tmp";
    /*  sprintf(temp_name, "%s~", files->spelling);  */
      temp_file = fopen(temp_name, "w");
      if (temp_file) {
        char indent_chars[500];
        write_scraps(temp_file, files->defs, 0, indent_chars,
                     files->debug_flag, files->tab_flag, files->indent_flag);
        fclose(temp_file);
        if (compare_flag)
          {
            FILE *old_file = fopen(files->spelling, "r");
            if (old_file) {
              int x, y;
              temp_file = fopen(temp_name, "r");
              do {
                x = getc(old_file);
                y = getc(temp_file);
              } while (x == y && x != EOF);
              fclose(old_file);
              fclose(temp_file);
              if (x == y)
                unlink(temp_name);
              else
                rename(temp_name, files->spelling);
            }
            else
              rename(temp_name, files->spelling);
          }
        else
          rename(temp_name, files->spelling);
      }
      else {
        fprintf(stderr, "%s: can't open %s\n", command_name, temp_name);
        exit(-1);
      }
    }
    files = files->rlink;
  }
}
