/*
  Released as open source in Feb 2003
  Richard Atterer <richard
  at atterer.net>

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

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

  ______________________________________________________________________
  __   _
  |_) /|  Copyright Richard Atterer <atterer@augsburg.baynet.de>
  | \/|  written on 04-10-1997
   ` 
  Get a line of ForeignNew
  Search for the first line in ForeignOld which has the same value (but not
    necessarily the same token(s)).
  If same value found, replace with text from MyOld
  If not found, output as in ForeignNew

  Files mustn't contain zero bytes, else 'performance is sub-optimal'...
  Cannot use this for Message files with more than one occurence of a token.

  Syntax: MsgUpdate <ForeignOld> <ForeignNew> <MyOld> <MyNew>

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "os.h"
#include "fileswitch.h"
#include "osfile.h"

#define VERSION "V1.00 (17\x1fOct\x1f""1997)"
#define BUFSIZE 1024
#define OPT_ForeignOld 1
#define OPT_ForeignNew 2
#define OPT_MyOld      3
#define OPT_Output     4


char *load(char *file,int *size);


static char NoMem[] = "Out of memory.\n\r";
static struct os_error *error;
int a, fosize, mosize;
char *clistring, *buf, *fobuf, *mobuf, *b;
FILE *get, *put;


int main (void) {
  clistring = os_get_env(NULL,NULL);
  /* os_write0("Command: ");
  os_write0(clistring);
  os_new_line(); */

  buf = malloc(BUFSIZE);
  if (buf == NULL) { fprintf(stderr,NoMem); exit(1); }

  if ((error = xos_read_args("/a,foreignold=fo/a,foreignnew=fn/a,myold=mo/a"
      ",output/a",clistring,buf,BUFSIZE,NULL))) {
    os_pretty_print(
    "\x1f__\x1f\x1f\x1f_\r"
    "\x1f|_)\x1f/| \x1fRichard Atterer <atterer@augsburg.baynet.de>\r"
    "\x1f|\x1f\\/| MsgUpdate " VERSION "\r"
    "\x1f\x1f`\x1f\r"
  /*"This makes updating the translation of a Messages file into another "
    "language easier.\rInput is the old and new versions of the file "
    "in the foreign language as well as your translation of the old file.\r"
    "Outputs a file with the same tokens as the new version of the "
    "foreign file, but with all unchanged message values substituted with "
    "your translation. Messages that appear only in the new file are "
    "preceded with  to make them stand out, and if the same *token* "
    "exists in your translation of the old file, its value is output in a "
    "seperate line preceded with #\x1f.\r"*/
    "Syntax: *MsgUpdate [-ForeignOld]|[-fo] <filename> [-ForeignNew]|[-fn] "
    "<filename> [-MyOld]|[-mo] <filename> [-Output]|[-o] <filename>\r"
    ,0,NULL);
    return 0;
  }

  /*os_write0("Argument#1: ");
  os_write0(*(char **)(buf+4));
  os_write0("\n\rArgument#2: ");
  os_write0(*(char **)(buf+8));
  os_write0("\n\rArgument#3: ");
  os_write0(*(char **)(buf+12));
  os_write0("\n\rArgument#4: ");
  os_write0(*(char **)(buf+16));
  os_new_line();*/

  /* load ForeignOld & MyOld */
  fobuf = load(*(char **) (buf+OPT_ForeignOld*4),&fosize);
  if (fobuf == NULL) goto finish;
  mobuf = load(*(char **)(buf+OPT_MyOld*4),&mosize);
  if (mobuf == NULL) goto finish;

  /* printf("fosize=%d, mosize=%d\n",fosize,mosize); */

  get = fopen(*(char **)(buf+OPT_ForeignNew*4),"r");
  if (get == NULL) {
    fprintf(stderr,"Couldnt open %s for reading.\n",
      *(char **)(buf+OPT_ForeignNew*4));
    exit(1);
  }

  put = fopen(*(char **)(buf+OPT_Output*4),"w");
  if (put == NULL) {
    fprintf(stderr,"Couldnt open %s for writing.\n",
      *(char **)(buf+OPT_Output*4));
    exit(1);
  }


  b = fgets(buf,BUFSIZE,get);

  while (b != NULL) {
    if ((buf[0] == '#') || (buf[0] == 10) || /* skip empty lines/comments */
      ((b = strchr(buf,':')) == NULL) ) { /* if b == NULL, is one of several
                                    tokens spread over more than one line */
      if ((a = fputs(buf,put))) exit(1);
    }
    else {
      char *c, *d;
      if ((c = strstr(fobuf,b))) {    /* c => ":ValueInForeignOld<...>" */
        char tempchar;
        tempchar = c[1];
        c[1] = 0;                     /* overwrite char after ':' */
        d = c - 1;
        do {} while (*d-- != 10);     /* d => "?<10>TokenInForeignOld:" */
        d = strstr(mobuf,++d);        /* d => "<10>TokenInMyOld:<...>" */
        c[1] = tempchar;
        if (d == NULL) {
          /* didn't find token in MyOld that exists in ForeignOld, i.e. the
             Old files are inconsistent - output original ForeignNew line */
          if ((a = fputc('',put)) == 0) exit(1);
          if ((a = fputs(buf,put))) exit(1);
        }
        else {
          /* first output the token without the ':' as in ForeignNew */
          *b = 0;
          if ((a = fputs(buf,put))) exit(1);
          /* now write the translation of the ForeignNew value */
          d = strchr(d,':');
          a = fwrite(d,sizeof(char),strchr(d,10)-d+1,put);
        }
      }
      else {
        if ((a = fputc('',put)) == 0) exit(1);
        if ((a = fputs(buf,put))) exit(1);
      }
    }
    b = fgets(buf,BUFSIZE,get);
  }


  fclose(put);
  fclose(get);

  return 0;


  finish:
  fprintf(stderr,error->errmess);
  os_new_line();
  free(buf);
  exit(1);
}

/* mallocate a block of memory and load file into it */
char *load(char *file,int *size) {
  char *buf;
  /* read size */
  if ((error = xosfile_read_stamped_no_path(file,
    &a,NULL,NULL,size,NULL,NULL))) return NULL;
  if ((a == 0) || (a == 2)) {
    fprintf(stderr,"File %s not found.\n",file); exit(1); }
  /* load */
  buf = malloc(1 + *size);
  if (buf == NULL) { fprintf(stderr,NoMem); exit(1); }
  if ((error = xosfile_load_stamped_no_path(file,
    buf + 1,NULL,NULL,NULL,NULL,NULL))) return NULL;
  buf[0] = 10; /* there must be a NL before the 1st token */
  return buf;
}
