#include "ctf.h"


//////////////// GLOBAL VAR /////////////////////////////////

unsigned long g_ctfError = 0;

//////////////// FILE ///////////////////////////////////////

unsigned long ctf_get_file_size(char *fileName)
{
    FILE *_fd;
    unsigned long _size;

    _size = 0;
    _fd = fopen(fileName, "rb");
    if (_fd)
    {
        _size = ctf_get_fd_size(_fd);
        fclose(_fd);
    }
    return _size;
}

unsigned long ctf_get_fd_size(FILE *fd)
{

    unsigned long _n;
    fpos_t _fpos;
    fgetpos(fd, &_fpos);
    fseek(fd, 0, SEEK_END);
    _n = ftell(fd);
    fsetpos(fd, &_fpos);
    return _n;
}

unsigned char *ctf_read_file(char *fileName, unsigned long readMax)
{
    FILE *_fd;
    unsigned char *_fileBuffer;
    unsigned long _fileSize;
    int _fr;

    _fileBuffer = 0;
    _fd = fopen(fileName, "rb");
    if (_fd == NULL)
    {
        g_ctfError = CTF_ERROR_OPEN_FILE_ERROR;
    }
    else
    {
        _fileSize = ctf_get_fd_size(_fd);
        _fileSize = _fileSize < readMax ? _fileSize : readMax;
        _fileBuffer = malloc(_fileSize);
        if (_fileBuffer == NULL)
        {
            g_ctfError = CTF_ERROR_ALLOC_MEMORY_FAILED;
        }
        else
        {

            _fr = fread(_fileBuffer, _fileSize, 1, _fd);
            if (_fr != 1)
            {
                g_ctfError = CTF_ERROR_READ_FILE_FAILED;
                free(_fileBuffer);
                _fileBuffer = 0;
            }

            fclose(_fd);
        }
    }

    return _fileBuffer;
}

int ctf_write_file(char *fileName, unsigned char *fileBuffer, unsigned long fileSize)
{
    FILE *_fd;
    int _wr;

    _wr = 0;
    _fd = fopen(fileName, "wb");
    if (_fd == NULL)
    {
        g_ctfError = CTF_ERROR_OPEN_FILE_ERROR;
    }
    else
    {
        _wr = fwrite(fileBuffer, fileSize, 1, _fd);
        if (_wr != 1)
        {
            g_ctfError = CTF_ERROR_WRITE_FILE_FAILED;
        }

        fclose(_fd);
    }

    return _wr;
}