Changed ben's code to take care of edge cases