Fixes issues #57 and #48.

Fixes issues #57 and #48 

A lot of big changes, requires proper testing.