Ported some improvements from @Shammah