document and simplify the logic