restructuring and tweaks, introduced some bugs