//
// Copyright(C) Simon Howard
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
//
// Detabifying program
//
// Expand tabs to spaces
//
// By Simon Howard
//

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

#define TMPNAME ".detabtmp"
#define TAB "        "

int main(int argc, char *argv[])
{
  int i;

  if(argc < 2) {
    printf("usage: detab <filename>\n");
    exit(-1);
  }

  for(i=1; i<argc; i++) {
    FILE *infile, *outfile;
    unsigned char c;

    infile = fopen(argv[i], "r");
    if(!infile) {
      fprintf(stderr, "cannot find '%s'!", argv[i]);
      continue;
    }

    outfile = fopen(TMPNAME, "w");
    if(!outfile) {
      fprintf(stderr, "cannot create '%s'!", TMPNAME);
      exit(-1);
    }

    while(!feof(infile)) {
      c = getc(infile);

      if(c == 0xff)         // ???
	continue;
      else if(c == '\t')
	fprintf(outfile, TAB);
      else
	fputc(c, outfile);
    }

    fclose(infile);
    fclose(outfile);

    remove(argv[i]);
    rename(TMPNAME, argv[i]);
  }
}

