//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------

#include <stdio.h>

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

	int ret;
	size_t size;

	// check the correct number of parameters

	if (argc != 5) {
		printf("Usage: blkcopy <input file> <offset> <length> <output file>\n");
		return -1;
	}

	// read block from input

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

	int offset;
	ret = sscanf(argv[2], "%d", &offset);
	if (!ret) {
		printf("Bad argument (number expected).\n");
		return -1;
	}

	int length;
	ret = sscanf(argv[3], "%d", &length);
	if (!ret) {
		printf("Bad argument (number expected).\n");
		return -1;
	}

	ret = fseek(fr, offset, SEEK_SET);
	if (ret) {
		printf("Seek operation failed.\n");
		return -1;
	}

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

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

	fclose(fr);

	// write block to output

	FILE *fw = fopen(argv[4], "wb");
	if (!fw) {
		free(block);
		printf("Cannot open output file.\n");
		return -1;
	}

	size = fwrite(block, 1, length, fw);
	if (size != length) {
		free(block);
		printf("Write operation failed.\n");
		return -1;
	}

	free(block);
	fclose(fw);

	return 0;
}
