Added performance improvements

Removed the giant for-loops and replaced them entirely with if-then
statements that execute ONLY when the state of the key is checked.