// buffer.asm
//
// read 4 bytes of textfile from SPI starting at address 0x040000 and write
// the string to SRAM. Finally read the string from SRAM and send
// the string to UART_TX
//
// Put your code here:
// cat.asm
//
// load spi flash rom starting at address 0x040000 and write the
// data to UART_TX
//
// Put your code here:

// D=M -> 1111110000010000
// M=D -> 1110001100001000
// M=0 -> 1110101010001000

// read data starting at address
// 0x03 0x04 0x00 0x00
    @3
    D=A
    @128
    M=D
    @4
    D=A
    @129
    M=D
    @130
    M=0
    @131
    M=0

// wake up from deep power down and wait 3us
// 0xAB
    @171
    D=A
    @SPI
    M=D
        @4
        D=A
        @COUNT
        M=D
        (DECR1)
        @COUNT
        DM=M-1
        @DECR1
        D;JGT
    @511
    D=A
    @SPI
    M=D
        @21
        D=A
        @COUNT
        M=D
        (DECR2)
        @COUNT
        DM=M-1
        @DECR2
        D;JGT

//command stack base address 
    @128
    D=A
    @CHARREAD
    M=D
    @WRITECOUNT
    M=0
    @SENDCOUNT
    M=0
    @WAITREAD
    0;JEQ

(WAITREAD)
    @SPI
    D=M
    @WAITREAD
    D;JLT
    @READ
    0;JMP

(READ)
    // read
    @CHARREAD
    A=M
    D=M
    @SPI
    M=D
    @CHARREAD
    M=M+1
    @132
    D=A
    @CHARREAD
    D=D-M
    @WAITREAD
    D;JGT
    @ENDREAD
    0;JMP

(ENDREAD)
    @WAITWRITE
    0;JMP

(WAITWRITE)
    @SPI
    D=M
    @WAITWRITE
    D;JLT
    @WRITE
    0;JMP

(WRITE)
    @SPI
    M=0
        @4
        D=A
        @COUNT
        M=D
        (FROMSPI)
        @COUNT
        DM=M-1
        @FROMSPI
        D;JGT
    @WRITECOUNT
    D=M
    @SRAM_A
    M=D
    @SPI
    D=M
    @SRAM_D
    M=D
    @WRITECOUNT
    M=M+1
    @8
    D=A
    @WRITECOUNT
    D=D-M
    @ENDWRITE
    D;JEQ
    @WAITWRITE
    0;JMP

(ENDWRITE)
    @WAITBOOT
    0;JMP


(WAITBOOT)
    @UART_TX
    D=M
    @BOOT
    D;JEQ
    @WAITBOOT
    0;JMP

(BOOT)
    @SENDCOUNT
    D=M
    @SRAM_A
    M=D
    @SRAM_D
    D=M
    @UART_TX
    M=D
    @SENDCOUNT
    M=M+1
    @8
    D=A
    @SENDCOUNT
    D=D-M
    @ENDBOOT
    D;JEQ
    @WAITBOOT
    0;JMP

(ENDBOOT)
    @POLL
    0;JMP


// LED<->BUT loop
(POLL)
    @BUT
    D=!M
    @LED
    M=D
    @POLL
    0;JMP
