Code improvements, remove code duplication