Rename local vars
Add some functions
Fix two bugs