Integrate changes from user1256821 (SO) to be more flexible on background size and remove magic numbers