def generate_filename(filename, ext):
    """Generate a filename with extension
    
    The function tries to accommodate for multiple cases of filename
    ('filename', 'filename.ext', 'file.name.ext') and provide a
    "reasonable" filename back. If an extension already exists,
    it is removed, otherwise it is added. If a file contains
    periods already, the last part (as segmented by periods)
    is considered the extension and therefore removed.
    This would cause unexpected behaviour for filenames which
    contain periods, but no extension (e.g. `file.name` where
    'name' is not an extension)

    Args:
        filename (str): the filename to be worked with
        ext (str): extension to be applied to the string
    
    Returns:
        str: Filename with the applied extension
    """
    trimmed_filename = '.'.join(filename.split('.')[:-1]) or filename
    return '.'.join([trimmed_filename, ext])