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

#define BUFSIZE 16384

int process (int inhandle, int outhandle, long pos)
{
  char buffer[BUFSIZE];
  lseek(inhandle, pos, SEEK_SET);
  lseek(outhandle, pos, SEEK_SET);

  read(inhandle, buffer, BUFSIZE);
  write(outhandle, buffer, BUFSIZE);
}

int main(int argc, char *argv[])
{
  char srcfilename[1024], destfilename[1024];
  int inhandle=0, outhandle=0;
  long size=0L, pos=0L;

  if(argc<2) {
    fprintf(stderr, "Erkle, give me more filenames to play with!\n");
    exit(-1);
  }

  strcpy(srcfilename, argv[1]);
  strcpy(destfilename, argv[2]);

  printf("Copying from the end of [%s] to [%s]...\n", 
	 srcfilename, destfilename);

  inhandle=open(srcfilename, O_RDONLY);
  if(inhandle<0) {
    fprintf(stderr, "Erkle, error opening %s\n", srcfilename);
    exit(-2);
  }

  outhandle=open(destfilename, O_RDWR);
  if(outhandle<0) {
    fprintf(stderr, "Erkle, error opening %s\n", destfilename);
    exit(-3);
  }

  size=lseek(inhandle, 0, SEEK_END); /* make a note of the size of the file */
  pos=size;

  do {
    pos-=BUFSIZE;

    process(inhandle, outhandle, pos);
    printf("Position: %ld\n", pos);

  }while(pos>0L);
  /* cater for the 0-position option as well */
  process(inhandle, outhandle, 0L);

  close(outhandle);
  close(inhandle);

  printf("All done!\n");

  return 0;
}
