Fix startup bug and tweak some code