#include <mz.h>
#include <stdio.h>

#define m8 ((uint8_t*)m) // access mz by byte
uint32_t loadmz(mz* m, uint8_t* mem, uint32_t xsz, uint32_t seg, mz_start* z) {

	/*printf(
		"mz\t%04X\n"
		"bytes\t%u\n"
		"pages\t%u\n"
		"relsz\t%u\n"
		"len\t%u\n"
		"minall\t%u\n"
		"maxall\t%u\n"
		"ss\t%04X\n"
		"sp\t%04X\n"
		"sum\t%04X\n"
		"ip\t%04X\n"
		"cs\t%04X\n"
		"rel*\t%04X\n"
		"overlay\t%u\n"
		,m->mz
		,m->bytes
		,m->pages
		,m->relsz
		,m->len
		,m->minalloc
		,m->maxalloc
		,m->ss
		,m->sp
		,m->sum
		,m->ip
		,m->cs
		,m->rel
		,m->overlay
	);*/

	uint32_t sz = (((uint32_t)m->pages-1) << 9) + (m->bytes ? m->bytes : 512) - (m->len << 4);

	memcpy( // copy mz to memory
		mem + (seg << 4),
		m8 + (m->len << 4),
		sz
	);

	for(int i = 0; i < m->relsz; i++) *(uint16_t*)(
		mem +
		(seg << 4) +
		((uint32_t)m->r[i].segment << 4) +
		(uint32_t)m->r[i].offset
	) += seg;

	*z = (mz_start) {
		m->ss+seg,
		m->sp,
		m->ip,
		m->cs+seg
	};
}
