Fixed #89

Found some bugs, and squashed them. Function now works as promised.