#!/usr/bin/python3
"""list the contents of a directory, sorted and clustered by extension
   special handling for Linux hidden files, and filenames with embedded spaces"""
import shutil, os, sys, stat

def main(path, doQuotes):
  # get the page width, fall back to 80
  cols = shutil.get_terminal_size().columns

  try:
    mat = os.scandir(path)
  except:
    print("File not found: " + path); sys.exit(1)

  def extractExtension(de):
    filename = de.name
    if de.is_dir():
      return "<dir>",filename
    if filename[0]=='.':	# linux hidden files
      return '.',filename[1:]
    r = filename.rfind('.') # ordinary files
    if r==-1:
      return "",filename  # no-ext files
    return filename[r:],filename[:r] 
  mat_exts = map(extractExtension,mat)

  mat_exts = sorted(mat_exts)

  def addQuotesToFilename(ext_data):
    if ' ' in ext_data[1] and doQuotes:
      return ext_data[0], '"'+ext_data[1]+'"'
    return ext_data
  mat_exts = map(addQuotesToFilename,mat_exts)

  curext = None; line = ''
  for ext,fname in mat_exts:
    if ext != curext:
      if curext != None:
        print(line)
      line = ext + ' '
      curext = ext
    else:
      if ((len(line) + 9) & ~7) + len(fname) > cols:
        print(line)
        line = ''
    line += (' ' * (8-len(line)%8)) + fname 
  print(line)

if __name__ == "__main__":
  path = '.'; doQuotes = False
  if len(sys.argv) > 1:
    if sys.argv[1] == "--help" or sys.argv[1] == "-h":
      print("{} [-h] [--help] [-q] [path] --  directory listing, sorted by type/extension".format(sys.argv[0]))
      print("    version 1.2   patb@pbeirne.com")
      print("    -q    quote filenames that contain a space")
      sys.exit(1)
    if sys.argv[1] == "-q":
      doQuotes = True
      sys.argv.remove(sys.argv[1])
  if len(sys.argv) > 1:
    path = sys.argv[1]
  main(path,doQuotes)

