Refactored some backend code that was driving me nuts.

A lot cleaner now.