Code design and bug fixed