#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <netinet/in.h>

struct header {
	char magic[7];
	uint16_t dummy1;
	char name[12];
	uint32_t len;
	uint32_t zero;
	uint8_t flag;
} __attribute__((packed));

struct preamble {
	char magic[10];
	uint8_t len;
} __attribute__((packed));

main()
{
	FILE *f = fopen("../SU-18_0.2005.40-18_PR_F5_MR0_ARM.bin", "r");
	FILE *g = fopen("SU-18_0.2005.40-18_PR_F5_MR0_ARM.bin", "w+");
	struct header h;
	struct preamble p;
	char *title;
	fseek(f, 0, SEEK_END);
	int flen = ftell(f);
	fseek(f, 0, SEEK_SET);

	fread(&p, sizeof(p), 1, f);
	fwrite(&p, sizeof(p), 1, g);
	title = malloc(p.len);
	fread(title, 1, p.len, f);
	fwrite(title, 1, p.len, g);
	
	printf("package title = %s\n", title);

	free(title);

	while (ftell(f) < flen) {
		char dump[16];
		FILE *o;
		char buffer[4096];
		int i;

		fread(&h, sizeof(h), 1, f);
		fwrite(&h, sizeof(h), 1, g);
		printf("block = %s, len = %d, dummy = %02x, flag = %02x\n",
				h.name, ntohl(h.len), (int)h.dummy1, h.flag);
		sprintf(dump, "%s.dmp", h.name);
		o = fopen(dump, "r");
		i = ntohl(h.len);
		while (i > 0) {
			int r = (i < 4096 ? i : 4096);
			fread(buffer, 1, r, o);
			fwrite(buffer, 1, r, g);
			i -= r;
		}
		fclose(o);
		fseek(f, ntohl(h.len), SEEK_CUR);
	}

	fclose(f);
	fclose(g);
}
