Add more documentation and moved optimization to its own file