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

#include "udmf.h"
#include "grp.h"

FILE *grp;
header_ header;
lump_* lumplist;

vertex_ vertices[16384];
linedef_ linedefs[8192];
dsector_ dsectors[1024];

int vindex = 0;
int lindex = 0;

int lump_byname(const char* name)
{
    int x;
    for(x=0;x<header.file_count;x++)
        if(strncmp(lumplist[x].name, name, 12) == 0)
            return x;
    return -1;
}

long get_offset(int id)
{
    int x;
    long offset = sizeof(header_) + (header.file_count * sizeof(lump_));
    for(x=0;x<header.file_count;x++)
        if(x != id)
            offset += lumplist[x].lsize;
        else
            return offset;
    return -1;
}

int main()
{
    //PARSE BASIC INFO
    grp = fopen("D:\\Bohdan\\Projects\\map2udmf\\bin\\duke3d.grp", "rb");
    fread(&header, sizeof(header_), 1, grp);

    printf("sig: %.12s\n", header.signature);
    printf("files: %ld\n", header.file_count);

    lumplist = (lump_*)malloc(header.file_count * sizeof(lump_));

    int x;
    for(x=0;x<header.file_count;x++)
    {
        fread(&lumplist[x], sizeof(lump_), 1, grp);
        printf("file %i: %.12s %ld\n", x, lumplist[x].name, lumplist[x].lsize);
    }
    //READ MAP
    fseek(grp, get_offset(lump_byname("E1L1.MAP")), SEEK_SET);

    long map_ver;
	fread(&map_ver, sizeof(long), 1, grp);

    long xp, yp, zp;
    fread(&xp, sizeof(long), 1, grp);
    fread(&yp, sizeof(long), 1, grp);
    fread(&zp, sizeof(long), 1, grp);

    short angle, cur_sec;
    fread(&angle, sizeof(short), 1, grp);
    fread(&cur_sec, sizeof(short), 1, grp);

	short num_sec;
	sector_ sectors[1024];
	fread(&num_sec, sizeof(short), 1, grp);
	for(x=0;x<num_sec;x++)
        fread(&sectors[x], sizeof(sector_), 1, grp);

    short num_walls;
	wall_ walls[8192];
	fread(&num_walls, sizeof(short), 1, grp);
	for(x=0;x<num_walls;x++)
        fread(&walls[x], sizeof(wall_), 1, grp);

	short num_sprites;
	sprite_ sprites[4096];
	fread(&num_sprites, sizeof(short), 1, grp);
	for(x=0;x<num_sprites;x++)
        fread(&sprites[x], sizeof(sprite_), 1, grp);

    //CONVERT TO UDMF
    for(x=0;x<num_sec;x++)
    {
        int y;
        int wi = sectors[x].wallptr;
        for(y=0;y<sectors[x].wallnum;y++)
        {
            vertices[vindex].x = (float)walls[wi].x;
            vertices[vindex].y = (float)walls[wi].y;
            linedefs[lindex].v1 = vindex;
            vindex++;

            wi = walls[wi].point2;
        }
    }

    fclose(grp);
    return 0;
}
