improvements on following algorithm