Added support for python 3.
Added some checks to prevent crashes.