Moved some code around for readability