<: if {![expr ([expr [getIntValue "C_HAS_I2C_SLAVE"] == 1] && [expr [getIntValue "C_IS_DIABLO"] == 0])]} {ttcl_return} :>
<: set ComponentName [getComponentNameString] :>
<: setOutputDirectory "./" :>
<: setFileName [ttcl_add $ComponentName "_i2c_drp"] :>
<: setFileExtension ".v" :>
<#: ttcl/variables.ttcl :>
<: set comment "//" :>
<#: ttcl/disclaimer.ttcl :>
`timescale 1ns / 1 ps

(* CORE_GENERATION_INFO = "<=: ComponentName :>,system_management_wiz_v1_3_10,{component_name=<=: ComponentName :>,enable_axi=<=: expr { $c_has_AXI ? "true" : "false" } :>,enable_axi4stream=<=: expr { $c_has_AXI4STREAM ? "true" : "false" } :>,dclk_frequency=<=: c_dclk_freq_int :>,enable_busy=<=: expr { $c_has_BUSY ? "true" : "false" } :>,enable_convst=<=: expr { $c_has_CONVST ? "true" : "false" } :>,enable_convstclk=<=: expr { $c_has_CONVSTCLK ? "true" : "false" } :>,enable_dclk=<=: expr { $c_has_DCLK ? "true" : "false" } :>,enable_drp=<=: expr { $c_has_DRP ? "true" : "false" } :>,enable_eoc=<=: expr { $c_has_EOC ? "true" : "false" } :>,enable_eos=<=: expr { $c_has_EOS ? "true" : "false" } :>,enable_vbram_alaram=<=: expr { $c_has_Vbram_Alarm ? "true" : "false" } :>,enable_vccpsaux_alaram=<=: expr { $c_has_vccpsaux_Alarm ? "true" : "false" } :>,enable_Vccint_Alaram=<=: expr { $c_has_Vccint_Alarm ? "true" : "false" } :>,enable_Vccaux_alaram=<=: expr { $c_has_Vccaux_Alarm ? "true" : "false" } :>,enable_vccpsintfp_alaram=<=: expr { $c_has_vccpsintfp_Alarm ? "true" : "false" } :>,enable_vccpsintlp_alaram=<=: expr { $c_has_vccpsintlp_Alarm ? "true" : "false" } :>,ot_alaram=<=: expr { $c_has_OT_Alarm ? "true" : "false" } :>,user_temp_alaram=<=: expr { $c_has_User_Temp_Alarm ? "true" : "false" } :>,timing_mode=<=: $timing_mode :>,channel_averaging=<=: $averaging :>,sequencer_mode=<=: $sequence_mode :>,startup_channel_selection=<=: $channel_sel :>}" *)

module <=: ComponentName :>_i2c_drp(
clk,                      // System Clock
rst,                      // Reset 
sda_i,                    // I2C serial data input
scl_i,                    // I2C serial clock input
sda_o,                    // I2C serial data out
sda_t,                    // I2C serial data out enable
scl_o,                    // I2C serial clock out
scl_t,                    // I2C serial clock out enable
drdy,              // Data ready
daddr_pl,         // Registerd version of daddr
den_pl,           // Registerd version of den
dwe_pl,           // Registerd version of dwe
di_pl,            // Registerd version of di
sel_pl,
jtag,
i2c_busy,
do_pl           // Data Out from the memory (cfg and status)
 );
// -----------------------------------------------------------------------------
 //  Global definitions
 // ----------------------------------------------------------------------------
 
 // -----------------------------------------------------------------------------
 // Local Constant definitions
 // -----------------------------------------------------------------------------       
 
 parameter       TSUDAT       = 15;              // Calculate data setup time depending on the mode {standard, fast}
                                                 // Standard Mode timing 250ns
                                                 // Fast Mode timing is 100ns
 parameter [3:0] CNT_DONE       = 4'b1000;                                                                                                                                      
 parameter       C_SIZE         = 4;
 localparam      DBYTE          = 8;
 localparam      TIMEOUT        = 1250000;       // 25 ms assuming osc_clk equal to 50 mhz  
 localparam      C_TIMEOUT_SIZE = 21;            // 21 bit counter
 localparam      ARA_CMD        = 7'b0001100;    // SMBus Alert Response Address
parameter IDLE  = 3'b001,HEADER = 3'b010,ACK_HEADER = 3'b011, RCV_DATA  = 3'b100,ACK_DATA = 3'b101,XMIT_DATA = 3'b110,WAIT_ACK = 3'b111 ;
reg   [2:0]          state;  
//parameter [2:0] {IDLE, HEADER, ACK_HEADER, RCV_DATA, ACK_DATA, XMIT_DATA, WAIT_ACK} state;  // State Machine states


input              clk;                      // System Clock
input              rst;                      // Reset 
input              sda_i;                    // I2C serial data input
input              scl_i;                    // I2C serial clock input
output             sda_o;                    // I2C serial data out
output             sda_t;                    // I2C serial data out enable
output             scl_o;                    // I2C serial clock out
output             scl_t;                    // I2C serial clock out enable
input        drdy;              // Data ready
input        jtag;              // Data ready
  output [7:0]  daddr_pl;         // Registerd version of daddr
  output        den_pl;           // Registerd version of den
  output        dwe_pl;           // Registerd version of dwe
  output        i2c_busy;           // 
  output [15:0] di_pl;            // Registerd version of di
  output [1:0] sel_pl;            // Registerd version of di
  input  [15:0] do_pl ;          // Data Out from the memory (cfg and status)


//======================
//    Internal Signals
//======================
reg [31:0] data_rcv_ff;      // Internal data receive bus 
reg [15:0] drp_data_ff;      // Internal DRP data bus
reg  [7:0] data_xmt_ff;      // Internal data transmit bus
reg  [1:0] stat_ff;          // Internal Status bits
reg [15:0] data_ff;          // Registered internal data bus to DRP
reg  [1:0] sel_ff;          // Registered internal address bus to DRP
reg  [7:0] addr_ff;          // Registered internal address bus to DRP
reg  [1:0] rcv_pointer_ff;   // Receive pointer
reg        xmt_pointer_ff;   // Transmit pointer

reg        new_cmd_ff;       // New command ready flag
reg        den_ff;           // Registered DRP enable
reg        den_d_ff;           // Registered DRP enable
reg        i2c_busy_ff;           // Registered DRP enable
reg        dwe_ff;           // Registered DRP write enable
reg        dwe_d_ff;           // Registered DRP write enable
  wire [15:0] do_status;        // Data out from the status registers
  reg         write_addr_valid; // if high, the write address is in the range of registers that exist

  reg  [11:0] drp_block_en;     // one-hot decoded address to select 1 block
reg                 detect_start_ff;      // START condition has been detected
reg                 detect_stop_ff;       // STOP condition has been detected
reg                 sm_stop;              // STOP condition needs to be generated from State Machine
reg                 bus_busy_ff;          // Indicates that the bus is busy
reg                 scl_d1_ff;            // Sampled version of SCL
reg                 scl_rin_ff;           // Sampled version of SCL, delayed by one cycle
reg                 scl_rin_d1_ff;        // Sampled version of SCL, delayed by 2 cycles
wire                sda_falling;          // Pulses when SDA falls
wire                sda_rising;           // Pulses when SDA rises
wire                sda_changing;         // Pulses when SDA changes
reg                 scl_rising_edge_ff;   // Rising edge of SCL
reg                 scl_falling_edge_ff;  // Falling edge of SCL
reg                 scl_f_edg_d1_ff;      // Falling edge of SCL delayed one clock cycle
reg                 scl_f_edg_d2_ff;      // Falling edge of SCL delayed two clock cycles   
reg                 scl_f_edg_d3_ff;      // Falling edge of SCL delayed three clock cycles
reg                 sda_d1_ff;            // Sampled version of SDA
reg                 sda_rin_ff;           // Sampled version of SDA dealyed by one clock cycle
reg                 sda_rin_d1_ff;        // Sampled version of SDA dealyed by two clock cycles
reg                 sda_setup_ff;         // SDA setup time in progress
wire [C_SIZE - 1:0] sda_setup_cnt;        // SDA setup time count     
reg                 sda_sample_ff;        // sda_rin sampled at SCL rising edge
reg                 slave_sda_ff;         // SDA slave value
wire [DBYTE-1:0]    shift_reg;            // I2C data shift reg
wire                shift_out;            // I2C data shift reg output
reg                 shift_reg_en_ff;      // I2C data shift reg enable
reg                 shift_reg_ld_ff;      // I2C data shift reg load
reg                 shift_reg_ld_d1_ff;   // I2C data shift load delayed by one clock cycle
wire [DBYTE-1:0]    i2c_header;           // I2C header register
reg [DBYTE-1:0] data_rcv;                 // Data receive
reg                 i2c_header_en_ff;     // I2C header register enable
wire                i2c_shiftout;         // I2C header register output
wire                 addr_match;           // Address matches
wire                 addr_match_master;           // Address matches
wire                 addr_match_slave0;           // Address matches
wire                 addr_match_slave1;           // Address matches
wire [6:0]                addr_loc_slave0;           // Address matches
wire [6:0]                addr_loc_slave1;           // Address matches
wire [7:0]           addr;           // Address matches
wire [6:0]                addr_loc;           // Address matches
wire [3:0]          bit_cnt;              // Bit counter value
reg                 bit_cnt_ld;           // Bit counter load
reg                 bit_cnt_en_ff;        // Bit counter enable
reg                 aas_ff;               // Internal addressed as slave
reg                 new_rcv_data_ff;      // Internal new_rcv_dta
reg                 rdy_new_xmt_ff;       // Internal ready to transmit new data
reg                 rdy_new_xmt_d_ff;     // Internal ready to transmit new data delayed by one clk cycle
reg                 timeout_rst_ff;       // Synchronous Reset signal after time out violation
reg                 detect_stop_d_ff;     // registred detect_stop
reg                 detect_start_d_ff;    // registred detect_stop
reg                 flag_fault_ff;        // registred flag_fault
reg                 en_test_ctrl_i2c_sda_ts;        // registred flag_fault
reg                 test_ctrl_i2c_sda_ts;        // registred flag_fault

wire                       detect_stop_pulse;  // detect stop 1 clk cycle pulse
reg                       jtag_busy;  // detect stop 1 clk cycle pulse
wire                       detect_start_pulse; // detect start 1 clk cycle pulse 
wire                       scl_t_i;            // Scl line before it's being gated by i2c_pmbus_disable
wire                       ack_cmd;            // Fault_management: ack/nack the received PMBus command
wire                       ack_byte;           // Fault_management: ack/nack the data b
wire [C_TIMEOUT_SIZE-1:0]  scl_time_cnt;       // SMBus Timeout counter
wire                       timeout_rst;        // Reset signal pulse after timeout violation
wire                       timeout_detect;     // Timeout detected clock low exeeds 25 ms 
reg                        sel_ara;            // Select General Call Alert Response Address if smablert pulled low (asserted)
reg                        imp_read_ff;            // Select General Call Alert Response Address if smablert pulled low (asserted)
reg                        first_rcv_header_ff;  // Asserted if the Adrres(header) received is the first slave address received over the bus 
reg [1:0]                  ack_data_cnt_ff;   
reg [3:0] ara_cnt_bit_valid_ff;
reg       arb_win_ff;
reg                        first_rcv_data_ff;    // Signal flag when the data byte is the first received Data byte (Data not the Header)
reg [2:0]                  prev_state_ff;        // Previous State (I2C control main state machine)
reg                        few_bit_xmt_ff;       // Signal Flag/Fault if the Master is reading two few bits from the PMBus SYSMONE slave interface 
reg                        few_bit_rcv_ff;       // Signal Flag/Fault if the Master is sending two few bits to the PMBus SYSMONE slave interface 
 
// Combinatorial logic Reg
reg                        en_cmd_dec;           // Control signal that enable the Decoding of the received command  
wire                       cmd_valid;            // Received command is a valid and supported PMBus command
wire                       scl_clean;            // Received command is a valid and supported PMBus command
wire                       sda_clean;            // Received command is a valid and supported PMBus command
wire                        start;            // Received command is a valid and supported PMBus command
wire                        stop;            // Received command is a valid and supported PMBus command
wire                        smbus_timeout_rst;            // Received command is a valid and supported PMBus command
 // =============================================================================
  <=: ComponentName :>_i2c_filter  i2c_filter_inst                               (                             
                                                        .clk                          ( clk                     ),
                                                        .rst                          ( rst                     ),
                                                        .scl_noisy                    ( scl_i               ),
                                                        .scl_clean                    ( scl_clean               ),
                                                        .sda_noisy                    ( sda_i               ),
                                                        .sda_clean                    ( sda_clean               ) 
                                                       );
//----------------------------------------------------------------------------
// Input Registers Process 
// Samples the incoming SDA and SCL with the system clock
//----------------------------------------------------------------------------
always @(posedge clk or posedge rst) begin 
  if(rst) begin
    sda_d1_ff     <= 1'b0; 
    sda_rin_ff    <= 1'b0;   
    sda_rin_d1_ff <= 1'b0;
    scl_d1_ff     <= 1'b0;   
    scl_rin_ff    <= 1'b0;  
    scl_rin_d1_ff <= 1'b0;
  end 
  else begin    
    sda_d1_ff      <= sda_clean;                // Register serial data input
    sda_rin_ff     <= sda_d1_ff;
    sda_rin_d1_ff  <= sda_rin_ff;  
    scl_d1_ff      <= scl_clean;                // Register serial clock input 
    scl_rin_ff     <= scl_d1_ff;  
    scl_rin_d1_ff  <= scl_rin_ff;
  end       
end
//----------------------------------------------------------------------------
// START/STOP Detect Process 
// This process detects the start condition by finding the falling edge of
// sda_rin and checking that SCL is high. It detects the stop condition on
// the bus by finding a rising edge of SDA when SCL is high.   
//----------------------------------------------------------------------------

assign sda_falling  =  sda_rin_d1_ff & ~sda_rin_ff;    // Find START condition
assign sda_rising   = ~sda_rin_d1_ff & sda_rin_ff;     // Find STOP condition
assign sda_changing = sda_falling | sda_rising;  
assign addr = 16'h<: print $C_I2C_SLAVE_ADDRESS :>;
assign addr_loc = addr[6:0];
assign  addr_loc_slave0 = addr_loc + 1;
assign  addr_loc_slave1 = addr_loc_slave0 + 1;

assign addr_match_master =  (addr_loc == i2c_header[7:1]) ? 1'b1:1'b0;
assign addr_match_slave0 =  (addr_loc_slave0 == i2c_header[7:1]) ? 1'b1:1'b0;
assign addr_match_slave1 =  (addr_loc_slave1 == i2c_header[7:1]) ? 1'b1:1'b0;


assign addr_match = addr_match_master | addr_match_slave0 | addr_match_slave1 ;

always @(posedge clk or posedge rst) begin                
  if(rst) begin                                        // START Detect Process
    sel_ff <= 2'b00;
  end
  else begin
 if (state == ACK_HEADER) begin
    if (addr_match_master == 1'b1) begin
      sel_ff <= 2'b00;
    end 
    else if (addr_match_slave0 == 1'b1) begin
     sel_ff <= 2'b01;
    end
    else if (addr_match_slave1 == 1'b1) begin
     sel_ff <= 2'b10;
    end
   else begin
    sel_ff <= sel_ff;
    end
 end
      end      
    end


always @(posedge clk or posedge rst) begin                
  if(rst) begin                                        // START Detect Process
    detect_start_ff <= 1'b0;
  end
  else begin
    if(state == HEADER) begin
      detect_start_ff <= 1'b0;
    end 
    else begin
      if(sda_falling) begin
        if(scl_rin_ff) begin
          detect_start_ff <= 1'b1;
        end     
        else begin
          detect_start_ff <= 1'b0;
        end 
      end      
    end
  end
end

always @(posedge clk or posedge rst) begin            //  STOP Detect Process              
  if(rst) begin                          
    detect_stop_ff <= 1'b0;
  end
  else if(detect_start_ff) begin        
    detect_stop_ff <= 1'b0; 
  end   
  else begin
    if(sda_rising) begin
      if (scl_rin_ff) begin
        detect_stop_ff <= 1'b1;
      end  
      else begin
        detect_stop_ff <= 1'b0;
      end
    end      
  end      
end
// Generate 1 clock cycle detect_stop and detect_start_signal signal


always @(posedge clk or posedge rst) begin            //  STOP Detect Process              
  if(rst) begin                          
    detect_stop_d_ff  <= 1'b0;
    detect_start_d_ff <= 1'b0; 
  end
  else begin
    detect_stop_d_ff <= detect_stop_ff;               // registred detect_stop
    detect_start_d_ff <= detect_start_ff;             // registred detect_start
  end
end

assign detect_stop_pulse  = detect_stop_ff && ~detect_stop_d_ff;
assign detect_start_pulse = detect_start_ff && ~detect_start_d_ff;
assign start       = detect_start_pulse;
assign stop        = detect_stop_pulse;
assign smbus_timeout_rst = timeout_rst; 

always @(posedge clk or posedge rst) begin
  if(rst) begin
    sda_setup_ff <= 1'b0;
  end  
  else begin
    if(sda_changing && ~scl_rin_ff) begin
      sda_setup_ff <= 1'b1;
    end  
    else if(sda_setup_cnt == TSUDAT) begin
      sda_setup_ff <= 1'b0; 
    end 
  end  
end
<=: ComponentName :>_i2c_upcnt_n #(C_SIZE) i2c_upcnt_setup_cnt_inst (
                                     .clk    ( clk           ),
                                     .rst    ( rst           ),
                                     .data   ( 4'b0000       ),
                                     .cnt_en ( sda_setup_ff  ),
                                     .load   ( sda_changing  ),
                                     .qout   ( sda_setup_cnt )
                                    );


//----------------------------------------------------------------------------
// Header/Address Shift Register & Control
//----------------------------------------------------------------------------               

always @(posedge clk or posedge rst) begin
  if(rst) begin
    i2c_header_en_ff <= 1'b0;
  end  
  else begin
    if ((state == HEADER) && scl_rising_edge_ff) begin
      i2c_header_en_ff <= 1'b1;
    end  
    else begin
      i2c_header_en_ff <= 1'b0;
    end  
  end  
end

<=: ComponentName :>_i2c_shift8 i2cheader_reg_inst (
                              .clk       ( clk              ),
                              .rst       ( rst              ),
                              .data_ld   ( 1'b0             ),                 // Will not load data_in
                              .data_in   ( 8'b00000000      ),
                              .shift_in  ( sda_rin_ff       ),
                              .shift_en  ( i2c_header_en_ff ),
                              .shift_out ( i2c_shiftout     ),
                              .data_out  ( i2c_header       )
                             );
//----------------------------------------------------------------------------
// SCL_EDGE_PROCESS
//---------------------------------------------------------------------------
// Generates a 1 clk wide pulse for both the rising edge 
// and the falling edge of scl_rin

always @(posedge clk or posedge rst) begin
  if(rst) begin
    scl_falling_edge_ff <= 1'b0;
    scl_rising_edge_ff  <= 1'b0;
    scl_f_edg_d1_ff     <= 1'b0;
    scl_f_edg_d2_ff     <= 1'b0;
    scl_f_edg_d3_ff     <= 1'b0;
  end
  else begin
    scl_falling_edge_ff <= scl_rin_d1_ff  & ~scl_rin_ff;
    scl_rising_edge_ff  <= ~scl_rin_d1_ff & scl_rin_ff;
    scl_f_edg_d1_ff     <= scl_falling_edge_ff;
    scl_f_edg_d2_ff     <= scl_f_edg_d1_ff;
    scl_f_edg_d3_ff     <= scl_f_edg_d2_ff;
  end  
end

//----------------------------------------------------------------------------
// Bit Counter & control
//----------------------------------------------------------------------------      

always @(posedge clk or posedge rst) begin
  if(rst) begin
    bit_cnt_en_ff <= 1'b0;
  end  
  else begin
    if(((state == HEADER)    && scl_falling_edge_ff) || 
       ((state == RCV_DATA)  && scl_falling_edge_ff) || 
       ((state == XMIT_DATA) && scl_falling_edge_ff)) 
    begin
      bit_cnt_en_ff <= 1'b1;
    end  
    else begin
      bit_cnt_en_ff <= 1'b0;
    end  
  end  
end

always @(*) begin
  if((state == IDLE)     || (state == ACK_HEADER) ||
     (state == ACK_DATA) || (state == WAIT_ACK  ) || 
      detect_start_ff) 
  begin
    bit_cnt_ld = 1'b1;
  end   
  else begin 
    bit_cnt_ld = 1'b0;
  end  
end

<=: ComponentName :>_i2c_upcnt_n #(4) bitcnt_inst (
                             .clk    ( clk           ), 
                             .rst    ( rst           ), 
                             .data   ( 4'b0000       ),                          // Count start value
                             .cnt_en ( bit_cnt_en_ff ), 
                             .load   ( bit_cnt_ld    ), 
                             .qout   ( bit_cnt       )
                             );
//----------------------------------------------------------------------------
// I2C Data Shift Register & Control
//----------------------------------------------------------------------------      

always @(posedge clk or posedge rst) begin
  if(rst) begin
    shift_reg_en_ff <= 1'b0;
  end   
  else begin
    if(((state == RCV_DATA)  && scl_rising_edge_ff && ~detect_start_ff)                                // Grab data byte
     ||((state == XMIT_DATA) && scl_f_edg_d2_ff    && ~detect_start_ff))
    begin                                                                                              // Send data byte
      shift_reg_en_ff <= 1'b1;
    end   
    else begin
      shift_reg_en_ff <= 1'b0;
    end
  end     
end

always @(posedge clk or posedge rst) begin
  if(rst) begin
    shift_reg_ld_ff <= 1'b0;
  end   
  else begin
    if((state == WAIT_ACK) 
      ||((state == ACK_HEADER) && (i2c_header[0] == 1'b1))                                             // Slave transmitter
      ||((state == RCV_DATA)   && detect_start_ff))
    begin
      shift_reg_ld_ff <= 1'b1;
    end   
    else begin
      shift_reg_ld_ff <= 1'b0;
    end
  end   
end

<=: ComponentName :>_i2c_shift8 i2cdata_reg_inst (
                            .clk       ( clk                  ), 
                            .rst       ( rst                  ), 
                            .data_ld   ( rdy_new_xmt_d_ff     ),// previously shift_reg_ld_ff 
                            .data_in   ( data_xmt_ff  ),   
                            .shift_in  ( sda_rin_ff           ), 
                            .shift_en  ( shift_reg_en_ff      ), 
                            .shift_out ( shift_out            ), 
                            .data_out  ( shift_reg            )
                           );


                          
always @(posedge clk or posedge rst) begin
  if(rst) begin
    i2c_busy_ff <= 1'b0;
  end   
  else begin
  if(rcv_pointer_ff == 2'b11) 
    begin
      i2c_busy_ff <= 1'b1;
    end
  else begin
   if (drdy)
    begin
      i2c_busy_ff <= 1'b0;
   end
  end   
end
end
                           
//----------------------------------------------------------------------------
// New transmit process
//----------------------------------------------------------------------------

always @(posedge clk or posedge rst) begin
  if(rst) begin
    shift_reg_ld_d1_ff  <= 1'b0;
    rdy_new_xmt_ff      <= 1'b0;               
    rdy_new_xmt_d_ff    <= 1'b0;
  end  
  else begin
    rdy_new_xmt_d_ff   <=  rdy_new_xmt_ff;
    shift_reg_ld_d1_ff <= shift_reg_ld_ff;
    if(state == XMIT_DATA) begin
      rdy_new_xmt_ff <= ~shift_reg_ld_ff & shift_reg_ld_d1_ff;
    end     
  end
end


<=: ComponentName :>_i2c_upcnt_n #(C_TIMEOUT_SIZE) scl_timeout_cnt_inst (
                                                   .clk    ( clk                    ),
                                                   .rst    ( rst                    ),
                                                   .data   ( {C_TIMEOUT_SIZE{1'b0}} ),
                                                   .cnt_en ( ~scl_rin_ff            ),
                                                   .load   ( scl_falling_edge_ff    ),
                                                   .qout   ( scl_time_cnt           )
                                                  );


assign timeout_detect = (scl_time_cnt == TIMEOUT) ? 1'b1 : 1'b0; 

always @(posedge clk or posedge rst) begin
  if(rst) begin
    timeout_rst_ff <= 1'b0;
  end
  else begin
    timeout_rst_ff <= timeout_detect;
  end
end  
// Generate Pulse each time a timeout is detected
assign timeout_rst = (~timeout_rst_ff) && timeout_detect; 

//----------------------------------------------------------------------------
// Data Register 
//----------------------------------------------------------------------------

always @(posedge clk or posedge rst) begin
  if(rst) begin
    data_rcv     <= 1'b0;    
    new_rcv_data_ff <= 1'b0;           // New receive data - like a valid signal
  end                         
  else begin
    if((state == ACK_DATA) && scl_falling_edge_ff) begin
      data_rcv     <= shift_reg;
      new_rcv_data_ff <= 1'b1;
    end
    else begin
      data_rcv     <= data_rcv;
      new_rcv_data_ff <= 1'b0;
    end
  end  
end

 always @(posedge clk or posedge rst) begin                                     // Sample sda_rin for use in checking the  
  if(rst) begin                                                                // acknowledge bit receieved by the controller
    sda_sample_ff <= 1'b0;
  end  
  else if(scl_rising_edge_ff) begin     
    sda_sample_ff <= sda_rin_ff;
  end  
end

always @(posedge clk or posedge rst) begin
  if(rst) begin
    first_rcv_data_ff <= 1'b0;
    prev_state_ff     <= 3'b0;
  end
  else begin
    prev_state_ff <= state;    
    if (state == IDLE) begin
      first_rcv_data_ff <= 1'b0;
    end
    else begin
      if ((prev_state_ff == ACK_HEADER) && (state == RCV_DATA) ) begin
        first_rcv_data_ff <= 1'b1;
      end
      else if ((prev_state_ff == ACK_DATA) && (state == RCV_DATA)) begin 
        first_rcv_data_ff <= 1'b0;
      end
    end
  end  
end


always @(posedge clk or posedge rst) begin
  if(rst) begin
    first_rcv_header_ff <= 1'b0;
  end
  else begin
    if (state == IDLE) begin                                                                             // Clear when IDLE
      first_rcv_header_ff <= 1'b0;
    end
    else begin
      if ((prev_state_ff == IDLE) && (state == HEADER)) begin                                            // Set when the first Header is being received 
        first_rcv_header_ff <= 1'b1;
      end

      if (((state == RCV_DATA) || (state == XMIT_DATA)) && (prev_state_ff == ACK_HEADER)) begin          // Clear when a second Header is received
        first_rcv_header_ff <= 1'b0;
      end
    end
  end  
end

assign ack_cmd    = 1'b1 ;
assign ack_byte   = 1'b1;
                                                                    
//----------------------------------------------------------------------------
// Main State Machine Process 
//----------------------------------------------------------------------------                                                                                   

always @(posedge clk or posedge rst) begin
  if(rst) begin                                           
    state   <= IDLE;
    sm_stop <= 1'b0;
  end                                                                          
  
  else if(scl_f_edg_d2_ff||detect_stop_pulse||timeout_rst) begin  
     
    case (state)
        
        IDLE :       begin
                       if(detect_start_ff) begin
                         state <= HEADER;
                       end  
                     end    
              
        HEADER :     begin    
                       if(bit_cnt == CNT_DONE) begin         // Count to 8
                         state <= ACK_HEADER;
                       end  
                     end    

        ACK_HEADER : begin
                       if(sda_sample_ff == 1'b0) begin       // Ack has been received
                        if(addr_match) begin                // If aas_ff is true then addressed as slave
                           if(i2c_header[0] ==  1'b0) begin  // Check i2c_header[0] to determine direction
                             state <= RCV_DATA;              // Receive Mode
                           end                      
                           else begin
                             state <= XMIT_DATA;             // Transmit Mode  
                           end 
                         end                      
                         else begin
                           state <= IDLE;
                         end 
                       end   
                       else begin
                         state <= IDLE;
                       end  
                     end   

        RCV_DATA :   begin
                       if(detect_start_ff) begin
                         state <= HEADER;
                       end  
                       else if(bit_cnt == CNT_DONE) begin
                         if(~addr_match) begin                  // TODO ??? - why check address match here?
                           state <= IDLE;
                         end  
                         else begin
                           state <= ACK_DATA;
                         end  
                       end
                     end  

        XMIT_DATA :  begin
                       if(detect_start_ff) begin
                         state <= HEADER;
                       end  
                       else if(bit_cnt == CNT_DONE) begin   // Wait for acknowledge
                         state <= WAIT_ACK;
                       end  
                     end
                         
        ACK_DATA :   begin
                       state <= RCV_DATA;
                     end    

        WAIT_ACK :   begin
                       if(sda_sample_ff == 1'b0) begin
                         state <= XMIT_DATA;
                       end  
                       else begin
                         state <= IDLE;
                       end   
                     end
                         
        default :    begin
                       state <= IDLE;
                     end                                                                                                                   
     endcase
     
     if(detect_stop_pulse||timeout_rst) begin                               
       state   <= IDLE;
       sm_stop <= 1'b0;
     end
     
  end  
end

//----------------------------------------------------------------------------
// Slave SDA 
//----------------------------------------------------------------------------   

// The following clocked procedure control the sda line tri-state
// The Bus is by default pulled high (released) by an external level shifter( on Board)
// The Slaves takes control over the sda line to either transmit data (XMIT_DATA) state
// or to ACK a Byte received from the master (ACK_HEADER and ACK_DATA)
// The slave always ack it's Header (address received)
// However if a fault occurs the slave NACK the received command and the next data bytes
// If the slave is a transmitter and a fault event is detected the Slave send all ones
// until the next stop condition

always @(posedge clk or posedge rst) begin
  if(rst) begin
    slave_sda_ff <= 1'b1;
  end  
  else begin
    if((addr_match && (state == ACK_HEADER)) 
     ||(state == ACK_DATA)) 
    begin      
      slave_sda_ff <= 1'b0;                                                      
    end                                                                           
    else if(state == XMIT_DATA && ack_byte) begin                                    
      slave_sda_ff <= shift_out;
    end  
    else begin
      slave_sda_ff <= 1'b1;  
    end 
  end   
end

//----------------------------------------------------------------------------
// Bus Busy Bit             
//----------------------------------------------------------------------------

always @(posedge clk or posedge rst) begin
  if(rst) begin
    bus_busy_ff    <= 1'b0;
  end
  else begin         
     if(detect_start_ff) begin
       bus_busy_ff <= 1'b1;
     end   
     if(detect_stop_ff) begin
       bus_busy_ff <= 1'b0;
     end   
  end  
end


// -----------------------------------------------------------------------------
// Transmit and Receive Data processes
// -----------------------------------------------------------------------------

always @(posedge clk or posedge rst) begin                
  if(rst) begin  
    xmt_pointer_ff <=  1'b0;
    rcv_pointer_ff <= 2'b00;                              
    data_rcv_ff    <= 32'b0;
    drp_data_ff    <= 16'b0;
    data_xmt_ff    <=  8'b0;
    new_cmd_ff     <=  1'b0;   
  end 
  else begin
  
    new_cmd_ff    <= 1'b0;
    
    if(drdy) begin   
      drp_data_ff   <= do_pl;                         // Register drp data in
    end  
            
    if(rdy_new_xmt_ff) begin                             // TODO: is this a one shot on clk or multiple clock cycles
                      
      xmt_pointer_ff <=  xmt_pointer_ff + 1;          // Increment transmit pointer
          
      case(xmt_pointer_ff)                            // Transmit data process
           1'b0: begin                                // TODO : This my change to the interface
                   data_xmt_ff <= drp_data_ff[15:8];  // Previously: data_xmt_ff <= drp_data_ff[7:0];
                 end  
           1'b1: begin
                   data_xmt_ff <= drp_data_ff[7:0];   // Previously: data_xmt_ff <= drp_data_ff[15:8]; 
                 end
        default: ; 
      endcase       
    end 
     
    if(new_rcv_data_ff) begin
    
      rcv_pointer_ff <=  rcv_pointer_ff + 1;          // Increment receive pointer
      
      case(rcv_pointer_ff)                            // Receive data process 
          2'b00: begin     
                   data_rcv_ff[7:0]   <= data_rcv;
                 end     
          2'b01: begin 
                   data_rcv_ff[15:8]  <= data_rcv;
                 end
          2'b10: begin 
                   data_rcv_ff[23:16] <= data_rcv;
                 end
          2'b11: begin 
                   data_rcv_ff[31:24] <= data_rcv;
                   new_cmd_ff         <= 1'b1;
                 end                                
        default: ; 
      endcase              
    end
    
    if(start || stop || smbus_timeout_rst) begin      // Should take precedence
      xmt_pointer_ff <=  1'b1;                        // Reset transmit pointer to 1 start or stop condition 
      rcv_pointer_ff <= 2'b00;                        // Reset receive pointer to zero on start       
    end
       
  end              
end 
  
//-----------------------------------------------------------------------------
// Command decode process
//-----------------------------------------------------------------------------

always@(posedge clk or posedge rst) begin
  if(rst) begin
    stat_ff <=  2'b0;
    data_ff <= 16'b0;
    addr_ff <= 10'b0;  
    den_ff  <=  1'b0;
    dwe_ff  <=  1'b0;
    //sel_ff  <= 2'b0;
  end
  else begin
      
    if(new_cmd_ff) begin                         // Decode the DRP command
      data_ff <= data_rcv_ff[15:0];
      addr_ff <= data_rcv_ff[23:16];                 
      stat_ff <= data_rcv_ff[31:30];          
      //sel_ff <= data_rcv_ff[25:24];          
      case(data_rcv_ff[29:26])                   // CMD used to set den & dwe                  
          4'b0001: begin
                     den_ff <= 1'b1;
                     dwe_ff <= 1'b0;
                   end              
          4'b0010: begin            
                     den_ff <= 1'b1;             // TODO: check if I need to add jtag_no_config   
                     dwe_ff <= 1'b1;
                   end              
          default: begin            
                     den_ff <= 1'b0;
                     dwe_ff <= 1'b0;
                   end
      endcase                             
    end 
    
    if(start || stop || smbus_timeout_rst) begin  //  TODO: Check that this is 1 shot on clk    
      den_ff <= 1'b0;
      dwe_ff <= 1'b0;
    end        
  end    
end        

always @(posedge clk or posedge rst) begin            //  STOP Detect Process              
  if(rst) begin                          
    den_d_ff  <= 1'b0;
    dwe_d_ff <= 1'b0; 
  end
  else begin
    den_d_ff <= den_ff;               // registred detect_stop
    dwe_d_ff <= dwe_ff;             // registred detect_start
  end
end

//----------------------------------------------------------------------------
// Output assignments
//----------------------------------------------------------------------------
assign sda_t = slave_sda_ff;                         // Tristate polarity 1 -> tri-state: sda line released
//assign sda_t   = en_test_ctrl_i2c_sda_ts  ? test_ctrl_i2c_sda_ts : sda_t_i;        // SDA Tristate driver controls                
//assign scl_t_i = sda_setup_ff ? 1'b0 : 1'b1;                                       // SCL Tristate driver controls: polarity (1 -> tri-state, 0 -> drive)
assign scl_o   = 1'b0;
assign scl_t   = 1'b1;                              // Tristate polarity 1 -> tri-state: scl line released 
assign sda_o   = 1'b0;
assign i2c_busy   = i2c_busy_ff;

assign di_pl =  data_ff;   // Transmit data out
assign daddr_pl     = addr_ff;       // DRP address command
assign den_pl      = den_ff && ~den_d_ff;        // DRP Enable
assign dwe_pl      = dwe_ff && ~dwe_d_ff;        // DRP write enable
assign sel_pl      = sel_ff;        // DRP write enable
endmodule
