# Main entry point for running autopep8 to convert a file in place
# Needed because autopep8 can't accept encoding for the text being 
# converted.  Wing is always passing utf-8 encoded files.

try:
  
  import sys
  sys.path.append('.')
  import autopep8
  
  if __name__ == '__main__':
    ignore = set(sys.argv[1].split(','))
    line_length = int(sys.argv[2])
    fname = sys.argv[3]
    
    f = open(fname, 'rb')
    txt = f.read()
    f.close()
    utxt = txt.decode('utf-8')
  
    options = {
      'max_line_length': line_length,
      'ignore': ignore,
    }
    new_utxt = autopep8.fix_code(utxt, options)
    
    new_txt = new_utxt.encode('utf-8', 'strict')
    if new_txt != txt:
      f = open(fname, 'wb')
      f.write(new_txt)
      f.close()
      sys.exit(0)
      print('success')
    else:
      sys.exit(1)
      print('no-changes')
     
except SystemExit:
  pass

except:
  print('error')
  import traceback
  traceback.print_exc()
  sys.exit(-1)
