Moved error detection to separate function