Fixed a nasty bug based on @njx's feedback.