Fixed space substitution error and made more robust

Added check to cope with zero length instances.