// Whenever we receive a data block, start spitting bytes out into the audio
// buffer bram. This could always be clocked at the 25MHz default speed clock,
// or it could switch over like the writer has to
module read_data(
    input clk,
    input reset,
    input sd_data,
    audio_buffer_interface.driver buffer
);
//  Block data is a start bit, 512 bytes sent msb first, then a CRC16 and end
//  bit.

// NOTE: This doesn't check which side of the buffer the audio player is
// reading from, so theoretically it could overwrite audio that's being
// played. However, as long as the sd card controller doesn't request extra
// blocks this shouldn't be an issue

localparam BLOCK_SIZE=512*8+16+2;
logic [$clog2(BLOCK_SIZE):0] counter;

logic [7:0] byte_shift;

logic [3:0] byte_counter;

assign buffer.clka = clk;

always_ff @(posedge clk) begin
    if (reset) begin
        buffer.ena <= 0;
        buffer.addra <= '1;
        buffer.dina <= 0;
    end
    else begin
        // We ignore the lower 17 bits of the block
        if (counter > 16) begin
            counter <= counter - 1;
            byte_shift <= {byte_shift[6:0],sd_data};
            byte_counter <= byte_counter - 1;

            // Store received byte in audio buffer and reset counter
            if (byte_counter == 0) begin
                byte_counter <= 7;
                buffer.dina <= byte_shift;//{byte_shift[6:0],sd_data};
                buffer.ena <= 1;
            end

            // Turn the enable signal off so we don't accidentally write
            // anything weird
            if (byte_counter == 4) begin
                buffer.ena <= 0;
                buffer.addra <= buffer.addra + 1;
            end

        end
        else if (counter != 0)
            counter<=counter-1;
        else if (sd_data == 0) begin
            counter <= BLOCK_SIZE-1;
            byte_counter <= 8;
        end
    end
end

endmodule
