Major code refactor

This refactor changes a lot of the code format and cleans up the performance in a number of areas. It is primarily targeted at better preparing the code to be wrapped using Cordova. It's not entirely functional yet, but I want to implement the rest of the changes using smaller branch merges and build on this request.