Completed logic for variable
Fixed up loop logic