Parameterize some things and move vars to the top; formatting and cleanup