//*****************************************************************************
// Boot loader. Load HACK code from SPI address 0x010000 (64k) into SRAM and GO
//*****************************************************************************
//
// Put your code here:


// @R0
// D=M
//
// // Shift left by 8 bits by doubling 8 times
// D=D+D   // Shift left by 1 bit
// D=D+D   // Shift left by another bit
// D=D+D   // Shift left by another bit
// D=D+D   // Shift left by another bit (4-bit shift so far)
// D=D+D   // Shift left by another bit
// D=D+D   // Shift left by another bit
// D=D+D   // Shift left by another bit
// D=D+D   // Shift left by another bit (now D contains 0xEA00)
//
// D=M -> 1111110000010000
// M=D -> 1110001100001000
// M=0 -> 1110101010001000
//
// // Store the result in R1
// @R1
// M=D
//
//
// 00010000          0 -> add 8 times and store to lhs
// 00000001          1 -> add to lhs and store to word
// 0001000000000001  write all the words to sram
//
// 0001000000000001
// 1111110001010000
// 0001000000000000
// 1110001100001000
// 0000000000000000
// 1110101010000111


// read data starting at address
// 0x03 0x01 0x00 0x00
    @3
    D=A
    @100
    M=D
    @1
    D=A
    @101
    M=D
    @102
    M=0
    @103
    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
    @100
    D=A
    @READCOMMAND
    M=D
    @DIRECTION
    M=0
    @WORDCOUNT
    M=0
    @WAITREAD
    0;JEQ

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

(READ)
    // read
    @READCOMMAND
    A=M
    D=M
    @SPI
    M=D
    @READCOMMAND
    M=M+1
    @104
    D=A
    @READCOMMAND
    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
    @DIRECTION
    D=M
    @WESTWORD
    D;JEQ
    @EASTWORD
    D;JGT

(WESTWORD)
    @SPI
    D=M
    @DEBUG0
    M=D
    DM=D+M
    DM=D+M
    DM=D+M
    DM=D+M
    DM=D+M
    DM=D+M
    DM=D+M
    DM=D+M
    @DIRECTION
    M=1
    @WAITWRITE
    0;JMP

(EASTWORD)
    @WORDCOUNT
    D=M
    @SRAM_A
    M=D
    @SPI
    D=M
    @DEBUG1
    M=D
    @DEBUG0
    D=M
    @DEBUG1
    D=D+M
    @SRAM_D
    M=D
    @DIRECTION
    M=0
    @WORDCOUNT
    M=M+1
    @57343
    D=A
    @WORDCOUNT
    D=D-M
    @ENDWRITE
    D;JEQ
    @WAITWRITE
    0;JMP

(ENDWRITE)
    @185
    D=A
    @SPI
    M=D
    @GO
    M=1
