`include "oled_init.v"
`include "oled_cls.v"

module fpga (
    input CLK,
    input RST,
    output CSN,
    output SDIN,
    output SCLK,
    output DCN,
    output RESN,
    output VBATN,
    output VDDN,
    output [1:0] Led
);

reg [7:0] clock_counter='b0;
reg init_fin_latched='b1;
reg cls_fin_latched='b1;

assign Led[0]=init_fin_latched;

oled_init i_oled_init(
    .clk(CLK),
    .reset(RST),
    
    .init_start(init_start),
    .init_fin(init_fin),
    
    .spi_csn(init_csn),
    .spi_sdo(init_sdin),
    .spi_sclk(init_sclk),
    .spi_dcn(init_dcn),
    .spi_resn(RESN),
    .spi_vbatn(VBATN),
    .spi_vddn(VDDN)
);

oled_cls i_oled_cls(
    .clk(CLK),
    .reset(RST),

    .cls_start(cls_start),
    .cls_fin(cls_fin),

    .spi_csn(cls_csn),
    .spi_sdo(cls_sdin),
    .spi_sclk(cls_sclk),
    .spi_dcn(cls_dcn)
);

assign init_start = (((&clock_counter)==1'b1) && (init_fin_latched==1'b0)) ? 1'b1 : 1'b0;

assign CSN  = init_fin_latched ? cls_csn  : init_csn;
assign SDIN = init_fin_latched ? cls_sdin : init_sdin;
assign SCLK = init_fin_latched ? cls_sclk : init_sclk;
assign DCN  = init_fin_latched ? cls_dcn  : init_dcn;

always @(posedge CLK) begin
    if (RST) begin
        clock_counter <= 'b0;
        init_fin_latched <= 'b0;
        cls_fin_latched <= 'b0;
    end else begin
        clock_counter <= clock_counter + 1;
        if (init_fin)
            init_fin_latched <= 'b1;
        if (cls_fin)
            cls_fin_latched <= 'b1;
    end
end

assign cls_start = init_fin;

assign Led[1] = cls_fin_latched;

endmodule
