lots of bug fixes. Refactored to make more sense logically.