Move some code around and extract methods