Moving popup logic to background, tidy up the structure