Well I for one don't see where mem_index is being set. Also the commands

write mem_index,temp
write 0,mem_index

would by default be writing over the contents of memory location 0 if mem_index is not set.