/*
 texindex.c: a wrapper
 public domain (2020/04/20 --ak)

 (1) change input index file in utf-8 into sjis by iconv
 (2) apply texindex.exe for sjis, renamed as ptexindex.exe
     to the changed input index file
 (3) change generated output index file in sjis into utf-8 by iconv.
*/

#include <stdio.h>
#include <string.h>
#include <process.h>
int main(int argc, char *argv[])
{
  char *tmpnam="tmp_index_file_a_b_c_d_xxx_yyy_zzz";

  /* input index file name */
  char *in_index;

  /* output index file name */
  char out_index[256];

  /* temporary file names */
  char mednam1[256];
  char mednam2[256];

  /* command line for system() */
  char cmdline[512];
  /* last suffix */
  char *suffix;

  int  i;

  if (argc < 2) {
    fprintf(stderr, "Usage: texindex index1, index2, ...\n");
    exit (1);
  }

  for(i=1; i < argc; i++) {
    in_index = argv[i];
    suffix = strrchr(in_index, '.');

    if (suffix == NULL || strlen(suffix) != 3) {
       fprintf(stderr, "%s is not an index file for Texinfo.\n", in_index);
       exit(1);
    }

    strcpy(out_index, in_index);
    strcat(out_index, "s");
    strcpy(mednam1, tmpnam);
    strcat(mednam1, suffix);

    /* use iconv to change into sjis */
    strcpy(cmdline, "iconv -c -f UTF-8 -t CP932 ");
    strcat(cmdline, in_index);
    strcat(cmdline, " >");
    strcat(cmdline, mednam1);
    system(cmdline);

    /* apply ptexindex to the changed file */
    strcpy(cmdline, "ptexindex ");
    strcat(cmdline, mednam1);
    system(cmdline);

    /* medname2 is the generated file */
    strcpy(mednam2, mednam1);
    strcat(mednam2, "s");

    /* change medname2 into utf-8 to obtain necessary out_index */
    strcpy(cmdline, "iconv -c -f CP932 -t UTF-8 ");
    strcat(cmdline, mednam2);
    strcat(cmdline, " >");
    strcat(cmdline, out_index);
    system(cmdline);

    /* remove temporary files */
    remove(mednam1);
    remove(mednam2);
  }
  return 0;
}
