Significantly cleaned code and moved some repeatedly called blocks to
helper functions