Added some comments and rewrote a function to reuse a portion of code instead of repeating it