new algorithm for add and edit