Some code restructure and cleanup