Minor bug fixes, made some copy/pasted code a function