
; Let's write a program!

	.ORIG	x3000

; R0 = string pointer
; R1 = pointer to current block
; R6 = temporary
	LEA	R0,STRINGS	; initialize R0 and R1
	LD	R1,BLOCKS

MAINLOOP			; check for remaining string
	LDR	R6,R0,#0	
	BRz	STRINGSDONE

; copy current string pointer (R0) into next block (at R1)
	STR	R0,R1,#0

; find end of string in R2
	ADD	R2,R0,#0	; copy R0 into R2
FINDEND	LDR	R6,R2,#0	; next char in string
	BRz	FOUNDEND
	ADD	R2,R2,#1
	BRnzp	FINDEND

FOUNDEND
	ADD	R0,R2,#1

; time to insert the new block into the list
; R3 = pointer to block pointer to change
	LEA	R3,LIST

; need to find the right insertion point for the block

; check first whether we have reached the end of the list
CHECKABLOCK
	LDR	R6,R3,#0
	BRz	INSERTBLOCK

; otherwise, compare the strings
; R4 = new block's string
; R5 = existing block's string
	LDR	R4,R1,#0
	LDR	R5,R6,#0
; R6 = character from new block's string
; R7 = character from existing block's string
COMPARESTRINGS
	LDR	R6,R4,#0
	BRz	INSERTBLOCK
	LDR	R7,R5,#0
	NOT	R7,R7
	ADD	R7,R7,#1
	ADD	R6,R6,R7
	BRp	LOOKATNEXT
	BRn	INSERTBLOCK
	ADD	R4,R4,#1
	ADD	R5,R5,#1
	BRnzp	COMPARESTRINGS

LOOKATNEXT
	LDR	R3,R3,#0
	ADD	R3,R3,#1
	BRnzp	CHECKABLOCK

INSERTBLOCK

STRINGSDONE	; have processed all strings

	HALT

; some data
LIST	.FILL	x0000	; list starts empty
BLOCKS	.FILL	x4000
STRINGS
	.STRINGZ "here"
	.STRINGZ "is"
	.STRINGZ "a"
	.STRINGZ "set"
	.STRINGZ "of"
	.STRINGZ "strings"
	.STRINGZ ""

	.END

