#include "BinaryFile.h"
#include "ByteUtils.h"

bool BinaryFile::GetNextByteAsInt(std::ifstream* file, int& target)
{
    char c;
    file->get(c);
    target = int(c);
    return true;
}

bool BinaryFile::GetNextNBytes(std::ifstream* file, char* buffer, unsigned number)
{
    char c;
    for(unsigned idx=0; idx<number; idx++)
    {
        if(file->get(c))
        {
            buffer[idx] = c;
        }
        else
        {
            return false;
        }
    }
    return true;
}

bool BinaryFile::GetNextWord(std::ifstream* file, char* buffer)
{
    return GetNextNBytes(file, buffer, ByteUtils::BYTES_PER_WORD);
}

bool BinaryFile::GetNextDWord(std::ifstream* file, char* buffer)
{
    return GetNextNBytes(file, buffer, ByteUtils::BYTES_PER_DWORD);
}

bool BinaryFile::GetNextWord(std::ifstream* file, int& target, bool reverse)
{
    char buffer[ByteUtils::BYTES_PER_WORD];
    if(!BinaryFile::GetNextWord(file, buffer))
    {
        return false;
    }
    target = ByteUtils::ToWord(buffer, reverse);
    return true;
}

bool BinaryFile::GetNextDWord(std::ifstream* file, int& target)
{
    char buffer[ByteUtils::BYTES_PER_DWORD];
    if(!BinaryFile::GetNextDWord(file, buffer))
    {
        return false;
    }
    target = ByteUtils::ToDWord(buffer);
    return true;
}

bool BinaryFile::CheckNextDWord(std::ifstream* file, const char* target)
{
    char buffer[ByteUtils::BYTES_PER_DWORD];
    if(!BinaryFile::GetNextDWord(file, buffer))
    {
        return false;
    }

    if(!ByteUtils::CompareDWords(buffer, target))
    {
        return false;
    }
    return true;
}

bool BinaryFile::GetNextString(std::ifstream* file, std::string& target, unsigned numBytes)
{
    char c;
    for(unsigned idx=0; idx<numBytes; idx++)
    {
        if(!file->get(c))
        {
            return false;
        }
        target += c;
    }
    return true;
}
