added final algorithm