def prof_main(main):
    @wraps(main)
    def wrapper(*args, **kwargs):
        import sys
        try:
            do_prof = sys.argv[1] == "prof"
            if do_prof: sys.argv.pop(1)
        except Exception:
            do_prof = False
        if not do_prof:
            sys.exit(main())
        else:
            print("Entering profiling mode...")
            import pstats, cProfile, tempfile
            prof_file = kwargs.get("prof_file", None)
            if prof_file is None:
                _, prof_file = tempfile.mkstemp()
                print("Profiling data stored in %s" % prof_file)
            sortby = kwargs.get("sortby", "time")
            cProfile.runctx("main()", globals(), locals(), prof_file)
            s = pstats.Stats(prof_file)
            s.strip_dirs().sort_stats(sortby).print_stats()
            if "retval" not in kwargs:
                sys.exit(0)
            else:
                return kwargs["retval"]
    return wrapper