Fixed issues to do with orphans, and condensed code by combining cases
and abstracting common operations.