Refactor sub optimal code