Check for invalid ids and some refactoring