module: quant_mbit
description: 
timing_sensitivity: 
parameters:  double vref, int num_bits
inputs:  double in, double_interp clk
outputs:  double out, int out_int
classes:  EdgeDetect rising_edge()
static_variables:  double prev_in, double num_levels_div2
                   int prev_fb_val, int update_out_flag, double del_out, double prev_out
init: 
if (num_bits < 1)
   {
    printf("error in 'quant_mbit':  num_bits must be >= 1\n");
    printf("   -> in this case, num_bits = %d\n", num_bits);
    exit(1);
   }
num_levels_div2 = (pow(2.0,((double) num_bits))-1.0)/2.0; 
prev_in = 0.0;
prev_fb_val = 0;
update_out_flag = 0;
del_out = 0.0;
prev_out = 0.0;

if (vref < 1e-30)
   {
    printf("error in 'quant_mbit':  vref must be > 1e-30\n");
    printf("  -> in this case, vref = %5.3e\n",vref);
    exit(1);
   }

code: 
double in_sampled, in_scaled, out_val;
int i;
 
out = del_out;

if (rising_edge.inp(clk))
  {
   update_out_flag = 1;
   in_sampled = (prev_in*(-clk + 1.0) + in*(clk + 1.0))/2.0;
   if (in_sampled > vref)
      in_sampled = vref;
   else if (in_sampled < -vref)
      in_sampled = -vref;

   in_scaled = in_sampled*num_levels_div2/vref + 0.5;
   out_val = (floor(in_scaled) - 0.5)/num_levels_div2*vref;
   del_out = (prev_out*(-clk + 1.0) + out_val*(clk + 1.0))/2.0;
   prev_out = out_val;

   prev_fb_val = (int) (floor(in_scaled) + num_levels_div2);
  }
else if (update_out_flag == 1)
   {
   update_out_flag = 0;
   del_out = prev_out;

   out_int = prev_fb_val;
   }

prev_in = in;
