#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <errno.h>

int main(int argc, char* argv[]) {
	int	fd;
	int 	i;
	int	n;
	int totBytes;
	struct 	stat st;
	void*	addr;

	if (argc != 2) {
		printf("You forgot the file name!\n");
		exit(1);
	}

	if (stat(argv[1], &st) == -1) {
		printf("Stat error on file %s!\n", argv[1]);
		printf("Failed to get size!\n");
		exit(2);
	}

	fd = open(argv[1], O_RDONLY);
	if (fd == -1) {
		printf("File open error!\n");
		exit(3);
	}

	addr = (void*)mmap(NULL, st.st_size, PROT_READ, MAP_SHARED,
						fd, (off_t) 0);
	if (addr == NULL) {
		printf("Mmap failed!\n");
		(void) close(fd);
		exit(4);
	}

	/*for (i=0; i < st.st_size; i++)  {
		putchar (addr[i]);
	} */

	do {
		n = read(fd, (void*)addr, sizeof(addr));
		totBytes += n;
		printf("Read %d bytes.\n", totBytes);
	} while (n > 0);

	close(fd);
	
	printf("Last value of n was %d.\n", n);
	
	printf("The error value was: %d.\n", errno);
	printf("The possible values for error are:\n");
	printf("EBADF 	= %d\n", EBADF);
	printf("EFAULT 	= %d\n", EFAULT);
	printf("EINTR	= %d\n", EINTR);
	printf("EINVAL	= %d\n", EINVAL);
	printf("EIO	= %d\n", EIO);
	printf("EISDIR	= %d\n", EISDIR);

	if (munmap(addr, st.st_size) == -1) {
		printf("Error releasing mmap!\n");
		(void) close(fd);
		exit(5);
	}

	exit(0);

}

