reorganize code; cleanup logic