def determine_filetype(filename):
    """
    Return the filetype of a given file by examining the first few bytes.
    
    Adapted from pyart.io.auto_read.py script by : https://arm-doe.github.io/pyart/ 

    The following filetypes are detected:

    * 'csv'
    * 'txt'
    * 'excel'
    * 'NETCDF3'
    * 'NETCDF4'
    * 'HDF4'
    * 'gzip'

    Parameters
    ----------
    filename : str
        Name of file to examine.

    Returns
    -------
    filetype : str
        Type of file.
        
    """
    
    # read the first 12 bytes from the file
    try:
        f = open(filename, 'rb')
        begin = f.read(12)
        f.close()
    except TypeError:
        f = filename
        begin = f.read(12)
        f.seek(-12, 1)
        
    # CSV - no file signature as far as I know
    csv_signature = "csv"
    if filename[-3:] == csv_signature:
        return "CSV"
    
    # txt
    txt_signature = "txt"
    if filename[-3:] == txt_signature:
        return "TXT"
    
    # txt
    txt_signature = "TXT"
    if filename[-3:] == txt_signature:
        return "TXT"
        
    # xlsx
    xlsx_signature = b'PK\x03\x04\x14\x00\x08\x08\x08\x00ss'
    if begin == xlsx_signature:
        return "XLSX"
        
    # NetCDF3, read with read_cfradial
    if begin[:3] == b"CDF":
        return "NETCDF3"

    # NetCDF4, read with read_cfradial, contained in a HDF5 container
    # HDF5 format signature from HDF5 specification documentation
    hdf5_signature = b'\x89\x48\x44\x46\x0d\x0a\x1a\x0a'
    if begin[:8] == hdf5_signature:
        return "NETCDF4"
    
    # HDF4 file
    # HDF4 format signature from HDF4 specification documentation
    hdf4_signature = b'\x0e\x03\x13\x01'
    if begin[:4] == hdf4_signature:
        return "HDF4"
    
    # gzip filetype
    gzip_signature = b'\x1f\x8b'
    if begin[:2] == gzip_signature:
        return 'GZ'
    
    # zip filetype
    zip_signature = b'PK\x03\x04\x14\x00\x08\x00\x08\x00\x84y'
    if begin == zip_signature:
        return 'ZIP'
    
    # Cannot determine filetype
    return "UNKNOWN"