Code restructuring and minor bugfix