Cleaned up logic so branches are only got when needed (much faster)