Bugfix variable names, tidy up code