Bugfix 1003

Rewrote the code