Major code organization overhaul and bug fixes