module led_chaser(
// module inputs
CLOCK_50,
KEY,
SW,
// module outputs
SSn_D,
MOSI_D,
SCLK_D,
LEDR
);

input [3:0] KEY;
input CLOCK_50;
input [15:0] SW;
output [3:0] SSn_D;
output MOSI_D, SCLK_D;
output [15:0] LEDR;

assign LEDR = LEDS;

// Reset wire
wire RESETn;
assign RESETn = KEY[0];

wire [15:0] LEDS;
reg [9:0] CLKDIV0, CLKDIV1, CLKDIV2;

`define DIVVAL0 1000-1
`define DIVVAL1 1000-1
`define DIVVAL2 50-1

// Clock Divider
always @(posedge CLOCK_50 or negedge RESETn)
	if (~RESETn) CLKDIV0 <=`DIVVAL0;
	else if (CLKDIV0 > 10'b0)
      CLKDIV0[9:0] <= CLKDIV0[9:0] - 1'b1;
    else
      CLKDIV0[9:0] <= `DIVVAL0;

always @(posedge CLOCK_50 or negedge RESETn)
	if (~RESETn) CLKDIV1 <=`DIVVAL1;
	else if (CLKDIV0[9:0] == 10'b0)
      begin
      if (CLKDIV1 > 10'b0)
        CLKDIV1[9:0] <= CLKDIV1[9:0] - 1'b1;
      else
        CLKDIV1[9:0] <= `DIVVAL1;
      end
		
always @(posedge CLOCK_50 or negedge RESETn)
	if (~RESETn) CLKDIV2<=`DIVVAL2;
	else if ((CLKDIV1[9:0] == 10'b0) & (CLKDIV0[9:0] == 10'b0))
      begin
      if (CLKDIV2 > 10'b0)
        CLKDIV2[9:0] <= CLKDIV2[9:0] - 1'b1;
      else
        CLKDIV2[9:0] <= `DIVVAL2;
      end

// ring_sr

ring_sr ring_shift_reg(
	.CLK(CLOCK_50),
	.RSTn(RESETn),
	.ENA((CLKDIV0[9:0] == 10'b0) & (CLKDIV1[9:0] == 10'b0) & (CLKDIV2[9:0] == 10'b0)),
	.PATTERN(SW),
	.Q(LEDS[15:0]));
	
// SPI-Master
spi_master spimaster(
  .RESETn(RESETn),
  .CLK(CLOCK_50),
  .CLK_DIVIDER(8'd10),
  .SLAVE_SELECT(8'h1),
  .DATA_LENGTH(2'd1),
  .MODE(2'd1),
  .MISO(1'b1),
  .TX({16'h0,LEDS}),
  .RUN((CLKDIV0[9:0] == 10'b0) & (CLKDIV1[9:0] == 10'b0) & (CLKDIV2[9:0] == 10'b0)),
  //module outputs
  .RX(),
  .SCLK(SCLK_D),
  .MOSI(MOSI_D),
  .SSn(SSn_D),
  .BUSY(),
  // module test outputs
  .SYNC_TEST(),
  .STATE_TEST(),
  .ENA_TEST()  
);
	
endmodule
