Clean up codes and fix small bugs