/* method4.c */

/****************************************************************************
 *
 *  Copyright (C) 2000-2001 Eli-Jean R. Leyssens, aka Pervect of Topix
 *
 *  This file is part of the CodePressor package.
 *
 *  CodePressor 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 2 of the License, or
 *  (at your option) any later version.
 *
 *  CodePressor 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 CodePressor; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 *
 *  Eli-Jean R. Leyssens can be reached via email at eli@dnd.utwente.nl
 *  snail: E-J.R. Leyssens, Schivelbeinerstr. 5, 10439 Berlin, Germany
 *
 ***************************************************************************/

#include <malloc.h>
#include <stdio.h>
#include <oslib/types.h>

#include "method4.h"
#include "inputfile.h"
#include "outputfile.h"
#include "byteslide.h"
#include "tonybslide.h"
#include "methodsup.h"

extern byte  depack4_part0_begin;
extern byte  depack4_part0_start;
extern byte  depack4_part0_jump_program;
extern byte  depack4_part0_end;

bool Method4_CompareFunction( byte bBestMatch, byte bBestMask, unsigned short usBestDistance, byte bMatch, byte bMask, unsigned short usDistance) {

    if ( bMatch > bBestMatch) {
        return TRUE;
    } else {
        return FALSE;
    }
}

bits Method4_Pack( bool fSave) {
    //
    // fSave = TRUE -> Also save out the result
    //
    bits dwRetval = FALSE;

    // Vars needed to build depack code
    byte * pbDepack = NULL;
    byte * pbBegin;
    bits Start;
    bits JumpProgram;
    int Size = 0;
    int Extend;

    // Vars needed to compress data
    int UncompressedSize;
    byte * pbMemory = NULL;
    TByteSlide * ptResult = NULL;
    byte * pbCompressed = NULL;
    int CompressedSize;
    byte * pbStream;
    bits * pdwHere;
    bits Here;
    byte bMask;

    int Index;

    pbBegin = &depack4_part0_begin;
    Start = &depack4_part0_start - pbBegin;
    JumpProgram = &depack4_part0_jump_program - pbBegin;
    Extend = &depack4_part0_end - pbBegin;

    if ( !MethodSupport_ExtendDepackCodeWithPart( &pbDepack, &Size, pbBegin, Extend)) {
        goto ReturnPoint;
    }

    //
    // Fill in Values, ADRs and Branches
    //

    OutputLoadAddress = InputLoadAddress + InputAlignedSize;
    OutputExecAddress = OutputLoadAddress + Start;

    SetBranch( pbDepack + JumpProgram, OutputExecAddress + JumpProgram - Start, InputExecAddress);

    //
    //
    // Setup memory for "compression"
    //
    //
    UncompressedSize = InputAlignedSize;
    pbMemory = (byte *) malloc( UncompressedSize + Size);
    if ( pbMemory == NULL) {
        fprintf( stderr, "Failed to claim memory for input data +depack code in Method4_Pack.\n");
        goto ReturnPoint;
    }
    memcpy( pbMemory, pbInputFile, UncompressedSize);
    memcpy( pbMemory + UncompressedSize, pbDepack, Size);

    ptResult = ( TByteSlide *) malloc( sizeof( TByteSlide) * UncompressedSize / 4);
    if ( ptResult == NULL) {
        fprintf( stderr, "Failed to claim memory for result data in Method4_Pack.\n");
        goto ReturnPoint;
    }

    //
    // Get "best" results
    //
    DoTheHainesByteSlide( pbMemory, UncompressedSize, Size, -1, ptResult, -1, 15, Method4_CompareFunction);

    //
    // Actually generate the compressed data
    //
    pdwHere = (bits *) ( pbMemory + UncompressedSize - 4);
    pbCompressed = (byte *) malloc( UncompressedSize * 2);
    if ( pbCompressed == NULL) {
        fprintf( stderr, "Failed to claim memory for compressed data in Method4_Pack. Increase slotsize.\n");
        goto ReturnPoint;
    }
    pbStream = (byte *) pbCompressed;
    CompressedSize = 0;
    Index = UncompressedSize / 4;

    while ( --Index >= 0) {
        bMask = ptResult[ Index].bMask;
        bMask = (( bMask & 0x1) << 3) | (( bMask & 0x2) << 1) | (( bMask & 0x4) >> 1) | (( bMask & 0x8) >> 3);
        *pbStream = bMask | (( ptResult[ Index].usDistance + 1) << 4);
        pbStream++;
        Here = pdwHere[ 0];

        while ( bMask != 0) {
            if ( ( bMask & 0x01) != 0) {
              *pbStream = (Here >> 24) & 0xff;
              pbStream++;
            }
            Here = Here << 8;
            bMask = (bMask >> 1) & 0x0f;
        }
        pdwHere--;
    }
    *pbStream = 0;
    pbStream++;

    dwRetval = Size + ( pbStream - pbCompressed);
    if ( fSave) {
        if ( OpenOutputFile()) {
             if ( !WriteToOutputFile( pbDepack, Size)) {
                dwRetval = FALSE;
             }
             if ( !WriteToOutputFile( pbCompressed, pbStream - pbCompressed)) {
                dwRetval = FALSE;
             }
             if ( !CloseOutputFile()) {
                dwRetval = FALSE;
             }
        }
    }

ReturnPoint:
    if ( pbDepack != NULL) {
      free( pbDepack);
      pbDepack = NULL;
    }
    if ( pbMemory != NULL) {
      free( pbMemory);
      pbMemory = NULL;
    }
    if ( ptResult != NULL) {
      free( ptResult);
      ptResult = NULL;
    }
    if ( pbCompressed != NULL) {
      free( pbCompressed);
      pbCompressed = NULL;
    }
    return dwRetval;
}
