updated the code to handle foreground and background correctly