Attempted to simplify code and remove possible bugs