Fixed shutting down crash when plot window open. Cleaned up code