Fix for bugs #174 and #266.

Add check to avoid calling methods on undefined objects.  Prevents bugs such as #174 and #266.