Move offset calculation code into a utility function