Update the code to avoid having duplicated rows

I also reformatted some parts of the code.