Added more explanation and rearranged codes.