Refactoring

Condensed and moved logic to the top.