Reworked nextValidId handling