Refactoring, fix bugs, added guard for duplicates entries