#include <stdlib.h>
#include <stdio.h>

void usage_print(char *program)
{
	if (program == NULL)
		return;

	printf("Usage: %s [SRC] [DST]\n", program);
}

int copy(char *src, char *dst)
{
	unsigned int chunk = 512;
	unsigned int count;
	unsigned int length;
	FILE *stream[2] = { NULL };
	char *buffer = NULL;
	int rc;

	if (src == NULL || dst == NULL)
		return -1;

	stream[0] = fopen(src, "r");
	if (stream[0] == NULL) {
		fprintf(stderr, "Unable to open file: %s\n", src);
		goto error;
	}

	stream[1] = fopen(dst, "w");
	if (stream[1] == NULL) {
		fprintf(stderr, "Unable to open file: %s\n", dst);
		goto error;
	}

	buffer = calloc(1, chunk);

	do {
		rc = fread(buffer, 1, chunk, stream[0]);
		if (ferror(stream[0])) {
			fprintf(stderr, "Unable to read data from file: %s\n", src);
			goto error;
		}

		if (rc == 0 && feof(stream[0]))
			break;

		count = rc;

		rc = fwrite(buffer, 1, count, stream[1]);
		if (ferror(stream[1])) {
			fprintf(stderr, "Unable to read data from file: %s\n", dst);
			goto error;
		}
	} while (!feof(stream[0]));


	rc = 0;
	goto complete;

error:
	rc = -1;

complete:
	if (stream[0] != NULL)
		fclose(stream[0]);

	if (stream[1] != NULL)
		fclose(stream[1]);

	if (buffer != NULL)
		free(buffer);

	return rc;
}

int main(int argc, char *argv[])
{
	char *src;
	char *dst;
	int rc;

	if (argc < 3) {
		usage_print(argv[0]);
		return 1;
	}

	src = argv[1];
	dst = argv[2];

	rc = copy(src, dst);
	if (rc < 0) {
		fprintf(stderr, "FIle copy failed\n");
		return 1;
	}

	return 0;	
}
