Various bug fixes, build refactoring