Remove code duplication, add documentation