/* asm.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 <stdio.h>
#include <oslib/types.h>

#include "asm.h"

void NumberToTASMNumber( bits Number, TASMNumber * ptNumber) {
    int    Shift;

    ptNumber->Number = Number;
    ptNumber->Count = 0;

    for ( Shift = 24 ; Shift >= 0 ; Shift -= 2) {
        if ( ( Number & ( 0xc0 << Shift)) != 0) {
           ptNumber->ASMValues[ ptNumber->Count++] = (( Number & ( 0xff << Shift)) >> Shift) | (( ((32 - Shift) / 2) & 0xf) << 8);
           Shift -= 6;
        }
    }
    Number = Number & ( ( 0xff << ( 8 + Shift)) >> 8);
    if ( ( Number != 0) || ( ptNumber->Count == 0)) {
        ptNumber->ASMValues[ ptNumber->Count++] = Number;
    }
}

void SetBranch( byte * pbInstruction, bits From, bits To) {
   From = ( To - ( From + 8)) >> 2;
   pbInstruction[ 0] = ( From >> 0) & 0xff;
   pbInstruction[ 1] = ( From >> 8) & 0xff;
   pbInstruction[ 2] = ( From >> 16) & 0xff;
}

void SetASMValue( byte * pbInstruction, bits ASMValue) {
   pbInstruction[ 0] = ASMValue & 0xff;
   pbInstruction[ 1] = (pbInstruction[ 1] & 0xf0) | (( ASMValue >> 8) & 0xf);
}

void SetDWORD( byte * pbMemory, bits DWORD) {
   pbMemory[ 0] = ( DWORD >> 0) & 0xff;
   pbMemory[ 1] = ( DWORD >> 8) & 0xff;
   pbMemory[ 2] = ( DWORD >> 16) & 0xff;
   pbMemory[ 3] = ( DWORD >> 24) & 0xff;
}

bool SetADR( byte * pbInstruction, bits From, bits Address) {
   bool fRetval = TRUE;
   TASMNumber tNumber;
   int Diff;

   Diff = Address - ( From + 8);
   NumberToTASMNumber( abs( Diff), &tNumber);
   if ( tNumber.Count == 1) {
       SetASMValue( pbInstruction, tNumber.ASMValues[ 0]);
       if ( Diff < 0) {
          pbInstruction[ 2] = ( pbInstruction[ 2] & 0x1f) | 0x40;
       } else {
          pbInstruction[ 2] = ( pbInstruction[ 2] & 0x1f) | 0x80;
       }
   } else {
       fRetval = FALSE;
   }
   return fRetval;
}
