Several logic errors fixed.