fixed LENGTH check, refactored error handling