optimized, but still ugly