Big code reorganization + bug fixes