Added some comments and moved code to more logical places