def main(argv=None):
    '''Command line options.'''

    program_name = os.path.basename(sys.argv[0])
    program_version = version
    program_build_date = "%s" % __updated__

    program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
    #program_usage = '''usage: spam two eggs''' # optional - will be autogenerated by optparse
    program_longdesc = '''''' # optional - give further explanation about what the program does
    program_license = "Copyright 2015-2018 Mohamed El Amine SEHILI                                            \
                Licensed under the General Public License (GPL) Version 3 \nhttp://www.gnu.org/licenses/"

    if argv is None:
        argv = sys.argv[1:]
    try:
        # setup option parser
        parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
        
        group = OptionGroup(parser, "[Input-Output options]")
        group.add_option("-i", "--input", dest="input", help="Input audio or video file. Use - for stdin [default: read from microphone using pyaudio]", metavar="FILE")
        group.add_option("-t", "--input-type", dest="input_type", help="Input audio file type. Mandatory if file name has no extension [default: %default]", type=str, default=None, metavar="String")
        group.add_option("-M", "--max_time", dest="max_time", help="Max data (in seconds) to read from microphone/file [default: read until the end of file/stream]", type=float, default=None, metavar="FLOAT")
        group.add_option("-O", "--output-main", dest="output_main", help="Save main stream as. If omitted main stream will not be saved [default: omitted]", type=str, default=None, metavar="FILE")
        group.add_option("-o", "--output-tokens", dest="output_tokens", help="Output file name format for detections. Use {N} and {start} and {end} to build file names, example: 'Det_{N}_{start}-{end}.wav'", type=str, default=None, metavar="STRING")
        group.add_option("-T", "--output-type", dest="output_type", help="Audio type used to save detections and/or main stream. If not supplied will: (1). guess from extension or (2). use wav format", type=str, default=None, metavar="STRING")
        group.add_option("-u", "--use-channel", dest="use_channel", help="Choose channel to use from a multi-channel audio file (requires pydub). 'left', 'right' and 'mix' are accepted values. [Default: 1 (i.e. 1st or left channel)]", type=str, default="1", metavar="STRING")
        parser.add_option_group(group)
        
        
        group = OptionGroup(parser, "[Tokenization options]", "Set tokenizer options and energy threshold.")
        group.add_option("-a", "--analysis-window", dest="analysis_window", help="Size of analysis window in seconds [default: %default (10ms)]", type=float, default=0.01, metavar="FLOAT")
        group.add_option("-n", "--min-duration", dest="min_duration", help="Min duration of a valid audio event in seconds [default: %default]", type=float, default=0.2, metavar="FLOAT")
        group.add_option("-m", "--max-duration", dest="max_duration", help="Max duration of a valid audio event in seconds [default: %default]", type=float, default=5, metavar="FLOAT")
        group.add_option("-s", "--max-silence", dest="max_silence", help="Max duration of a consecutive silence within a valid audio event in seconds [default: %default]", type=float, default=0.3, metavar="FLOAT")
        group.add_option("-d", "--drop-trailing-silence", dest="drop_trailing_silence", help="Drop trailing silence from a detection [default: keep trailing silence]",  action="store_true", default=False)
        group.add_option("-e", "--energy-threshold", dest="energy_threshold", help="Log energy threshold for detection [default: %default]", type=float, default=50, metavar="FLOAT")
        parser.add_option_group(group)
        
        
        group = OptionGroup(parser, "[Audio parameters]", "Define audio parameters if data is read from a headerless file (raw or stdin) or you want to use different microphone parameters.")        
        group.add_option("-r", "--rate", dest="sampling_rate", help="Sampling rate of audio data [default: %default]", type=int, default=16000, metavar="INT")
        group.add_option("-c", "--channels", dest="channels", help="Number of channels of audio data [default: %default]", type=int, default=1, metavar="INT")
        group.add_option("-w", "--width", dest="sample_width", help="Number of bytes per audio sample [default: %default]", type=int, default=2, metavar="INT")
        group.add_option("-I", "--input-device-index", dest="input_device_index", help="Audio device index [default: %default] - only when using PyAudio", type=int, default=None, metavar="INT")
        group.add_option("-F", "--audio-frame-per-buffer", dest="frame_per_buffer", help="Audio frame per buffer [default: %default] - only when using PyAudio", type=int, default=1024, metavar="INT")
        parser.add_option_group(group)
        
        group = OptionGroup(parser, "[Do something with detections]", "Use these options to print, play or plot detections.") 
        group.add_option("-C", "--command", dest="command", help="Command to call when an audio detection occurs. Use $ to represent the file name to use with the command (e.g. -C 'du -h $')", default=None, type=str, metavar="STRING")
        group.add_option("-E", "--echo", dest="echo", help="Play back each detection immediately using pyaudio [default: do not play]",  action="store_true", default=False)
        group.add_option("-p", "--plot", dest="plot", help="Plot and show audio signal and detections (requires matplotlib)",  action="store_true", default=False)
        group.add_option("", "--save-image", dest="save_image", help="Save plotted audio signal and detections as a picture or a PDF file (requires matplotlib)",  type=str, default=None, metavar="FILE")
        group.add_option("", "--printf", dest="printf", help="print detections, one per line, using a user supplied format (e.g. '[{id}]: {start} -- {end}'). Available keywords {id}, {start}, {end} and {duration}",  type=str, default="{id} {start} {end}", metavar="STRING")
        group.add_option("", "--time-format", dest="time_format", help="format used to print {start} and {end}. [Default= %default]. %S: absolute time in sec. %I: absolute time in ms. If at least one of (%h, %m, %s, %i) is used, convert time into hours, minutes, seconds and millis (e.g. %h:%m:%s.%i). Only required fields are printed",  type=str, default="%S", metavar="STRING")
        parser.add_option_group(group)
        
        parser.add_option("-q", "--quiet", dest="quiet", help="Do not print any information about detections [default: print 'id', 'start' and 'end' of each detection]",  action="store_true", default=False)
        parser.add_option("-D", "--debug", dest="debug", help="Print processing operations to STDOUT",  action="store_true", default=False)
        parser.add_option("", "--debug-file", dest="debug_file", help="Print processing operations to FILE",  type=str, default=None, metavar="FILE")
        
        

        # process options
        (opts, args) = parser.parse_args(argv)
        
        if opts.input == "-":
            asource = StdinAudioSource(sampling_rate = opts.sampling_rate,
                                       sample_width = opts.sample_width,
                                       channels = opts.channels)
        #read data from a file
        elif opts.input is not None:
            asource = file_to_audio_source(filename=opts.input, filetype=opts.input_type, uc=opts.use_channel)
        
        # read data from microphone via pyaudio
        else:
            try:
                asource = PyAudioSource(sampling_rate = opts.sampling_rate,
                                        sample_width = opts.sample_width,
                                        channels = opts.channels,
                                        frames_per_buffer = opts.frame_per_buffer,
                                        input_device_index = opts.input_device_index)
            except Exception:
                sys.stderr.write("Cannot read data from audio device!\n")
                sys.stderr.write("You should either install pyaudio or read data from STDIN\n")
                sys.exit(2)
               
        logger = logging.getLogger(LOGGER_NAME)
        logger.setLevel(logging.DEBUG)
        
        handler = logging.StreamHandler(sys.stdout)
        if opts.quiet or not opts.debug:
            # only critical messages will be printed
            handler.setLevel(logging.CRITICAL)
        else:
            handler.setLevel(logging.DEBUG)
        
        logger.addHandler(handler)
        
        if opts.debug_file is not None:
            logger.setLevel(logging.DEBUG)
            opts.debug = True
            handler = logging.FileHandler(opts.debug_file, "w")
            fmt = logging.Formatter('[%(asctime)s] | %(message)s')
            handler.setFormatter(fmt)
            handler.setLevel(logging.DEBUG)
            logger.addHandler(handler)
        
        record = opts.output_main is not None or opts.plot or opts.save_image is not None
                        
        ads = ADSFactory.ads(audio_source = asource, block_dur = opts.analysis_window, max_time = opts.max_time, record = record)
        validator = AudioEnergyValidator(sample_width=asource.get_sample_width(), energy_threshold=opts.energy_threshold)
        
        
        if opts.drop_trailing_silence:
            mode = StreamTokenizer.DROP_TRAILING_SILENCE
        else:
            mode = 0
        
        analysis_window_per_second = 1. / opts.analysis_window
        tokenizer = StreamTokenizer(validator=validator, min_length=opts.min_duration * analysis_window_per_second,
                                    max_length=int(opts.max_duration * analysis_window_per_second),
                                    max_continuous_silence=opts.max_silence * analysis_window_per_second,
                                    mode = mode)
        
        
        observers = []
        tokenizer_worker = None
        
        if opts.output_tokens is not None:
            
            try:
                # check user format is correct
                fname  = opts.output_tokens.format(N=0, start=0, end=0)
                
                # find file type for detections
                tok_type =  opts.output_type
                if tok_type is None:
                    tok_type = os.path.splitext(opts.output_tokens)[1][1:]
                if tok_type == "": 
                    tok_type = "wav"
                
                token_saver = TokenSaverWorker(name_format=opts.output_tokens, filetype=tok_type,
                                               debug=opts.debug, logger=logger, sr=asource.get_sampling_rate(),
                                               sw=asource.get_sample_width(),
                                               ch=asource.get_channels())
                observers.append(token_saver)
            
            except Exception:
                sys.stderr.write("Wrong format for detections file name: '{0}'\n".format(opts.output_tokens))
                sys.exit(2)
            
        if opts.echo:
            try:
                player = player_for(asource)
                player_worker = PlayerWorker(player=player, debug=opts.debug, logger=logger)
                observers.append(player_worker)
            except Exception:
                sys.stderr.write("Cannot get an audio player!\n")
                sys.stderr.write("You should either install pyaudio or supply a command (-C option) to play audio\n")
                sys.exit(2)
                
        if opts.command is not None and len(opts.command) > 0:
            cmd_worker = CommandLineWorker(command=opts.command, debug=opts.debug, logger=logger)
            observers.append(cmd_worker)
        
        if not opts.quiet or opts.plot is not None or opts.save_image is not None:    
            oformat = opts.printf.replace("\\n", "\n").replace("\\t", "\t").replace("\\r", "\r")
            converter = seconds_to_str_fromatter(opts.time_format)
            log_worker = LogWorker(print_detections = not opts.quiet, output_format=oformat,
                                   time_formatter=converter, logger=logger, debug=opts.debug)
            observers.append(log_worker)
        
        tokenizer_worker = TokenizerWorker(ads, tokenizer, opts.analysis_window, observers)
        
        def _save_main_stream():
            # find file type
            main_type =  opts.output_type
            if main_type is None:
                main_type = os.path.splitext(opts.output_main)[1][1:]
            if main_type == "": 
                main_type = "wav"
            ads.close()
            ads.rewind()
            data = ads.get_audio_source().get_data_buffer()
            if len(data) > 0:
                save_audio_data(data=data, filename=opts.output_main, filetype=main_type, sr=asource.get_sampling_rate(),
                                sw = asource.get_sample_width(),
                                ch = asource.get_channels())
        
        def _plot():
            import numpy as np
            ads.close()
            ads.rewind()
            data = ads.get_audio_source().get_data_buffer()
            signal = AudioEnergyValidator._convert(data, asource.get_sample_width())
            detections = [(det[3] , det[4]) for det in log_worker.detections]
            max_amplitude = 2**(asource.get_sample_width() * 8 - 1) - 1
            energy_as_amp = np.sqrt(np.exp(opts.energy_threshold * np.log(10) / 10)) / max_amplitude
            plot_all(signal / max_amplitude, asource.get_sampling_rate(), energy_as_amp, detections, show = opts.plot, save_as = opts.save_image)
        
        
        # start observer threads
        for obs in observers:
            obs.start()
        # start tokenization thread
        tokenizer_worker.start()
        
        while True:
            time.sleep(1)
            if len(threading.enumerate()) == 1:
                break
            
        tokenizer_worker = None
            
        if opts.output_main is not None:
            _save_main_stream()
        if opts.plot or opts.save_image is not None:
            _plot()
            
        return 0
            
    except KeyboardInterrupt:
        
        if tokenizer_worker is not None:
            tokenizer_worker.stop()
        for obs in observers:
            obs.stop()
            
        if opts.output_main is not None:
            _save_main_stream()
        if opts.plot or opts.save_image is not None:
            _plot()
        
        return 0

    except Exception as e:
        sys.stderr.write(program_name + ": " + str(e) + "\n")
        sys.stderr.write("for help use -h\n")
        
        return 2
Command line options.