
module: time_to_digital_primitive
parameters: double delay_resolution, int num_levels
inputs: double_interp ref_in double_interp clk_in
outputs: double out_rising double out_falling
classes: 
static_variables: Delay *delay_chain, Reg *reg_chain
init:
int i;

if (num_levels < 1)
   {
    printf("error in 'time_to_digital_primitive':  num_levels must be > 0\n");
    printf("  in this case, num_levels = %d\n",num_levels);
    exit(1);
   }

// create register chain
reg_chain = new Reg[num_levels];

// create delay chain for ref_in signal
if (num_levels > 1)
   {
    delay_chain = new Delay[num_levels-1];
    for (i = 0; i < num_levels-1; i++)
       delay_chain[i].set_nom_delay(delay_resolution/Ts);
   }
else
   {
    delay_chain = NULL;
   }
end:
delete [] reg_chain;
if (delay_chain != NULL)
   delete [] delay_chain;

code:

int i;

out_rising = -1;
out_falling = -1;

for (i = 0; i < num_levels; i++)
   {
    if (i == 0)
       reg_chain[i].inp(clk_in,ref_in,-1.0,-1.0);
    else
      {
       if (i == 1)
          delay_chain[i-1].inp(clk_in);
       else
          delay_chain[i-1].inp(delay_chain[i-2].out);

       reg_chain[i].inp(delay_chain[i-1].out,ref_in,-1.0,-1.0);
      }
    if (i > 0)
      {
       if (reg_chain[i-1].out == -1.0 && reg_chain[i].out != -1.0 &&
           out_rising == -1)
          out_rising = i-1;
       else if (reg_chain[i-1].out == 1.0 && reg_chain[i].out != 1.0 &&
                out_falling == -1)
          out_falling = i-1;
      }    
   }
