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

#define BLOCK_SIZE 4096

int main(int argc, char* argv[]) {
    if (argc != 3) {
        fprintf(stderr, "Usage: simple-block-compare FILE1 FILE2\n");
        exit(EXIT_FAILURE);
    }
    int fd1 = open(argv[1], O_RDONLY);
    if (fd1 == -1) {
        fprintf(stderr, "simple-block-compare: Couldn't open '%s'\n", argv[1]);
        exit(EXIT_FAILURE);
    }
    int fd2 = open(argv[2], O_RDONLY);
    if (fd2 == -1) {
        fprintf(stderr, "simple-block-compare: Couldn't open '%s'\n", argv[2]);
        exit(EXIT_FAILURE);
    }
    char block1[BLOCK_SIZE], block2[BLOCK_SIZE];
    int n1, n2;
    int n = 0;
    while ((n1 = read(fd1, block1, BLOCK_SIZE)) > 0) {
        n2 = read(fd2, block2, n1);
        if (n1 != n2) {
            fprintf(stderr, "simple-block-compare: Not the same length\n");
            exit(EXIT_FAILURE);
        }
        else if (memcmp(block1, block2, n1) != 0) {
            printf("Different in block number %d.\n", n);
            return EXIT_SUCCESS;
        }
        ++n;
    }
    if (read(fd2, block2, 1) != 0) {
        fprintf(stderr, "simple-block-compare: Not the same length\n");
        exit(EXIT_FAILURE);
    }
    printf("Same.\n");            

    return EXIT_SUCCESS;
}
