Added a check for invalid tokens. These shouldn't occur within the scope of this code, but for robustness the check is there.