Simplified the code and improved it. Removed some crashes.