Restructuring logic and removing duplicated code