/* makes a copy of a file, (Unix cp command) */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#define BUFSIZE 100
extern int errno;

/***** function prototypes **/
void ArgChecker(int, char **, int *, int *);
void CopyTheFile(int, int, char[], char[]);


/******** MAIN *****************/
int main(int argc, char *argv[])
{
    int fd1, fd2;

    ArgChecker(argc, argv, &fd1, &fd2);
    CopyTheFile(fd1, fd2, argv[1], argv[2]);
    return 0;
}

/******  ARGCHECKER ******************
  Verifies arguments and confirms that
  files can be opened.  It returns only
  if files were successfully opened.
************************************/
void ArgChecker(int argc, char *argv[], int *fd1, int *fd2)
{
  char in;
  char errmsg[256];
    if (argc != 3) {
        printf("usage, %s sourcefile destfile\n",argv[0]);
        exit(0);
    }

    *fd1 = open(argv[1],O_RDONLY);
    if (*fd1 < 0) {
        sprintf(errmsg, "error opening the file %s",argv[1]);
        perror(errmsg);
        exit(0);
    }
    * fd2 = open(argv[2],O_WRONLY | O_CREAT | O_EXCL, 
                 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    if (*fd2 < 0) {
        if (errno == EEXIST) {
            printf("The file %s exists, ",argv[2]);
            printf("do you want to overwrite it (y or n)?\n");
            in = getchar();
            if (in == 'y' || in == 'Y') {
                *fd2 = open(argv[2],O_WRONLY | O_TRUNC, 
                     S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
            }
            else {
	        printf("Good bye!\n");
                exit(0);
	    }
	}
        else {
            sprintf(errmsg, "error, opening the file %s",
                   argv[2]);
            perror(errmsg);
            exit(0);
        }
    }        
}


/********* COPYTHEFILE **************/
void CopyTheFile(int fd1, int fd2, char infilename[], 
     char outfilename[])
{
  int count;
    ssize_t n;
    size_t numbytes;
    char buffer[BUFSIZE];
    char errmsg[128];

    count = 0;
    n = read(fd1,buffer,BUFSIZE);
    while (n > 0) {
      if (n < 0) {
           sprintf(errmsg,"Error reading from file %s\n",
                  infilename);
           perror(errmsg);
           exit(0);
       }
       count += n;
       numbytes = (size_t) n;
       n = write(fd2,buffer, numbytes);
       if (n != numbytes) {
           sprintf(errmsg,"Error writing to the file %s\n",
                  outfilename);
           perror(errmsg);
           exit(0);
       }
       n = read(fd1,buffer, BUFSIZE);
    }
    if (n < 0) {
           sprintf(errmsg,"Error writing to the file %s\n",
                  infilename);
           perror(errmsg);
           exit(0);
       }
       printf("%d bytes were copied to %s. Good bye!\n",
               count, outfilename);
}







