updated version of previous algo