Improved input validation

Major refactoring to widely improve input validation