Fix bugs and cleanup code