Refactoring: using guard clauses to split functions into smaller ones

Using guard clauses and pattern matching makes it clear what cases each
function handles. Also reordered functions to handle cases from left child
to right child.