Reorganize code logic