fixed UnboundLocalError: j referenced before assignment