Rewrote to use .pop(), also documented the code