Minor code fixes and partial code optimization