Program works, but my solution was a little hackish and might not work for all cases. Maybe should ask if there's a better way.