first decent rewrite version