import gzip


def yopen(gzipped, *args):
    """ Passes args on to the appropriate opener, gzip or regular.

        A dooplicity.tools.xopen that uses the gzip module, which is
        unsafe for writing. See xopen's docstring in dooplicity.tools for
        more information.

        gzipped: True iff gzip.open() should be used to open rather than
            open(); False iff open() should be used; None if input should be
            read and guessed
        *args: unnamed arguments to pass

        Return value: file object
    """
    if gzipped is None:
        with open(args[0], 'rb') as binary_input_stream:
            # Check for magic number
            if binary_input_stream.read(2) == '\x1f\x8b':
                gzipped = True
            else:
                gzipped = False
    if gzipped:
        return gzip.open(*args)
    return open(*args)