refinements on algorithm, checking edge cases