Factorize some error-checking code

Plus some cosmetics changes