/*
 * d1rcpy
 * ----------------------------------------
 * d1s4st3r's direct raw copy program
 *
 */



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>


#define    STATBLEN    20


int filesize(FILE *fp);

struct stat stat_p;


int filesize(FILE *fp)
{
	int size;

	if (fp)
	{
		fseek(fp, 0, SEEK_END);
		size = ftell(fp);
		fseek(fp, 0, SEEK_SET);
	}
	else
		size = -1;

	return size;
}


int main(int argc, char *argv[])
{
	FILE *fin;
	FILE *fout;

	char *buf;

	size_t bytesread;
	size_t readsize;
	size_t totalbytes = 0;

	/* char statbstr[STATBLEN] = "                    ";     // use for meter 0%........100% one day :-)   */
	int fsize = 0;
	int peratom = 0;

	if (argc<3)
	{
		fprintf(stderr, "Usage: %s <infile> <outfile>\n", argv[0]);

		return EXIT_FAILURE;
	}
	else
	{
		if ((fin=fopen(argv[1], "rb"))==NULL)
		{
			fprintf(stderr, "Error opening file \"%s\" for input: %s\n", argv[1], strerror(errno));

			return errno;
		}
		else if ((fout=fopen(argv[2], "wb"))==NULL)
		{
			fprintf(stderr, "Error opening file \"%s\" for output: %s\n", argv[2], strerror(errno));

			return errno;
		}
		else
		{
			if ((fsize=filesize(fin))<0)
			{
				fprintf(stderr, "Error calculating size of file \"%s\"\n", argv[1]);

				return EXIT_FAILURE;
			}
			else
			{
				peratom = fsize / STATBLEN;
				buf = calloc(fsize, sizeof(char));
				readsize = peratom;
			}
		}
	}

	fprintf(stdout, "Copying \"%s\" to \"%s\"...\n", argv[1], argv[2]);

	while ((bytesread=fread(buf, 1, readsize, fin))!=0)
	{
		if (bytesread!=fwrite(buf, 1, bytesread, fout))
		{
			fprintf(stderr, "Error writing \"%s\": %s\n", argv[2], strerror(errno));
			break;
		}
		else
			totalbytes += bytesread;

		fprintf(stdout, "\r%d bytes copied (%d%%)", totalbytes, (totalbytes*100)/fsize);
		fflush(stdout);
	}

	fprintf(stdout, "\nTotal data: %.2f MBytes (%d bytes)\n", totalbytes/(1024.0*1024.0), totalbytes);

	fclose(fin);
	fclose(fout);

	return EXIT_SUCCESS;
}


