// CvsFilenames.cpp: implementation of the CvsFilenames class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "CvsTrace.h"
#include "CvsFilenames.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CvsFilenames::CvsFilenames(const unsigned char* sFilenames)
:   m_sBuffer((const char*)sFilenames),
    m_nFilenames(0),
    m_arrayOffsetName(0)
{
    qTRACE_FN(CvsFilenames);
    qTRACE(("* strlen(sFilenames) = %d",strlen((const char*)sFilenames)));

    char* sBase = m_sBuffer.getBuffer();

    // count \n separators
    int nNames = 0;
    char* sName = sBase;
    for (;;) {
        char* s = strchr(sName,'\n');
        if (!s) break;
        ++nNames;
        sName = s + 1;
    }

    qTRACE(("* found %d names",nNames));

    // set name offsets and replace \n with \0
    m_arrayOffsetName = new int[nNames];
    int iName = 0;
    sName = sBase;
    for (;;) {
        char* s = strchr(sName,'\n');
        if (!s) break;
        m_arrayOffsetName[iName++] = (int)(sName - sBase);
        *s++ = 0;
        sName = s;
    }
    ASSERT(iName == nNames);
    ASSERT((0 == iName) || !*sName);
}

CvsFilenames::~CvsFilenames()
{
    delete [] m_arrayOffsetName;
}

//
//
//

const char* CvsFilenames::getFilename(int i)
{
    if ((i < 0) || (m_nFilenames <= i)) return "";
    int iOffset = m_arrayOffsetName[i];
    ASSERT(0 <= iOffset);
    ASSERT(iOffset < m_sBuffer.getBufferMax());
    const char* p = m_sBuffer;
    return p + iOffset;
}

//
//
//

bool CvsFilenames::getOptionsAndFilename(int i,CvsString& sOptions,CvsString& sFilename)
{
    if ((i < 0) || (m_nFilenames <= i)) {
        sOptions.strcpy("");
        sFilename.strcpy("");
        return false;
    }
    int iOffset = m_arrayOffsetName[i];
    ASSERT(0 <= iOffset);
    ASSERT(iOffset < m_sBuffer.getBufferMax());
    const char* pBase = m_sBuffer + iOffset;
    const char* pTab  = strchr(pBase,'\t');
    if (pTab) {
        sOptions.strncpy(pBase,(int)(pTab - pBase));
        sFilename.strcpy(pTab+1);
    } else {
        sOptions.strcpy("");
        sFilename.strcpy(pBase);
    }
    return true;
}
