`timescale 1ns / 1ps

`include "src/clkdiv.v"

module io_controller #(
	parameter CLK_DIV = 100,
	parameter FRAME_SIZE = 16,
	
	// AUTOCALCULATED
	parameter FRAME_IDX_MSB = $clog2(FRAME_SIZE - 1) - 1
)(
	input clk, rst, clear,
	input [7:0] leds,
	output reg [7:0] sw,
	
	output mosi,
	input miso,
	output load,
	output sclk,
	output rstn
);

wire rstclr = rst || clear;

wire strobe;

clkdiv #(
	.DIV(CLK_DIV)
) sclk_div (
	.clk(clk),
	.rst(rst),
	.clear(clear),
	
	.sclk(sclk),
	.pos(),
	.neg(strobe)
);

reg [FRAME_SIZE-1:0] data;
reg [FRAME_IDX_MSB:0] idx;

always @(posedge clk)
begin
	if (rstclr)
	begin
		data <= 0;
		sw <= 0;
	end
	else
	begin
		if (strobe)
		begin
			if (idx == (FRAME_SIZE - 1'b1))
			begin
				sw <= data[7:0];
				data <= {miso, 7'b0, leds};
			end
			else
			begin
				data <= {miso, data[15:1]};
			end
		end
	end
end

always @(posedge clk)
begin
	if (rstclr)
	begin
		idx <= (FRAME_SIZE - 1'b1);
	end
	else
	begin
		if (strobe)
		begin
			if (idx == (FRAME_SIZE - 1'b1))
			begin
				idx <= 0;
			end
			else
			begin
				idx <= idx + 1'b1;
			end
		end
	end
end

assign rstn = !rstclr;
assign load = idx == (FRAME_SIZE - 1'b1);
assign mosi = data[0];


endmodule
