/* a file copier routine */
#include <windows.h>
#include <stdio.h>
#define BUFSIZE 100

/************ function prototypes *************/
void CheckArgs(int, char **, LPHANDLE, LPHANDLE);
void CopyFile(HANDLE, HANDLE, char[], char []);
char *GetErrorMessage();


/*********** MAIN **************/
int main(int argc, char *argv[])
{
	 HANDLE h1, h2;
	 CheckArgs(argc, argv, &h1, &h2);
	 CopyFile(h1,h2,argv[1], argv[2]);
	 return 0;
}

/******* CHECKARGS **************************/
void CheckArgs(int argc, char *argv[], LPHANDLE h1, 
               LPHANDLE h2)
{
	char in;
	 if (argc != 3) {
		 printf("usage %s sourcefile destfile\n",
                        argv[0]);
		 exit(0);
	 }

	 *h1 = CreateFile(argv[1],GENERIC_READ,0,NULL,
                          OPEN_EXISTING,0,NULL);
	 if (*h1 == INVALID_HANDLE_VALUE) {
	     printf("Error, could not open the file %s, error code %d: %s\n",
		argv[1], GetLastError(), GetErrorMessage());
	     exit(0);
	 }
	 *h2 = CreateFile(argv[2],GENERIC_WRITE,0,NULL,
                     CREATE_NEW, 0,NULL);
	 if (*h2 == INVALID_HANDLE_VALUE) {
	    printf("File %s already exists, do you want to overwrite (y or n)?\n",
			 argv[2]);
         in = getchar();
		 if (in == 'y' || in == 'Y')
              *h2 = CreateFile(argv[2],GENERIC_WRITE,0,
                    NULL, CREATE_ALWAYS, 0, NULL);
		 else {
			 printf("Good bye!\n");
		     exit(0);
		 }
	 }
}

/***************** COPYFILE ************************/
void CopyFile(HANDLE h1, HANDLE h2, char infile[], 
             char outfile[])
{
	 DWORD n, numbytes;
	 char buffer[BUFSIZE];
	 int count;
 
	 count = 0;
	 while (ReadFile(h1,buffer,BUFSIZE,&numbytes,NULL)) {
		 if (numbytes == 0) break;
		 count += numbytes;
		 WriteFile(h2,buffer,numbytes,&n,NULL);
		 if (n != numbytes) {
		      printf("Error writing to the file %s;%s\n",
                              outfile, GetErrorMessage());
		      exit(0);
		 }	 
	 }
	 printf("%d bytes were copied to the file %s, good bye\n",
                count, outfile);
}
 
/****  GETERRORMESSAGE **************/
char  *GetErrorMessage() 
{
    char *ErrMsg;
        FormatMessage( 
             FORMAT_MESSAGE_ALLOCATE_BUFFER | 
             FORMAT_MESSAGE_FROM_SYSTEM |              
                         FORMAT_MESSAGE_IGNORE_INSERTS,
             NULL,
             GetLastError(),
             MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
             (LPTSTR) &ErrMsg,
             0,
             NULL 
        );
        return ErrMsg;
}

