More code cleanups. Separated some stuff into new functions.