Fix range issue in inventory and add additional error checking

Fixes #6331