replaced [-1] with .last and used replace_last where possible
rearranged for readability