Cleaned up the code (Unfortunately, I haven't been able to test it all).