Cleaned up main thread handling code