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

#define MLEN 999

char dir[MLEN];

void ReadFile( char *fpath, int *blen, char **buf )
{
  FILE *F = fopen(fpath, "rb");

  fseek(F, 0, SEEK_END);
  *blen = ftell(F);
  rewind(F);

  *buf = (char *)malloc(*blen);
  fread(*buf, *blen, 1, F);
  fclose(F);
}

void WriteFile( char *fpath, int blen, char *buf )
{
  FILE *F = fopen(fpath, "wb");
  fwrite(buf, blen, 1, F);
  fclose(F);
}

void Change( int *len, char **buf, char *s1, char *s2 )
{
  int cnt = 0, i, j, n1 = strlen(s1), n2 = strlen(s2);

//  printf("%s --> %s\n", s1, s2);

  for (i = 0; i + n1 <= *len; i++)
  {
    for (j = 0; j < n1; j++)
      if ((*buf)[i + j] != s1[j])
        break;
    if (j < n1)
      continue;

    for (j = i; j + n1 < *len; j++)
      (*buf)[j] = (*buf)[j + n1];
    *len -= n1;
    
    (*buf) = (char *)realloc((*buf), *len + n2);

    for (j = *len - 1; j >= i; j--)
      (*buf)[j + n2] = (*buf)[j];
    for (j = 0; j < n2; j++)
      (*buf)[i + j] = s2[j];
    *len += n2;
    cnt++;
  }
  printf("%d strings were changed\n", cnt);
}

void Process( char *fname )
{
  char *buf, *fpath;
  int len;

  fpath = (char *)malloc(strlen(fname) + 10);
  sprintf(fpath, "bin\\%s", fname);

  ReadFile(fpath, &len, &buf);
  Change(&len, &buf, "%%path%%", dir);
  WriteFile(fpath, len, buf);

  free(fpath);
  free(buf);
}

void InsertPath( char *fpath, int pos, char *s )
{
  char *buf;
  int i, j, len, slen = strlen(s);

  for (i = 0; i < slen; i++)
    if (s[i] == '\\')
    {
      j = i + 1;
      while (j < slen && s[j] != '\\')
        j++;
      if (j - (i + 1) > 8)
      {
        printf("InsertPath failed: path=%s, it contains too long names (maxlength=8)\n", s);
        break;
      }
    }

  ReadFile(fpath, &len, &buf);
  for (i = 0; i < slen; i++)
    buf[pos + i] = s[i];
  buf[pos + i] = 0;
  WriteFile(fpath, len, buf);

  free(buf);
}

int main( void )
{
  struct _finddata_t fdata;
  long hFile;
  int pos;

  getcwd(dir, MLEN);

  printf("--------------------> Patch bin\\*.cfg files\n");

  hFile = _findfirst("bin\\*.cfg", &fdata);
  if (hFile != -1)
  {
    do
    {
      printf("Process file: %s\n", fdata.name);
      Process(fdata.name);
    } while (_findnext(hFile, &fdata) == 0);
  
    _findclose(hFile);
  }

  printf("--------------------> Patch bin\\tcdef.dpr files\n");

  pos = strlen(dir);
  sprintf(dir + pos, "\\INCLUDE");
  InsertPath("bin\\tcdef.dpr", 0x388, dir);
  sprintf(dir + pos, "\\LIB");
  InsertPath("bin\\tcdef.dpr", 0x40C, dir);

  printf("--------------------> COMPLETED SUCCESSFUL\n");

  return 0;
}
