/*---------------------------------------------------------------*/
/*   Copyright (c) 1992 Regents of the University of California  */
/*                 All Rights Reserved                           */
/*---------------------------------------------------------------*/
/*-----------------------------------------------------------------
  Byte swapping functions.

  Development History:
    Begun: 03/20/92 - Todd King

  Version:
      %W%     (UCLA/IGPP)    %G%
-----------------------------------------------------------------*/
/*--------------------------------------------------------------------
NAME
  lsbfirst - Swaps bytes and words so that the byte order
	     is least significant byte (lsb) first.
  msbfirst - Swaps bytes and words so that the byte order
	     is most significant byte (msb) first.
  swapbytes - Swaps contents of adjacent bytes.
  swap2bwords - Swaps contents of adjacent two byte words.
  swap4bwords - Swaps contents of adjacent four byte words.

SYNOPSIS
    call lsbfirst(ptr, len)
    char *ptr;
    int len;

    call msbfirst(ptr, len)
    char *ptr;
    int len;

    call swapbytes(ptr, len)
    char *ptr;
    int len;

    call swap2bword(ptr, len)
    char *ptr;
    int len;

    call swap4bword(ptr, len)
    char *ptr;
    int len;

DESCRIPTION
  Swaps the contents of bytes and words in a region of memory.
  The area to swap is passed as a pointer and the number of bytes
  from the beginning of the pointer is passed. The number of bytes
  must be an even multiple of the type of operation to be performed.

RETURN VALUE
  None.  Contents of ptr are changed.

ERRORS

CALLS

Development History:
  Begun: 03/16/92 - Todd King

Version:
   %W%   (CUAL/IGPP)    %G%
--------------------------------------------------------------------*/
#include "BC.h"

void 
BCSwapBytes (char *ptr, int len)
{
   int i;
   int last;
   char c;

   last = len - (len % 2);

   for (i = 0; i < last; i += 2) {
      c = ptr[i];
      ptr[i] = ptr[i + 1];
      ptr[i + 1] = c;
   }
}

void 
BCSwap2BWord (char *ptr, int len)
{
   int i;
   int last;
   char c[2];

   last = len - (len % 4);

   for (i = 0; i < last; i += 4) {
      c[0] = ptr[i];
      c[1] = ptr[i + 1];
      ptr[i] = ptr[i + 2];
      ptr[i + 1] = ptr[i + 3];
      ptr[i + 2] = c[0];
      ptr[i + 3] = c[1];
   }
}

void 
BCSwap4BWord (char *ptr, int len)
{
   int i;
   int last;
   char c[4];

   last = len - (len % 8);

   for (i = 0; i < last; i += 8) {
      c[0] = ptr[i];
      c[1] = ptr[i + 1];
      c[2] = ptr[i + 2];
      c[3] = ptr[i + 3];
      ptr[i] = ptr[i + 4];
      ptr[i + 1] = ptr[i + 5];
      ptr[i + 2] = ptr[i + 6];
      ptr[i + 3] = ptr[i + 7];
      ptr[i + 4] = c[0];
      ptr[i + 5] = c[1];
      ptr[i + 6] = c[2];
      ptr[i + 7] = c[3];
   }
}

void 
BCGenericReverseByteOrder (char *ptr, int len)
{
   BCSwapBytes(ptr, len);
   BCSwap2BWord(ptr, len);
   BCSwap4BWord(ptr, len);
}
