rewritten - highly optimized