Restructured and adjusted for iOS 6+ (probably still works on iOS 5)