added comments and speeded code up