The actual bug-free version

Cleaned up some of code too