Code restructurization and bug fixes