Refactor margin moving code