Tweaked code / rewrote function