Merge pull request #2 from GrahamCampbell/master

Bug fixes and optimizations. Thx to GrahamCampbell