fixed bug on edge case and simplified code somewhat