Added additional documentation. Tested improved code and found that it produces correct output.