Sleep algorithm