/* bits.c - Bit arithmetic functions.
 *  Copyright (C) 2022 by Jed Marti
 *   This program 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 3 of the License, or
 *   (at your option) any later version.
 *
 *  This program 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 this program.  If not, see https://www.gnu.org/licenses/.
 */


#include <C8051F380.h>
#include <stdint.h>

#include "lfxmit.h"
#include "serial.h"
#include "storage.h"

extern __xdata uint16_t   ST[];
extern uint16_t           DREG;
extern __xdata floatOrInt         IACC;
extern __xdata floatOrInt IACCB;

extern __bit            errorThrown;
extern __bit            doit;



void bitand(void)
// Bitwise AND from & operator but only on integers. If not executing, just return.
{
  // Not executing, just return.
  if (!doit) return;

  // RHS value, must be integer.
  DREG = popST();
  if (tag() == DESC_INT)
  {
    getIACC();
    DREG = popST();
    if (tag() == DESC_INT)
    {
      getIACCB();
      pushST(newInt(IACC.i & IACCB.i));
    }
    else
    {
      putstring("??? & Int\n");
      errorThrown = 1;
    }
  }

  // Otherwise error.
  else
  {
    putstring("??? & ???\n");
    errorThrown = 1;
  }
}



void bitor(void)
// Bitwise OR form | operator but only on integers. if not executing, just return.
{
  // Not executing, just return.
  if (!doit) return;
  
  DREG = popST();
  if (tag() == DESC_INT)
  {
    getIACC();
    DREG = popST();
    if (tag() == DESC_INT)
    {
      getIACCB();
      pushST(newInt(IACC.i | IACCB.i));
    }
    else
    {
      putstring("??? | Int\n");
      errorThrown = 1;
    }
  }
  else
  {
    putstring("??? | ???\n");
    errorThrown = 1;
  }
}




void bitnot(void)
// Bitwise complement from ~ operator but only on integers. If not executing, just return.
{
  // Not executing, just return.
  if (!doit) return;
  
  DREG = popST();
  if (tag() == DESC_INT)
  {
    getIACC();
    pushST(newInt(~IACC.i));
  }
  else
  {
    putstring("~???\n");
    errorThrown = 1;
  }
}



// EOF
