enhance helper function `pad` with a better algorithm