#include "coff.h"
#include "tcc.h"


static int
read_mem(int fd, unsigned offset, void *buffer, unsigned len)
{
	lseek(fd, offset, SEEK_SET);
	return len == read(fd, buffer, len);
}

int
coff_load_lib(TCCState *s1, int fd)
{
	return (0);
}

static int
coff_merge_or_create(void)
{
	return (0);
}

static int
coff_resolve_symbols(void)
{
	return (0);
}

int
coff_load_obj(TCCState *s1, int fd)
{
	FILHDR hdr;
	SCNHDR *scns;
	SYMENT *syments;
	RELOC *relocs;
	Section *s;
	uint16_t i;
	int32_t j;
	int k;
	char buff[9];

	if (!read_mem(fd, 0, &hdr, FILHSZ))
		return (tcc_error_noabort("not a coff object file"));

	if (hdr.f_magic != F_MACH_I386 || hdr.f_flags & F_EXEC)
		return (tcc_error_noabort("invalid coff object file"));

	/* read sections */
	scns = tcc_malloc(SCNHSZ * hdr.f_nscns);
	if (!read_mem(fd, FILHSZ, scns, SCNHSZ * hdr.f_nscns))
	{
		tcc_free(scns);
		return (-1);
	}

	for (i = 0; i < hdr.f_nscns; i++)
	{
		memset(buff, 0, 9);
		memcpy(buff, scns[i].s_name, 8);
		printf("sec: %s\n", buff);

		for (k = 1; k < s1->nb_sections; k++)
		{
			if (strcmp(s1->sections[k]->name, buff) != 0)
			{
				continue;
			}


		}

	}

	/* load symtab */
	syments = tcc_malloc(SYMESZ * hdr.f_nsyms);
	read_mem(fd, hdr.f_symptr, syments, SYMESZ * hdr.f_nsyms);
	for (j = 0; j < hdr.f_nsyms; j++)
	{
		memset(buff, 0, 9);
		memcpy(buff, syments[j].n_name, 8);
		printf("sym: %s\n", buff);
	}

	tcc_free(syments);
	tcc_free(scns);
	return (0);
}

int
coff_load_file(TCCState *s1, int fd, const char *fname)
{
	if (strcmp(tcc_fileextension(fname), ".a") == 0)
	{
		return (coff_load_lib(s1, fd));
	}
	else
	{
		return (coff_load_obj(s1, fd));
	}
}

int
coff_output_file(TCCState *s1, const char *fname)
{
	return (0);
}