Fixed a couple of bugs and changed a variable name for clarity