More elaborate algorithm, with a few bugfixes and nice fuzzing