Fixed reference counting bugs in main mode