#include <stdio.h>
#include <stdlib.h>

#include "mex.h"

void outputbin(char c, int bytenumber)
{
   int i, bit;
   char b[8];

   for (i = 7;i >= 0;i--)
   {
      bit = c & 1;
      if (bit == 0)
         b[i] = '0';
      else
         b[i] = '1';
      c = c >> 1;
   }

   for (i = 0;i < 8;i++)
   {
      printf("%c",b[i]);
      if (bytenumber == 1 && i == 0)
         printf("|");
      else
         if (bytenumber == 2 && i == 3)
            printf("|");
   }
}


/*
 * This mex function is called from MATLAB using the form
 *
 *    outputdouble(x);
 *
*/


/* nlhs is the number of left-hand sides (0).
 *
 * nrhs is the number of input arguments (1)
 *
 * prhs[0] points at the matrix double value x
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
   /* c[8] occupies the same space as x. we use this to gain access
    * to the 8 bytes of x
   */
   union
   {
      unsigned char c[8];
      double x;
   } bits;
   int i;

   /* Check for the proper number of arguments
   */
   if (nrhs != 1)
       mexErrMsgIdAndTxt("outputdouble:Error",
                         "The double value is the only input argument.");
   else if (nlhs != 0)
      mexErrMsgIdAndTxt("outputdouble:Error",
                        "There are no output arguments");

   bits.x = mxGetScalar(prhs[0]);;
   for (i=7;i >= 0;i--)
      outputbin(bits.c[i],8-i);
   printf("\n");
}
