added comments explaining algoritm