Fix loop issue and shorten some code