/* method3.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 "method3.h"
#include "inputfile.h"
#include "outputfile.h"
#include "nibslide.h"
#include "tonyslide.h"
#include "methodsup.h"

extern byte depack3_part0_begin;
extern byte depack3_part0_start;
extern byte depack3_part0_adrdata;
extern byte depack3_part0_jump_program;
extern byte depack3_part0_data;
extern byte depack3_part0_end;


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

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

bits Method3_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 AdrData;
    bits JumpProgram;
    bits Data;
    int Size = 0;
    int Extend;

    // Vars needed to compress data
    int UncompressedSize;
    byte * pbMemory = NULL;
    TNibSlide * ptResult = NULL;
    byte * pbCompressed = NULL;
    byte * pbDistanceStream;
    byte bDistanceCache;
    int DistanceCacheCount;
    byte * pbMaskStream;
    bits * pdwHere;
    bits Here;
    byte bMask;

    int Index;

    if ( InputLoadAddress != 0x8000) {
       fprintf( stderr, "Can only handle files whose load address is at 0x8000 in Method3_Pack.\n");
       goto ReturnPoint;
    }

    pbBegin = &depack3_part0_begin;
    Start = &depack3_part0_start - pbBegin;
    AdrData = &depack3_part0_adrdata - pbBegin;
    JumpProgram = &depack3_part0_jump_program - pbBegin;
    Data = &depack3_part0_data - pbBegin;
    Extend = &depack3_part0_end - pbBegin;

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

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

    if ( !SetADR( pbDepack + AdrData, AdrData, Data)) {
        fprintf( stderr, "ADR out of range in Method3_Pack.\n");
        goto ReturnPoint;
    }

    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 Method3_Pack.\n");
        goto ReturnPoint;
    }
    memcpy( pbMemory, pbInputFile, UncompressedSize);
    memcpy( pbMemory + UncompressedSize, pbDepack, Size);

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

    //
    // Get "best" results
    //
    DoTheHainesSlide( pbMemory, UncompressedSize, Size, -1, ptResult, -1, 16, Method3_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 Method3_Pack. Increase slotsize.\n");
        goto ReturnPoint;
    }
    bDistanceCache = 0;
    DistanceCacheCount = 0;
    pbMaskStream = pbCompressed;
    pbDistanceStream = pbMaskStream;
    Index = UncompressedSize / 4;

    while ( --Index >= 0) {
        bMask = ptResult[ Index].bMask;

        if ( DistanceCacheCount == 0) {
           bDistanceCache = (byte) ptResult[ Index].usDistance;
           pbDistanceStream = pbMaskStream;
           pbMaskStream++;
        } else {
           bDistanceCache = bDistanceCache | (((byte) ptResult[ Index].usDistance) << 4);
           *pbDistanceStream = bDistanceCache;
        }
        DistanceCacheCount = DistanceCacheCount ^ 1;

        *pbMaskStream = bMask;
        pbMaskStream++;

        Here = pdwHere[ 0] ^ pdwHere[ ptResult[ Index].usDistance + 1];

        while ( bMask != 0) {
            if ( ( bMask & 0x01) != 0) {
               if ( DistanceCacheCount == 0) {
                  bDistanceCache = ( Here & 0xf);
                  pbDistanceStream = pbMaskStream;
                  pbMaskStream++;
               } else {
                  bDistanceCache = bDistanceCache | (( Here & 0xf) << 4);
                  *pbDistanceStream = bDistanceCache;
               }
               DistanceCacheCount = DistanceCacheCount ^ 1;
            }

            Here = Here >> 4;
            bMask = (bMask >> 1) & 0xff;
        }
        pdwHere--;
    }

    if ( DistanceCacheCount != 0) {
      *pbDistanceStream = bDistanceCache;
    }

    dwRetval = Size + ( pbMaskStream - pbCompressed);
    if ( fSave) {
        if ( OpenOutputFile()) {
             if ( !WriteToOutputFile( pbDepack, Size)) {
                dwRetval = FALSE;
             }
             if ( !WriteToOutputFile( pbCompressed, pbMaskStream - 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;
}
