Major rewrite, simplification, more logging and tests