Code refactoring, some corrections and better errors