Fixed inactive and background mode bugs. Refactored some code