added more comments, reduced two functions to one