//
// tardy - a tar post-processor
// Copyright (C) 1998, 1999, 2001-2004, 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/assert.h>
#include <libtardy/ac/string.h>

#include <libtardy/tar/format.h>
#include <libtardy/tar/output/tar.h>


tar_output_tar::~tar_output_tar()
{
}


tar_output_tar::tar_output_tar(const file_output::pointer &a_fp) :
    fp(a_fp),
    pos(0),
    block_size(TBLOCK * 20)
{
    assert(fp);
}


void
tar_output_tar::write_data(const void *data, int data_size)
{
    fp->write(data, data_size);
    pos += data_size;
}


void
tar_output_tar::write_data_padding(void)
{
    static char padding[TBLOCK];
    int n = pos % TBLOCK;
    if (n)
        write_data(padding, TBLOCK - n);
}


rcstring
tar_output_tar::filename(void)
    const
{
    return fp->filename();
}


void
tar_output_tar::write_archive_end(void)
{
    if ((pos % block_size) == 0)
        return;
    char buffer[TBLOCK];
    memset(buffer, 0, TBLOCK);
    for (;;)
    {
        write_data(buffer, TBLOCK);
        if ((pos % block_size) == 0)
            break;
    }
}


void
tar_output_tar::set_block_size(long nbytes)
{
    if (nbytes <= 0 || (nbytes % TBLOCK != 0))
        block_size = TBLOCK * 20;
    else
        block_size = nbytes;
}
