Thinning algorithm