//
// tardy - a tar post-processor
// Copyright (C) 2002, 2008, 2009, 2011 Peter Miller
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or (at
// your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//

#include <libtardy/ac/string.h>
#include <libtardy/filenamelist/file.h>


filenamelist_file::~filenamelist_file()
{
}


filenamelist_file::filenamelist_file(const file_input::pointer &a_source) :
    source(a_source),
    position(0),
    length(0)
{
}


filenamelist::pointer
filenamelist_file::create(const file_input::pointer &a_source)
{
    return pointer(new filenamelist_file(a_source));
}


int
filenamelist_file::read_one_char(void)
{
    if (position >= length)
    {
        position = 0;
        length = source->read(buffer, sizeof(buffer));
        if (length == 0)
            return -1;
    }
    return buffer[position++];
}


bool
filenamelist_file::read_one_line(rcstring &result)
{
    static char *temp;
    static size_t maximum;
    size_t line_length = 0;
    for (;;)
    {
        int c = read_one_char();
        if (c < 0)
        {
            if (line_length)
            {
                while (line_length && temp[line_length - 1] == '/')
                    --line_length;
                result = rcstring(temp, line_length);
                return true;
            }
            return false;
        }
        if (c == '\n')
        {
            while (line_length && temp[line_length - 1] == '/')
                --line_length;
            result = rcstring(temp, line_length);
            return true;
        }
        if (line_length >= maximum)
        {
            maximum = maximum * 2 + 16;
            char *temp2 = new char[maximum];
            memcpy(temp2, temp, line_length);
            delete temp;
            temp = temp2;
        }
        temp[line_length++] = c;
    }
}


rcstring
filenamelist_file::filename(void)
    const
{
    return source->filename();
}
