Bug fixes, better error signaling and code reorganization