//-----------------------------------------------------------------------------
// FATware - firmware and file system driver for ZX Spectrum divIDE interface
// Copyright (c) 2005-2009 Milos Bazelides (baze)
//-----------------------------------------------------------------------------
// This software is provided "as is" without warranties or conditions of any
// kind, either express or implied. In no event shall the author(s) be held
// liable for any damages arising from the use of this software.
// See accompanying "licence.txt" file for copyright and terms of use.
//-----------------------------------------------------------------------------
// This utility converts a binary file to a sequence of DB statements that can
// be included into source files (useful for assemblers which don't support
// binary include).
//-----------------------------------------------------------------------------

#include <stdio.h>

int main(int argc, char **argv) {

	int i, j;

	if (argc != 3) {
		printf("Usage: bin2asm <input file> <length> [> <output>]\n");
		return -1;
	}

	FILE *fr = fopen(argv[1], "rb");
	if (!fr) {
		printf("Cannot open input file.\n");
		return -1;
	}

	int length = atoi(argv[2]);
	if (!length) {
		printf("Bad argument (number expected).\n");
		return -1;
	}

	unsigned char *buffer = malloc(length);
	if (!buffer) {
		printf("Not enough memory.\n");
		return -1;
	}

	size_t size = fread(buffer, 1, length, fr);
	if (size != length) {
		free(buffer);
		printf("Read operation failed.\n");
		return -1;
	}

	fclose(fr);
	unsigned char *p = buffer;
	int numLines = length >> 3;

	for (i = 0; i < numLines; i++) {
		printf("\tdb\t");
		for (j = 0; j < 7; j++) {
			printf("%03Xh, ", *p++);
		}
		printf("%03Xh\n", *p++);
	}

	int trail = length & 7;
	if (trail) {
		printf("\tdb\t");
		for (j = 0; j < trail - 1; j++) {
			printf("%03Xh, ", *p++);
		}
		printf("%03Xh\n", *p++);
	}

	free(buffer);
	return 0;
}
