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

extern byte  depack0_part0A_begin;
extern byte  depack0_part0A_start;
extern byte  depack0_part0A_adrdata;
extern byte  depack0_part0A_end;
extern byte  depack0_part0B_begin;
extern byte  depack0_part0B_stop_value;
extern byte  depack0_part0B_start;
extern byte  depack0_part0B_adrdata;
extern byte  depack0_part0B_end;

extern byte  depack0_part1_begin;
extern byte  depack0_part1_main_loop;
extern byte  depack0_part1_call_get_nice_byte1;
extern byte  depack0_part1_call_get_nice_byte2;
extern byte  depack0_part1_call_get_bits;
extern byte  depack0_part1_compare;
extern byte  depack0_part1_end;

extern byte  depack0_part2_compare1_begin;
extern byte  depack0_part2_compare1_end;
extern byte  depack0_part2_compare2_begin;
extern byte  depack0_part2_compare2_end;
extern byte  depack0_part2_compare34_begin;
extern byte  depack0_part2_compare34_end;

extern byte  depack0_part3_begin;
extern byte  depack0_part3_jump_main_loop;
extern byte  depack0_part3_jump_program;
extern byte  depack0_part3_get_nice_byte;
extern byte  depack0_part3_get_bits;
extern byte  depack0_part3_data;
extern byte  depack0_part3_end;

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

    if ( bMatch > bBestMatch) {
        return TRUE;
    } else {
        if ( ( bMatch == bBestMatch) && ( (bMask & 0xf0) == 0) && ( bBestMask & 0xf0)) {
            //
            // Has just as many matching nibbles as best.
            // However, the new one has all its top nibbles matching
            // while the other hasn't. So, the new one's mask could
            // be encoded in 5 bits, rather than 9.
            //
            // If the currently best one was within 16 distance and
            // the new one isn't then we don't gain anything as
            // first the distance could be encoded as 5 bits and now 9
            // No gain, no loss, so don't even mind checking, just
            // use the new one anyway
            //
            return TRUE;
        } else {
            return FALSE;
        }
    }
}

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

    // Vars needed to build depack code
    byte * pbDepack0 = NULL;
    byte * pbBegin;
    bits StopValue;
    bits AdrData;
    bits Start;
    bits MainLoop;
    bits CallGetNiceByte1;
    bits CallGetNiceByte2;
    bits CallGetBits;
    bits Compare;
    bits JumpMainLoop;
    bits JumpProgram;
    bits GetNiceByte;
    bits GetBits;
    bits Data;
    int Size = 0;
    int Extend;

    // Vars needed to compress data
    int UncompressedSize;
    byte * pbMemory = NULL;
    TNibSlide * ptResult = NULL;
    byte * pbCompressed = NULL;
    int CompressedSize;
    bits * pdwStream;
    bits StreamCache;
    int CacheCount;
    byte * pbStreamEnd;
    bits * pdwHere;
    bits Here;
    byte bMask;
    int RunLength;

    int Index;

    switch ( tInputLoadAddress.Count) {
      case 1:
      case 2:
        pbBegin = &depack0_part0A_begin;
        StopValue = 0;  // To remove the "might be used initialize" warning
        Start = &depack0_part0A_start - pbBegin;
        AdrData = &depack0_part0A_adrdata - pbBegin;
        Extend = &depack0_part0A_end - pbBegin;
        break;
//    case 3:
//    case 4:
      default:
        pbBegin = &depack0_part0B_begin;
        StopValue = &depack0_part0B_stop_value - pbBegin;
        Start = &depack0_part0B_start - pbBegin;
        AdrData = &depack0_part0B_adrdata - pbBegin;
        Extend = &depack0_part0B_end - pbBegin;
        break;
    }

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

    pbBegin = &depack0_part1_begin;
    MainLoop = Size + &depack0_part1_main_loop - pbBegin;
    CallGetNiceByte1 = Size + &depack0_part1_call_get_nice_byte1 - pbBegin;
    CallGetNiceByte2 = Size + &depack0_part1_call_get_nice_byte2 - pbBegin;
    CallGetBits = Size + &depack0_part1_call_get_bits - pbBegin;
    Extend = &depack0_part1_end - pbBegin;

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

    switch ( tInputLoadAddress.Count) {
      case 1:
        pbBegin = &depack0_part2_compare1_begin;
        Extend = &depack0_part2_compare1_end - pbBegin;
        break;
      case 2:
        pbBegin = &depack0_part2_compare2_begin;
        Extend = &depack0_part2_compare2_end - pbBegin;
        break;
      case 3:
      case 4:
        pbBegin = &depack0_part2_compare34_begin;
        Extend = &depack0_part2_compare34_end - pbBegin;
        break;
    }
    Compare = Size;

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

    pbBegin = &depack0_part3_begin;
    JumpMainLoop = Size + &depack0_part3_jump_main_loop - pbBegin;
    JumpProgram = Size + &depack0_part3_jump_program - pbBegin;
    GetNiceByte = Size + &depack0_part3_get_nice_byte - pbBegin;
    GetBits = Size + &depack0_part3_get_bits - pbBegin;
    Data = Size + &depack0_part3_data - pbBegin;
    Extend = &depack0_part3_end - pbBegin;

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

    //
    // Fill in Values, ADRs and Branches
    //
    switch ( tInputLoadAddress.Count) {
      case 1:
        SetASMValue( pbDepack0 + Compare, tInputLoadAddress.ASMValues[ 0]);
        break;
      case 2:
        SetASMValue( pbDepack0 + Compare, tInputLoadAddress.ASMValues[ 0]);
        SetASMValue( pbDepack0 + Compare + 4, tInputLoadAddress.ASMValues[ 1]);
        break;
      case 3:
      case 4:
        SetDWORD( pbDepack0 + StopValue, InputLoadAddress);
        break;
    }

    if ( !SetADR( pbDepack0 + AdrData, AdrData, Data)) {
        fprintf( stderr, "ADR out of range in Method0_Pack.\n");
        goto ReturnPoint;
    }
    SetBranch( pbDepack0 + JumpMainLoop, JumpMainLoop, MainLoop);
    SetBranch( pbDepack0 + CallGetNiceByte1, CallGetNiceByte1, GetNiceByte);
    SetBranch( pbDepack0 + CallGetNiceByte2, CallGetNiceByte2, GetNiceByte);
    SetBranch( pbDepack0 + CallGetBits, CallGetBits, GetBits);

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

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

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

    //
    // Get "best" results
    //
    DoTheHainesSlide( pbMemory, UncompressedSize, Size, -1, ptResult, -1, 256, Method0_CompareFunction);

    //
    // Calculate size needed to store each word
    //
    Index = UncompressedSize / 4;
    RunLength = 0;
    while ( --Index >= 0) {
      if ( ptResult[ Index].bMatch > 1) {
        ptResult[ Index].User = ( ptResult[ Index].bMask & 0xf0 ? 9 : 5) + ( ptResult[ Index].usDistance & 0xf0 ? 9 : 5) + ( 8 - ptResult[ Index].bMatch) * 4;
      } else {
        ptResult[ Index].User = 41;
      }
      switch ( RunLength) {
        case 0:
          if ( ptResult[ Index].User >= 36) {
            // Start an uncompressed run
            RunLength++;
          }
          break;
        case 1:
          if ( ptResult[ Index].User >= 36) {
            // First two words have to be really "awfully bad
            // compressable"
            RunLength++;
          } else {
            RunLength = 0;
          }
          break;
        default:
          if ( ptResult[ Index].User >= 28) {
            // Uncompressable enough to continue the uncompressed run
            RunLength++;
            if ( RunLength == 256) {
              // Maximum runlength reached
              ptResult[ Index + RunLength - 1].User = -RunLength;
              RunLength = 0;
            }
          } else {
            // Compresses well enough to stop the run for
            ptResult[ Index + RunLength].User = -RunLength;
            RunLength = 0;
          }
          break;
      }
    }
    if ( RunLength >= 2) {
      ptResult[ Index + RunLength].User = -RunLength;
      RunLength = 0;
    }

    //
    // 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 Method0_Pack. Increase slotsize.\n");
        goto ReturnPoint;
    }
    pdwStream = (bits *) pbCompressed;
    CompressedSize = 0;
    StreamCache = 0;
    CacheCount = 0;
    RunLength = 0;
    Index = UncompressedSize / 4;
    while ( --Index >= 0) {
        if ( ptResult[ Index].User < 0) {
            // Uncompressed run
            RunLength = ptResult[ Index].User;
            MethodSupport_InsertNiceByte( &pdwStream, &StreamCache, &CacheCount, 0xff);
            MethodSupport_InsertNiceByte( &pdwStream, &StreamCache, &CacheCount, -RunLength - 1);
        }
        if ( ( RunLength == 0) && (ptResult[ Index].bMatch > 1)) {
            //
            // Compressed word
            //
            MethodSupport_InsertNiceByte( &pdwStream, &StreamCache, &CacheCount, ptResult[ Index].bMask);
            MethodSupport_InsertNiceByte( &pdwStream, &StreamCache, &CacheCount, ptResult[ Index].usDistance);
            Here = pdwHere[ 0] ^ pdwHere[ ptResult[ Index].usDistance + 1];
            bMask = ptResult[ Index].bMask;
        } else {
            //
            // Uncompressed word
            //
            if ( RunLength < 0) {
              RunLength++;
            } else {
              MethodSupport_InsertNiceByte( &pdwStream, &StreamCache, &CacheCount, 0xfe);
            }
            Here = pdwHere[ 0];
            bMask = 0xff;
        }

        while ( bMask != 0) {
            if ( ( bMask & 0x80) != 0) {
              MethodSupport_InsertIntoStream( &pdwStream, &StreamCache, &CacheCount, (Here >> 28) & 0xf, 4);
            }
            Here = Here << 4;
            bMask = (bMask << 1) & 0xff;
        }
        pdwHere--;
    }

    pbStreamEnd = MethodSupport_FlushStream( &pdwStream, &StreamCache, &CacheCount);

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

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