Added some error checking
Merged with latest version