Refactored to limit use of vars to the the necessary ones.