#include <stdint.h>
#include <stdlib.h>

#include "fs_private.h"

int32_t FS_FileCompare(const char *path1, const char *path2)
{
    FILE *file1;
    FILE *file2;
    long savedOffset;
    int32_t file1Length;
    int32_t file2Length;
    char *buffer1;
    char *buffer2;
    char *cursor1;
    char *cursor2;
    int32_t index;
    int32_t result;
    size_t transferCount;

    file1 = fopen(path1, "rb");
    if (file1 == NULL) {
        Com_Error(0, "\x15" "FS_FileCompare: %s does not exist\n", path1);
    }

    file2 = fopen(path2, "rb");
    if (file2 == NULL) {
        fclose(file1);
        result = 0;
    } else {
        savedOffset = ftell(file1);
        fseek(file1, 0, SEEK_END);
        file1Length = (int32_t)ftell(file1);
        fseek(file1, savedOffset, SEEK_SET);

        savedOffset = ftell(file2);
        fseek(file2, 0, SEEK_END);
        file2Length = (int32_t)ftell(file2);
        fseek(file2, savedOffset, SEEK_SET);

        if (file1Length == file2Length) {
            buffer1 = Z_Malloc((size_t)(uint32_t)file1Length);
            transferCount =
                fread(buffer1, 1, (size_t)(uint32_t)file1Length, file1);
            if (transferCount != (size_t)(uint32_t)file1Length) {
                Com_Error(0, "\x15" "Short read in FS_FileCompare()\n");
            }
            fclose(file1);

            buffer2 = Z_Malloc((size_t)(uint32_t)file2Length);
            transferCount =
                fread(buffer2, 1, (size_t)(uint32_t)file2Length, file2);
            if (transferCount != (size_t)(uint32_t)file2Length) {
                Com_Error(0, "\x15" "Short read in FS_FileCompare()\n");
            }
            fclose(file2);

            cursor1 = buffer1;
            cursor2 = buffer2;
            for (index = 0; index < file1Length; index++) {
                if (*cursor1 != *cursor2) {
                    free(buffer1);
                    free(buffer2);
                    return 0;
                }
                cursor1++;
                cursor2++;
            }

            free(buffer1);
            free(buffer2);
            result = 1;
        } else {
            fclose(file1);
            fclose(file2);
            result = 0;
        }
    }

    return result;
}
