#include <iostream>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include "m3dme.h"
#include <stdio.h>
#define GLfloat float
#define GLint uint32_t
INCLUDE_FILE


using namespace std;
using namespace M3D;

M3DME_Header m3dm_header;
M3DME_Vertex_Data *m3dm_vertex_data;
M3DME_Index_Data *m3dm_index_data;

void convert()
{
	int vertex_count = sizeof(vertices)/sizeof(vertices[0]);
	int index_count = 3 * sizeof(face_indicies)/sizeof(face_indicies[0]);
	int face_count = index_count / 3;
	
	m3dm_header.vertex_data_size = vertex_count * sizeof(M3DME_Vertex_Data);
	m3dm_header.index_data_size = index_count * sizeof(M3DME_Index_Data);
	
	std::cout<<"Vertex count:"<<vertex_count<<std::endl;
	std::cout<<"Index count:"<<index_count<<std::endl;
	std::cout<<"Face count:"<<face_count<<std::endl;
	
	m3dm_vertex_data = new M3DME_Vertex_Data[vertex_count];
	m3dm_index_data = new M3DME_Index_Data[index_count];
	
	for(int a=0;a<face_count;a++)
	{
		printf("Converting: %06d of %06d\r", a, face_count);
		for(int j=0;j<3;j++)
		{
			int vertex_id = face_indicies[a][j];
			int normal_id = face_indicies[a][j+3];
			int texture_id = face_indicies[a][j+6];
			
			//Vertex coords
			m3dm_vertex_data[vertex_id].x=vertices[vertex_id][0];
			m3dm_vertex_data[vertex_id].y=vertices[vertex_id][1];
			m3dm_vertex_data[vertex_id].z=vertices[vertex_id][2];
			//Texture coords
			m3dm_vertex_data[vertex_id].u=textures[texture_id][0];
			m3dm_vertex_data[vertex_id].v=textures[texture_id][1];
			//Normal coords
			m3dm_vertex_data[vertex_id].n_x=normals[normal_id][0];
			m3dm_vertex_data[vertex_id].n_y=normals[normal_id][1];
			m3dm_vertex_data[vertex_id].n_z=normals[normal_id][2];
			
			m3dm_index_data[a*3+j].index=vertex_id;
		}
	}
	printf("\n");
}

int main(int argc, char *argv[])
{
	if(argc<2)
	{
		std::cerr<<"usage: "<<argv[0]<<" <output file>"<<std::endl;
		return 1;
	}
	M3DME model;
	
	m3dm_header.primitive_type = 0;
		
	convert();
	model.set_header(&m3dm_header);
	model.set_vertex_data( m3dm_vertex_data );
	model.set_index_data( m3dm_index_data );
	model.save( argv[1] );
	
	return 0;
}
