Fixed some variable scoping and added some javadocs