latest code - still very messy