Fix generation of duplicated records. Refactor code.