Add more meaningful error messages, minor refactorings