rewrite, hopefully clearer and more efficient