Fixing a few bugs, reorganizing the core script