working out algorithm