Fix various minor errors.

Fix errors like undefined variables, wrong array index, etc.