General bug fixes, refactor and minor additions