Fixed the crash on resume issue and reorganized the code.