Fix bugs and organize code