Completely rewritten: much better code