Fixed #259
Fixed #261. Warning! Mass refactoring! Please test!