Changes to code structure and some bugs fixed