Cleaned up the code and made it more readable, there maybe some problems, if so please let me know.