Remove code duplication, add more comments