#include <stdint.h>

#include "fs_private.h"

int32_t FS_Write(const void *buffer, int32_t length,
                 int32_t handle)
{
    const unsigned char *cursor;
    FILE *file;
    uint32_t remaining;
    uint32_t bytesWritten;
    int zeroByteWrite;

    FS_CheckFileSystemStarted();

    if (handle == 0) {
        return 0;
    }

    /* ORIGINAL_BINARY_BUG: negative VM byte counts become the original
     * unsigned dword transfer extent; see
     * original-bugs/coduomp-vm-filesystem-negative-byte-count.md. */
    file = FS_LoadIOFile(FS_FileForHandle(handle));
    cursor = buffer;
    remaining = (uint32_t)length;
    zeroByteWrite = 0;

    while (remaining != 0) {
        bytesWritten = (uint32_t)fwrite(cursor, 1, remaining, file);
        if (bytesWritten == 0) {
            if (zeroByteWrite) {
                Com_Printf("FS_Write: 0 bytes written\n");
                return 0;
            }
            zeroByteWrite = 1;
        }

        if (bytesWritten == UINT32_MAX) {
            Com_Printf("FS_Write: -1 bytes written\n");
            return 0;
        }

        remaining -= bytesWritten;
        cursor += bytesWritten;
    }

    if (fs_handleFiles[handle].sync != 0) {
        fflush(file);
    }

    return length;
}
