#include <stdio.h>
#include <unistd.h>
#define DBREF_TOKEN '#'
#define BEGIN_MOVE "***Property list start ***"
#define END_MOVE "***Property list end ***\n"
void main(int argc, char **argv)
{
FILE *map, *data, *in, *out, *from;
long tmp[2];
long newdbref;
int state = 0;
int linecount;
long backtrack = 0;
long backtmp;
char buf[16384];
if (argc != 3)
{
fprintf(stderr, "Usage: unconvert <infile> <outfile>\n");
exit(1);
}
#define CHECKFILE(x) if ((x) == NULL) \
{ fprintf(stderr, "Trouble opening %s\n", buf); \
exit(1);}
sprintf(buf, "%s", argv[2]);
out = fopen(buf, "w+");
CHECKFILE(out);
sprintf(buf, "%s.map", argv[1]);
map = fopen(buf, "r+");
CHECKFILE(map);
sprintf(buf, "%s.dat", argv[1]);
data = fopen(buf, "r+");
CHECKFILE(data);
sprintf(buf, "%s", argv[1]);
in = fopen(buf, "r");
CHECKFILE(in);
fread((void *) tmp, sizeof(long), 2, map);
from = in;
while (fgets(buf, sizeof(buf), from) != NULL)
switch(state)
{
case 0:
fprintf(out, "%s", buf);
if(strncmp(buf, BEGIN_MOVE, strlen(BEGIN_MOVE)) == 0)
{
tmp[1] = fseek(map, sizeof(long) * 2 * (tmp[0] + 1), SEEK_SET);
fread((void *) tmp, sizeof(long), 2, map);
if (tmp[0] != -1L)
{
fseek(data, tmp[1], SEEK_SET);
from = data;
state = 1;
fgets(buf, sizeof(buf), from); /* chow 1 line */
}
else
{
tmp[0] = newdbref;
}
}
if(buf[0] == DBREF_TOKEN)
{
newdbref = atol(&(buf[1]));
if ((tmp[0] + 1) == newdbref)
tmp[0] = newdbref;
}
break;
case 1:
if (strcmp(buf, END_MOVE) == 0)
{
state = 0;
from = in;
}
else
{
fprintf(out, "%s", buf);
}
break;
default:
fprintf(stderr, "Bleugh!\n");
exit(1);
}
fclose(map);
fclose(data);
fclose(out);
fclose(in);
}