Fix some bugs and add smart insertion