re-structured some logic