Paul's updated code, fixed some bugs