Major refactor in progress, TODO error checking and bugfixing