//
// $Id: ZlibInStream.m,v 1.8 2005/05/18 06:46:54 will_mason Exp $
//
// vi: set ft=objc:

/*
 * ObjectiveLib - a library of containers and algorithms for Objective-C
 *
 * Copyright (c) 2004
 * Will Mason
 *
 * Portions:
 *
 * Copyright (c) 1994
 * Hewlett-Packard Company
 *
 * Copyright (c) 1996,1997
 * Silicon Graphics Computer Systems, Inc.
 *
 * Copyright (c) 1997
 * Moscow Center for SPARC Technology
 *
 * Copyright (c) 1999 
 * Boris Fomitchev
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * You may contact the author at will_mason@users.sourceforge.net.
 */

#import "ZlibInStream.h"
#import "Macros.h"
#import <Foundation/NSString.h>
#import <Foundation/NSException.h>
#import <zlib.h>
#import <string.h>
#import <limits.h>

extern voidpf __ol_zalloc(voidpf, uInt, uInt);
extern void __ol_zfree(voidpf, voidpf);

@interface OLZlibInStream (PrivateMethods)

- (void) fillBuffer;

@end

@implementation OLZlibInStream

+ (id) streamWithInStream: (OLInStream*)underStream
{
    OL_BEGIN_AUTO_CTOR(OLZlibInStream)
        initWithInStream: underStream
    OL_END_AUTO_CTOR;
}

- (id) initWithInStream: (OLInStream*)underStream
{
    return [self initWithInStream: underStream bufferSize: 1024];
}

- (id) initWithInStream: (OLInStream*)underStream bufferSize: (unsigned)size
{
    return [self initWithInStream: underStream bufferSize: size readZlibHeader: YES];
}

- (id) initWithInStream: (OLInStream*)underStream bufferSize: (unsigned)size readZlibHeader: (BOOL)zlibHeader
{
    int rc;
    char msgBuf[512];
    int windowBits = zlibHeader ? MAX_WBITS : -MAX_WBITS;

    [super initWithInStream: underStream];
    zstream = [allocator allocateBytes: sizeof(struct z_stream_s)];
    zstream->zalloc = __ol_zalloc;
    zstream->zfree = __ol_zfree;
    zstream->opaque = allocator;
    rc = inflateInit2(zstream, windowBits);
    if (rc != Z_OK)
    {
        if (zstream->msg == NULL)
        {
            msgBuf[0] = 0;
        }
        else
        {
            strncpy(msgBuf, zstream->msg, 512);
            msgBuf[511] = 0;
        }
        [allocator deallocateBytes: zstream];
        zstream = NULL;
        buffer = NULL;
        bufferSize = 0;
        [NSException raise: OLInputOutputException
            format: @"Error initializing for inflation - %s", msgBuf];
    }
    buffer = [allocator allocateBytes: size];
    bufferSize = size;
    zstream->avail_in = 0;
    return self;
}

- (void) dealloc
{
    [self close];
    if (buffer != NULL)
        [allocator deallocateBytes: buffer];
    [super dealloc];
}

- (void) close
{
    char msgBuf[512];

    if (zstream != NULL)
    {
        if (inflateEnd(zstream) != Z_OK)
        {
            if (zstream->msg == NULL)
            {
                msgBuf[0] = 0;
            }
            else
            {
                strncpy(msgBuf, zstream->msg, 512);
                msgBuf[511] = 0;
            }
            [allocator deallocateBytes: zstream];
            zstream = NULL;
            [NSException raise: OLInputOutputException
                format: @"Error closing OLZlibOutStream - %s", msgBuf];
        }
        [allocator deallocateBytes: zstream];
        zstream = NULL;
    }
    [stream close];
}

- (unsigned) readBytes: (uint8_t*)dest count: (unsigned)max
{
    int rc;

    if (max != 0)
    {
        zstream->next_out = dest;
        zstream->avail_out = max;
        do
        {
            if (zstream->avail_in == 0)
                [self fillBuffer];
            rc = inflate(zstream, Z_NO_FLUSH);
            if (rc != Z_OK)
            {
                if (rc == Z_STREAM_END)
                {
                    if (zstream->avail_out == max)
                        return UINT_MAX;
                    break;
                }
                else
                {
                    [NSException raise: OLInputOutputException
                        format: @"Error inflating - %s", zstream->msg];
                }
            }
        } while (zstream->avail_out != 0);
    }
    return max - zstream->avail_out;
}

@end

@implementation OLZlibInStream (PrivateMethods)

- (void) fillBuffer
{
    unsigned cur = 0;
    unsigned total = 0;

    while (total < bufferSize)
    {
        cur = [stream readBytes: buffer + total count: bufferSize - total];
        if (cur == UINT_MAX)
            break;
        total += cur;
    }
    zstream->next_in = buffer;
    zstream->avail_in = total;
}

@end
