def main(argv=None):
    """Tifffile command line usage main function."""
    if argv is None:
        argv = sys.argv

    log.setLevel(logging.INFO)

    import optparse  # TODO: use argparse

    parser = optparse.OptionParser(
        usage='usage: %prog [options] path',
        description='Display image data in TIFF files.',
        version='%%prog %s' % __version__, prog='tifffile')
    opt = parser.add_option
    opt('-p', '--page', dest='page', type='int', default=-1,
        help='display single page')
    opt('-s', '--series', dest='series', type='int', default=-1,
        help='display series of pages of same shape')
    opt('--nomultifile', dest='nomultifile', action='store_true',
        default=False, help='do not read OME series from multiple files')
    opt('--noplots', dest='noplots', type='int', default=10,
        help='maximum number of plots')
    opt('--interpol', dest='interpol', metavar='INTERPOL', default=None,
        help='image interpolation method')
    opt('--dpi', dest='dpi', type='int', default=96,
        help='plot resolution')
    opt('--vmin', dest='vmin', type='int', default=None,
        help='minimum value for colormapping')
    opt('--vmax', dest='vmax', type='int', default=None,
        help='maximum value for colormapping')
    opt('--debug', dest='debug', action='store_true', default=False,
        help='raise exception on failures')
    opt('--doctest', dest='doctest', action='store_true', default=False,
        help='runs the docstring examples')
    opt('-v', '--detail', dest='detail', type='int', default=2)
    opt('-q', '--quiet', dest='quiet', action='store_true')

    settings, path = parser.parse_args()
    path = ' '.join(path)

    if settings.doctest:
        import doctest
        if sys.version_info < (3, 6):
            print('Doctests work with Python >=3.6 only')
            return 0
        doctest.testmod(optionflags=doctest.ELLIPSIS)
        return 0
    if not path:
        path = askopenfilename(title='Select a TIFF file',
                               filetypes=TIFF.FILEOPEN_FILTER)
        if not path:
            parser.error('No file specified')

    if any(i in path for i in '?*'):
        path = glob.glob(path)
        if not path:
            print('No files match the pattern')
            return 0
        # TODO: handle image sequences
        path = path[0]

    if not settings.quiet:
        print_('\nReading TIFF header:', end=' ', flush=True)
    start = time.time()
    try:
        tif = TiffFile(path, multifile=not settings.nomultifile)
    except Exception as exc:
        if settings.debug:
            raise
        print('\n\n%s: %s' % (exc.__class__.__name__, exc))
        sys.exit(0)

    if not settings.quiet:
        print('%.3f ms' % ((time.time()-start) * 1e3))

    if tif.is_ome:
        settings.norgb = True

    images = []
    if settings.noplots > 0:
        if not settings.quiet:
            print_('Reading image data: ', end=' ', flush=True)

        def notnone(x):
            return next(i for i in x if i is not None)

        start = time.time()
        try:
            if settings.page >= 0:
                images = [(tif.asarray(key=settings.page),
                           tif[settings.page], None)]
            elif settings.series >= 0:
                images = [(tif.asarray(series=settings.series),
                           notnone(tif.series[settings.series]._pages),
                           tif.series[settings.series])]
            else:
                for i, s in enumerate(tif.series[:settings.noplots]):
                    try:
                        images.append((tif.asarray(series=i),
                                       notnone(s._pages),
                                       tif.series[i]))
                    except Exception as exc:
                        images.append((None, notnone(s.pages), None))
                        if settings.debug:
                            raise
                        print('\nSeries %i failed with %s: %s... ' %
                              (i, exc.__class__.__name__, exc), end='')
        except Exception as exc:
            if settings.debug:
                raise
            print('%s: %s' % (exc.__class__.__name__, exc))

        if not settings.quiet:
            print('%.3f ms' % ((time.time()-start) * 1e3))

    if not settings.quiet:
        print_('Generating printout:', end=' ', flush=True)
        start = time.time()
        info = TiffFile.__str__(tif, detail=int(settings.detail))
        print('%.3f ms' % ((time.time()-start) * 1e3))
        print()
        print(info)
        print()
    tif.close()

    if images and settings.noplots > 0:
        try:
            import matplotlib
            matplotlib.use('TkAgg')
            from matplotlib import pyplot
        except ImportError as exc:
            log.warning('tifffile.main: %s: %s', exc.__class__.__name__, exc)
        else:
            for img, page, series in images:
                if img is None:
                    continue
                vmin, vmax = settings.vmin, settings.vmax
                if 'GDAL_NODATA' in page.tags:
                    try:
                        vmin = numpy.min(
                            img[img > float(page.tags['GDAL_NODATA'].value)])
                    except ValueError:
                        pass
                if tif.is_stk:
                    try:
                        vmin = tif.stk_metadata['MinScale']
                        vmax = tif.stk_metadata['MaxScale']
                    except KeyError:
                        pass
                    else:
                        if vmax <= vmin:
                            vmin, vmax = settings.vmin, settings.vmax
                if series:
                    title = '%s\n%s\n%s' % (str(tif), str(page), str(series))
                else:
                    title = '%s\n %s' % (str(tif), str(page))
                photometric = 'MINISBLACK'
                if page.photometric not in (3,):
                    photometric = TIFF.PHOTOMETRIC(page.photometric).name
                imshow(img, title=title, vmin=vmin, vmax=vmax,
                       bitspersample=page.bitspersample,
                       photometric=photometric,
                       interpolation=settings.interpol,
                       dpi=settings.dpi)
            pyplot.show()
    return 0