Restructuring and bug fixes