/* ptex2xindy.c: A filter to transform the output of tex2xindy into a form
                 suitable for platex and uplatex.

   Copyright 2014 Akira Kakuto.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public License
   along with this library; if not, see <http://www.gnu.org/licenses/>.  */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#endif

#define BUFFLEN 1024
#define READLEN 1022
#define WORDLEN  256

int main(int argc, char *argv[])
{
  char ibuf[BUFFLEN];
  char obuf[BUFFLEN];
  char key[WORDLEN];
  char prt[WORDLEN];
  int  isq = 0;
  int  isp = 0;

  char *p, *q, *r;
  char *kp, *pp;

#ifdef _WIN32
  _setmode(fileno(stdout), _O_BINARY);
#endif

  while(fgets(ibuf, READLEN, stdin)) {
    p = strstr(ibuf, ":tkey");
    if(p == NULL)
      strcpy(obuf, ibuf);
    else {
      q = ibuf;
      r = obuf;
      while(q < p)
        *r++ = *q++;
      while(*q != '(')
        *r++ = *q++;
      *r++ = *q++;
      isp++;
      while(isp) {
        if(*q == '(') {
          *r++ = *q++;
          isp++;
        } else if(*q == ')') {
          *r++ = *q++;
          isp--;
        } else if(isp == 2 && isq == 0 && *q == '\"') {
          kp = key;
          isq++;
          *kp++ = *q++;
          while(*q != '\"')
            *kp++ = *q++;
          *kp++ = *q++;
          isq--;
          *kp = '\0';
          while(*q == ' ' || *q == '\t')
            q++;
          if(*q != '\"') {
            kp = key;
            while(*kp)
              *r++ = *kp++;
          } else {
            pp = prt;
            *pp++ = *q++;
            isq++;
            while(*q != '\"')
              *pp++ = *q++;
            *pp++ = *q++;
            isq--;
            *pp = '\0';
            key[strlen(key)-1] = '\0';
            pp = prt;
            pp++;
            strcat(key, pp);
            kp = key;
            while(*kp)
              *r++ = *kp++;
            *r++ = ' ';
            pp = prt;
            while(*pp)
              *r++ = *pp++;
          }
        } else {
          *r++ = *q++;
        }
      }
      while(*q)
        *r++ = *q++;
      *r = '\0';
    }
    fputs(obuf, stdout);
  }
  return 0;
}
