complete algorithm, not working