/* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.

iem_dp written by IOhannes m zmoelnig, Thomas Musil, Copyright (c) IEM KUG Graz Austria 1999 - 2013 */
/* double precision library */

#include "m_pd.h"
#include "iemlib.h"
#include "iem_dp.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* -------------------------- dptohex ------------------------------ */
/* double float to 16 digits of hexadecimal converter */

/* double float is only internal used */
/* to transfer this value, we divide this double value into use one float casted value */
/* and into the difference to the accurate double value. */

/* double float (sign_1 + exp_12 + mant_51) */

static t_class *dptohex_class;

typedef struct _dptohex
{
  t_object  x_obj;
  t_float   x_float_casted_value;
  t_float   x_residual;
} t_dptohex;

static void dptohex_bang(t_dptohex *x)
{
  char buf[100];
  union tabfudge_d tf;

  tf.tf_d = iem_dp_calc_sum(x->x_float_casted_value, x->x_residual);
  sprintf(buf, "#%08X%08X", tf.tf_i[HIOFFSET], tf.tf_i[LOWOFFSET]);
  outlet_symbol(x->x_obj.ob_outlet, gensym(buf));
}

static void dptohex_float(t_dptohex *x, t_floatarg f)
{
  x->x_float_casted_value = f;
  dptohex_bang(x);
}

static void *dptohex_new(void)
{
  t_dptohex *x = (t_dptohex *)pd_new(dptohex_class);

  floatinlet_new(&x->x_obj, &x->x_residual);
  x->x_float_casted_value = 0.0f;
  x->x_residual = 0.0f;
  outlet_new(&x->x_obj, &s_symbol);
  return (x);
}

static void dptohex_free(t_dptohex *x)
{
}

void dptohex_setup(void)
{
  dptohex_class = class_new(gensym("dptohex"),
    (t_newmethod)dptohex_new, (t_method)dptohex_free, sizeof(t_dptohex), 0, 0);
  class_addbang(dptohex_class, dptohex_bang);
  class_addfloat(dptohex_class, dptohex_float);
}
