#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <string.h>
#include "../inc/getopt.h"
#include "../inc/debug.h"

#define	msg(s) fputs(s, stderr)

char   *file[50];

char   *help_msg[] =
{
    "タブ→スペース変換  ＴＡＢ２ＳＰＣ．ＥＸＥ\n",
    "                     Y.Tsuzi[" __DATE__ "]\n",
    "    >tab2spc [-hH?] [-s size] [infile...] [-o outfile]\n",
    "                                < [infile] > [outfile]\n",
    "    -hH?       ヘルプ\n",
    "    -s size    タブサイズ指定（デフォルト８）\n",
    "    -d         デバックモード（タブを'_'で出力）\n",
    "    infile     入力ファイル\n",
    "    outfile    出力ファイル\n",
    NULL
};

typedef enum {
    ON = !0, OFF = 0
}       flag_t;

int     help(void);
int     tab2spc(FILE *, FILE *, int, flag_t);

int     main(int argc, char **argv)
{
    int     i;
    int     tab_size = 8;
    flag_t  debug = OFF;
    char   *data;
    char   *out_file = NULL;
    char  **fname = file;
    FILE   *in_fp, *out_fp;

    setopt(argc, argv);

    while ((i = getopt('-', "o:s:dhH?", &data)) >= 0) {
	switch (i) {
	case 'o':
	    if (data != NULL)
		out_file = data;
	    break;
	case 's':
	    if (data != NULL) {
		if (sscanf(data, "%i", &tab_size) != 1) {
		    help();
		    return 1;
		}
	    }
	    break;
	case 'd':
	    debug = ON;
	    break;
	case 'h':
	case 'H':
	case '?':
	    help();
	    return 1;
	case 0:
	    *fname++ = data;
	}
    }
    *fname = NULL;

    if (tab_size == 0)
	tab_size = 4;

    if (out_file != NULL) {
	if ((out_fp = fopen(out_file, "w")) == NULL) {
	    msg("出力ファイルがオープンできません。\n");
	    return 1;
	}
    } else {
	out_fp = stdout;
    }

    fname = file;

    if (!isatty(fileno(stdin))) {
	tab2spc(stdin, out_fp, tab_size, debug);
    } else if (*fname == NULL) {
	help();
	goto EXIT;
    }
    while (*fname != NULL) {
	if ((in_fp = fopen(*fname++, "r")) == NULL) {
	    msg("ファイルがオープンできません。\n");
	    goto EXIT;
	}
	tab2spc(in_fp, out_fp, tab_size, debug);

	fclose(in_fp);
    }

  EXIT:
    if (out_file != NULL)
	fclose(out_fp);
    return 0;
}

int     tab2spc(FILE * in, FILE * out, int size, flag_t debug)
{
    int     c, space = ' ', i = 1, j;

    if (debug)
	space = '_';

    while ((c = fgetc(in)) != EOF) {
	if (c == '\t') {
	    j = size - ((i - 1) % size);
	    i += j;
	    for (; j > 0; j--)
		fputc(space, out);
	    continue;
	} else if (c == '\n') {
	    i = 1;
	} else {
	    i++;
	}
	fputc(c, out);
    }

    return 0;
}

int     help(void)
{
    char  **help = help_msg;

    while (*help != NULL)
	msg(*help++);
    return 0;
}
