/*
Copyright (c) 2010, Dirk Krause
All rights reserved.

Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions are met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.
* Redistributions in binary form must reproduce the above 
  opyright notice, this list of conditions and the following
  disclaimer in the documentation and/or other materials
  provided with the distribution.
* Neither the name of the Dirk Krause nor the names of
  contributors may be used to endorse or promote
  products derived from this software without specific
  prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/

#include "dk.h"

#include <stdio.h>

#if DK_HAVE_STRING_H
#include <string.h>
#endif

#if DK_HAVE_STRINGS_H
#include <strings.h>
#endif

#if DK_HAVE_STDLIB_H
#include <stdlib.h>
#endif

#if DK_HAVE_UNISTD_H
#include <unistd.h>
#endif

#if DK_HAVE_PROCESS_H
#include <process.h>
#endif



static char str_includedir[] = { "includedir" };
static char str_libdir[] = { "libdir" };

static char dir_include[] = { DK_INCLUDEDIR };
static char dir_lib[] = { DK_LIBDIR };



#if DK_HAVE_PROTOTYPES
int main(int argc, char *argv[] )
#else
int main(argc, argv) int argc; char *argv[];
#endif
{
  int back = 0;
  FILE *inf;
  FILE *of;
  char buffer[8192], *p1, *p2, *p3;

  if(argc > 2) {
    inf = fopen(argv[1], "r");
    if(inf) {
      of= fopen(argv[2], "w");
      if(of) {
	while(fgets(buffer, sizeof(buffer), inf)) {
	  p1 = strchr(buffer, '@');
	  if(p1) {
	    p2 = p1; p2++;
	    p2 = strchr(p2, '@');
	    if(p2) {
	      *p1 = '\0'; *p2 = '\0';
	      p3 = p1; p3++;
	      if(strcmp(p3, str_includedir) == 0) {
		fputs(buffer, of);
		fputs(dir_include, of);
		p2++;
		fputs(p2, of);
	      } else {
		if(strcmp(p3, str_libdir) == 0) {
		  fputs(buffer, of);
		  fputs(dir_lib, of);
		  p2++;
		  fputs(p2, of);
		} else {
		  *p1 = '@'; *p2 = '@';
		  fputs(buffer, of);
		}
	      }
	    } else {
	      fputs(buffer, of);
	    }
	  } else {
	    fputs(buffer, of);
	  }
	}
	fclose(of);
      }
      fclose(inf);
    }
  }
  exit(back);
  return back;
}

