// Called when unable to parse the command line automatically and assumes an old launch
556587
func updatePackageConfig(c *model.CommandConfig, args []string) bool {
	c.Index = model.PACKAGE
	c.Package.ImportPath = args[0]
	if len(args) > 1 {
		c.Package.Mode = args[1]
	}
	return true

}
227578
func main() {
	if reexec.Init() {
		return
	}

	defer func() {
		if r := recover(); r != nil {
			fmt.Fprintf(os.Stderr, "initc: panicked: %s\n", r)
			os.Exit(4)
		}
	}()

	rootFsPath := flag.String("root", "", "Path for the root file system directory")
	configFilePath := flag.String("config", "./etc/config", "Path for the configuration file")
	title := flag.String("title", "", "")
	cflager.AddFlags(flag.CommandLine)
	flag.Parse()

	if *rootFsPath == "" {
		missing("--root")
	}

	syncReader := os.NewFile(uintptr(3), "/dev/a")
	defer syncReader.Close()
	syncWriter := os.NewFile(uintptr(4), "/dev/d")
	defer syncWriter.Close()

	sync := &containerizer.PipeSynchronizer{
		Reader: syncReader,
		Writer: syncWriter,
	}

	if err := sync.Wait(2 * time.Minute); err != nil {
		fail(fmt.Sprintf("initc: wait for host: %s", err), 8)
	}

	env, err := process.EnvFromFile(*configFilePath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "initc: failed to get env from config file: %s\n", err)
		os.Exit(3)
	}

	dropCapabilities := env["root_uid"] != "0"
	procMountFlags := syscall.MS_NOSUID | syscall.MS_NODEV | syscall.MS_NOEXEC
	sysMountFlags := syscall.MS_NOSUID | syscall.MS_NODEV | syscall.MS_NOEXEC | syscall.MS_RDONLY

	if dropCapabilities {
		procMountFlags = procMountFlags | syscall.MS_RDONLY
	}

	initializer := &system.Initializer{
		Steps: []system.StepRunner{
			&containerizer.FuncStep{system.Mount{
				Type:       system.Tmpfs,
				Flags:      syscall.MS_NODEV,
				TargetPath: "/dev/shm",
			}.Mount},
			&containerizer.FuncStep{system.Mount{
				Type:       system.Proc,
				Flags:      procMountFlags,
				TargetPath: "/proc",
			}.Mount},
			&containerizer.FuncStep{system.Mount{
				Type:       system.Sys,
				Flags:      sysMountFlags,
				TargetPath: "/sys",
			}.Mount},
			&containerizer.FuncStep{system.Mount{
				Type:       system.Devpts,
				TargetPath: "/dev/pts",
				Data:       "newinstance,ptmxmode=0666",
			}.Mount},
			&containerizer.FuncStep{system.Unmount{
				Dir: "/tmp/garden-host",
			}.Unmount},
			&containerizer.FuncStep{func() error {
				return setupNetwork(env)
			}},
			&containerizer.CapabilitiesStep{
				Drop:         dropCapabilities,
				Capabilities: &sys.ProcessCapabilities{Pid: os.Getpid()},
			},
		},
	}

	containerizer := containerizer.Containerizer{
		RootfsPath:           *rootFsPath,
		ContainerInitializer: initializer,
		Waiter:               sync,
		Signaller:            sync,
	}

	if err := containerizer.Init(); err != nil {
		fail(fmt.Sprintf("failed to init containerizer: %s", err), 2)
	}

	syscall.RawSyscall(syscall.SYS_FCNTL, uintptr(4), syscall.F_SETFD, 0)
	syscall.RawSyscall(syscall.SYS_FCNTL, uintptr(5), syscall.F_SETFD, 0)

	if err := syscall.Exec("/proc/self/exe", []string{"initd", fmt.Sprintf("-dropCapabilities=%t", dropCapabilities), fmt.Sprintf("-title=\"%s\"", *title)}, os.Environ()); err != nil {
		fail(fmt.Sprintf("failed to reexec: %s", err), 3)
	}
}
1184978
func main() {
	opts := CliOptions{}
	_, err := flags.Parse(&opts)
	if err != nil {
		log.Fatal(err)
	}
	err = config.LoadDotEnvFirst(opts.EnvFile, os.Getenv("ENV_PATH"), "./.env")
	if err != nil {
		log.Fatal(err)
	}
	rcCfg, err := NewRingCentralConfigEnv()
	if err != nil {
		log.Fatal(err)
	}

	fmtutil.PrintJSON(opts)
	fmtutil.PrintJSON(rcCfg)

	apiClient, err := ru.NewApiClientPassword(
		rcCfg.ApplicationCredentials(),
		rcCfg.PasswordCredentials())
	if err != nil {
		log.Fatal(err)
	}

	httpClient := apiClient.HTTPClient()

	if 1 == 0 {
		sendFaxRaw(opts, httpClient)
	}

	if 1 == 1 {
		fmt.Println(opts.Files[0])

		file, err := os.Open(opts.Files[0])
		if err != nil {
			log.Fatal(err)
		}

		params := rc.SendFaxMessageOpts{}
		if len(opts.CoverPageText) > 0 {
			//params.FaxResolution = optional.NewString("High")
			params.CoverPageText = optional.NewString(opts.CoverPageText)
		}
		fmtutil.PrintJSON(opts)
		if 1 == 1 {
			params.Attachment = optional.NewInterface(file)
		}
		info, resp, err := apiClient.MessagesApi.SendFaxMessage(
			context.Background(),
			"~",
			"~",
			opts.To,
			&params)

		if err != nil {
			panic(err)
		} else if resp.StatusCode > 299 {
			panic(fmt.Errorf("API Status %v", resp.StatusCode))
		}
		fmtutil.PrintJSON(info)
	}

	fmt.Println("DONE")
}
880838
func (sd *ServiceDefinition) NormalizeLaunch() {
	testStr := strings.Trim(strings.ToLower(sd.Launch), " ")
	if testStr == "" {
		testStr = commons.AUTO
	}
	sd.Launch = testStr
}
15196
func main() {
	var args []string

	// Detect the current user to figure out what their ~ is.
	usr, err := user.Current()
	fatalOnError(err)

	// Load the list of aliases from the file at dbPath.
	aliases, err := LoadAliases(path.Join(usr.HomeDir, dbPath))
	fatalOnError(err)
	defer aliases.Close()

	// Parse arguments which might get passed to "wol".
	parser := flags.NewParser(&cliFlags, flags.Default & ^flags.HelpFlag)
	args, err = parser.Parse()

	ec := 0
	switch {

	// Parse Error, print usage.
	case err != nil:
		ec = printUsageGetExitCode("", 1)

	// No arguments, or help requested, print usage.
	case len(os.Args) == 1 || cliFlags.Help:
		ec = printUsageGetExitCode("", 0)

	// "--version" requested.
	case cliFlags.Version:
		fmt.Printf("%s\n", wol.Version)

	// Make sure we are being asked to run a something.
	case len(args) == 0:
		ec = printUsageGetExitCode("No command specified, see usage:\n", 1)

	// All other cases go here.
	case true:
		cmd, cmdArgs := strings.ToLower(args[0]), args[1:]
		if fn, ok := cmdMap[cmd]; ok {
			err = fn(cmdArgs, aliases)
		} else {
			err = wakeCmd(args, aliases)
		}
		fatalOnError(err)
	}
	os.Exit(ec)
}
49257
func ParseCommandLine(args []string) (*CommandLine, error) {
	noTarget := NoTarget{}

	cl := CommandLine{
		Target: noTarget,
	}
	i := 0
	for len(args) > 0 {
		// Stop parsing after we have a target, as Python does.
		if cl.Target != noTarget {
			break
		}

		// Consume the next argument.
		arg := args[0]
		args = args[1:]
		i++

		if arg == "-" {
			// "-" instructs Python to load the script from STDIN.
			cl.Target = ScriptTarget{
				Path: "-",
			}
			continue
		}

		isFlag := false
		if !cl.FlagSeparator {
			arg, isFlag = trimPrefix(arg, "-")
		}

		if !isFlag {
			// The first positional argument is the path to the script, and all
			// subsequent arguments are script arguments.
			cl.Target = ScriptTarget{
				Path:             arg,
				FollowsSeparator: cl.FlagSeparator,
			}
			continue
		}

		// Note that at this point we've trimmed the preceding "-" from arg, so
		// this is really "--". If we encounter "--" that marks the end of
		// interpreter flag parsing; everything hereafter is considered positional
		// to the interpreter.
		if arg == "-" {
			cl.FlagSeparator = true
			continue
		}

		// Parse this flag and any remainder.
		fs := parsedFlagState{
			flag: arg,
			args: args,
		}
		for len(fs.flag) > 0 {
			if err := cl.parseSingleFlag(&fs); err != nil {
				return nil, errors.Annotate(err, "failed to parse Python flag #%d", i).
					InternalReason("arg(%q)", arg).Err()
			}
		}
		args = fs.args
	}

	// The remainder of arguments are for the script.
	cl.Args = append([]string(nil), args...)
	return &cl, nil
}
550708
func main() {
	g := generator.New()

	data, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		failWithError(err, "reading input")
	}

	if err := proto.Unmarshal(data, g.Request); err != nil {
		failWithError(err, "parsing input proto")
	}

	if len(g.Request.FileToGenerate) == 0 {
		fail("no files to generate")
	}

	g.CommandLineParameters(g.Request.GetParameter())

	if val, ok := g.Param["logtostderr"]; ok && val == "true" {
		logtostderr = true
	}

	tree := buildTree(g.Request.GetProtoFile())

	packageLocations := make(map[string]string)
	for _, file := range g.Request.GetProtoFile() {
		loc := file.GetName()[:strings.LastIndex(file.GetName(), "/")]
		packageLocations[file.GetPackage()] = loc
	}

	selectedServices := make(map[string]string)
	for k, v := range g.Param {
		switch {
		case k == "logtostderr":
			if v == "true" {
				logtostderr = true
			}
		case strings.HasPrefix(k, "."):
			selectedServices[k] = v
		}
	}

	for serviceKey := range selectedServices {
		service, ok := tree.services[serviceKey]
		if !ok {
			fail("Service", serviceKey, "unknown")
		}

		usedMessages := make(map[string]*message)
		usedEnums := make(map[string]*enum)

		content := new(bytes.Buffer)

		fmt.Fprintf(content, "# %s API Reference\n\n", service.GetName())
		if service.comment != "" {
			fmt.Fprintf(content, "%s\n\n", service.comment)
		}

		if len(service.methods) > 0 {
			fmt.Fprint(content, "## Methods\n\n")

			for _, method := range service.methods {
				fmt.Fprintf(content, "### `%s`\n\n", method.GetName())
				if method.comment != "" {
					fmt.Fprintf(content, "%s\n\n", method.comment)
				}
				if method.inputStream {
					fmt.Fprintf(content, "- Client stream of [`%s`](#%s)\n", method.input.GetName(), heading(method.input.key))
				} else {
					fmt.Fprintf(content, "- Request: [`%s`](#%s)\n", method.input.GetName(), heading(method.input.key))
				}
				useMessage(tree, method.input, usedMessages, usedEnums)
				if method.outputStream {
					fmt.Fprintf(content, "- Server stream of [`%s`](#%s)\n", method.output.GetName(), heading(method.input.key))
				} else {
					fmt.Fprintf(content, "- Response: [`%s`](#%s)\n", method.output.GetName(), heading(method.input.key))
				}
				useMessage(tree, method.output, usedMessages, usedEnums)

				fmt.Fprintln(content)

				if len(method.endpoints) != 0 {
					if len(method.endpoints) == 1 {
						fmt.Fprint(content, "#### HTTP Endpoint\n\n")
					} else {
						fmt.Fprint(content, "#### HTTP Endpoints\n\n")
					}
					for _, endpoint := range method.endpoints {
						fmt.Fprintf(content, "- `%s` `%s`", endpoint.method, endpoint.url)
						var params []string
						for _, match := range regexp.MustCompile(`\{([a-z_]+)\}`).FindAllStringSubmatch(endpoint.url, -1) {
							if match != nil && len(match) == 2 && match[1] != "" {
								params = append(params, fmt.Sprintf("`%s`", match[1]))
							}
						}
						if len(params) > 0 {
							fmt.Fprintf(content, "(%s can be left out of the request body)", strings.Join(params, ", "))
						}
						fmt.Fprintln(content)
					}
					fmt.Fprintln(content)

					fmt.Fprint(content, "#### JSON Request Format\n\n")
					fmt.Fprintf(content, "```json\n%s\n```\n\n", method.input.JSONExample(tree))

					fmt.Fprint(content, "#### JSON Response Format\n\n")
					fmt.Fprintf(content, "```json\n%s\n```\n\n", method.output.JSONExample(tree))
				}
			}
		}

		if len(usedMessages) > 0 {
			fmt.Fprint(content, "## Messages\n\n")

			var messageKeys []string
			for key := range usedMessages {
				messageKeys = append(messageKeys, key)
			}
			sort.Strings(messageKeys)

			for _, messageKey := range messageKeys {
				message := usedMessages[messageKey]
				fmt.Fprintf(content, "### `%s`\n\n", message.key)
				if strings.HasPrefix(messageKey, ".google") {
					fmt.Fprintf(content, "%s\n\n", strings.SplitAfter(message.comment, ".")[0])
				} else if message.comment != "" {
					fmt.Fprintf(content, "%s\n\n", message.comment)
				}
				if len(message.fields) > 0 {
					fmt.Fprintln(content, "| Field Name | Type | Description |")
					fmt.Fprintln(content, "| ---------- | ---- | ----------- |")
					for idx, field := range message.fields {
						if field.isOneOf {
							if idx == 0 || !message.fields[idx-1].isOneOf || message.fields[idx-1].GetOneofIndex() != field.GetOneofIndex() {
								oneof := message.GetOneof(field.GetOneofIndex())
								if len(oneof.fields) > 1 {
									fmt.Fprintf(content, "| **%s** | **oneof %d** | one of the following %d |\n", oneof.GetName(), len(oneof.fields), len(oneof.fields))
								}
							}
						} else {
							if idx > 0 && message.fields[idx-1].isOneOf {
								oneof := message.GetOneof(message.fields[idx-1].GetOneofIndex())
								if len(oneof.fields) > 1 {
									fmt.Fprintf(content, "| **%s** | **end oneof %d** |  |\n", oneof.GetName(), len(oneof.fields))
								}
							}
						}

						var fieldType string
						if field.repeated {
							fieldType += "_repeated_ "
						}
						typ := strings.ToLower(strings.TrimPrefix(field.GetType().String(), "TYPE_"))
						switch typ {
						case "message":
							friendlyType := field.GetTypeName()[strings.LastIndex(field.GetTypeName(), ".")+1:]
							fieldType += fmt.Sprintf("[`%s`](#%s)", friendlyType, heading(field.GetTypeName()))
						case "enum":
							// TODO(htdvisser): test this
							if enum, ok := tree.enums[field.GetTypeName()]; ok {
								usedEnums[field.GetTypeName()] = enum
							}
							friendlyType := field.GetTypeName()[strings.LastIndex(field.GetTypeName(), ".")+1:]
							fieldType += fmt.Sprintf("[`%s`](#%s)", friendlyType, heading(field.GetTypeName()))
						default:
							fieldType += fmt.Sprintf("`%s`", typ)
						}
						fmt.Fprintf(content, "| `%s` | %s | %s |\n", field.GetName(), fieldType, strings.Replace(field.comment, "\n", " ", -1))
					}
					fmt.Fprintln(content)
				}
			}
		}

		if len(usedEnums) > 0 {
			fmt.Fprint(content, "## Used Enums\n\n")

			var enumKeys []string
			for key := range usedEnums {
				enumKeys = append(enumKeys, key)
			}
			sort.Strings(enumKeys)

			for _, enumKey := range enumKeys {
				enum := usedEnums[enumKey]

				fmt.Fprintf(content, "### `%s`\n\n", enum.key)
				if enum.comment != "" {
					fmt.Fprintf(content, "%s\n\n", enum.comment)
				}

				if len(enum.values) > 0 {
					fmt.Fprintln(content, "| Value | Description |")
					fmt.Fprintln(content, "| ----- | ----------- |")
					for _, value := range enum.values {
						fmt.Fprintf(content, "| `%s` | %s |\n", value.GetName(), strings.Replace(value.comment, "\n", " ", -1))
					}
					fmt.Fprintln(content)
				}
			}
		}

		packageService := strings.TrimPrefix(service.key, ".")
		packageName := packageService[:strings.Index(packageService, ".")]
		location, ok := packageLocations[packageName]
		if !ok {
			fail("Could not find location of package", packageName)
		}
		fileName := path.Join(location, service.GetName()+".md")
		contentString := content.String()
		g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
			Name:    &fileName,
			Content: &contentString,
		})
	}

	// Send back the results.
	data, err = proto.Marshal(g.Response)
	if err != nil {
		failWithError(err, "failed to marshal output proto")
	}
	_, err = os.Stdout.Write(data)
	if err != nil {
		failWithError(err, "failed to write output proto")
	}
}
332526
func Start(cmds map[string]*Command) error {
	// cfsslFlagSet is the flag sets for cfssl.
	var cfsslFlagSet = flag.NewFlagSet("cfssl", flag.ExitOnError)
	var c Config

	registerFlags(&c, cfsslFlagSet)
	// Initial parse of command line arguments. By convention, only -h/-help is supported.
	if flag.Usage == nil {
		flag.Usage = func() {
			fmt.Fprintf(os.Stderr, usage)
			for name := range cmds {
				fmt.Fprintf(os.Stderr, "\t%s\n", name)
			}
			fmt.Fprintf(os.Stderr, "Top-level flags:\n")
			flag.PrintDefaults()
		}
	}

	flag.Parse()

	if flag.NArg() < 1 {
		fmt.Fprintf(os.Stderr, "No command is given.\n")
		flag.Usage()
		return errors.New("no command was given")
	}

	// Clip out the command name and args for the command
	cmdName = flag.Arg(0)
	args := flag.Args()[1:]
	cmd, found := cmds[cmdName]
	if !found {
		fmt.Fprintf(os.Stderr, "Command %s is not defined.\n", cmdName)
		flag.Usage()
		return errors.New("undefined command")
	}
	// always have flag 'loglevel' for each command
	cmd.Flags = append(cmd.Flags, "loglevel")
	// The usage of each individual command is re-written to mention
	// flags defined and referenced only in that command.
	cfsslFlagSet.Usage = func() {
		fmt.Fprintf(os.Stderr, "\t%s", cmd.UsageText)
		for _, name := range cmd.Flags {
			if f := cfsslFlagSet.Lookup(name); f != nil {
				printDefaultValue(f)
			}
		}
	}

	// Parse all flags and take the rest as argument lists for the command
	cfsslFlagSet.Parse(args)
	args = cfsslFlagSet.Args()

	var err error
	if c.ConfigFile != "" {
		c.CFG, err = config.LoadFile(c.ConfigFile)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to load config file: %v", err)
			return errors.New("failed to load config file")
		}
	}

	if err := cmd.Main(args, c); err != nil {
		fmt.Fprintln(os.Stderr, err)
		return err
	}

	return nil
}
696654
func Main(params Parameters, args []string) int {
	return subcommands.Run(GetApplication(params), fixflagpos.FixSubcommands(args))
}
430494
func main() {
	// Add command names to cfssl usage
	flag.Usage = nil // this is set to nil for testabilty
	// Register commands.
	cmds := map[string]*cli.Command{
		"bundle":         bundle.Command,
		"certinfo":       certinfo.Command,
		"crl":            crl.Command,
		"sign":           sign.Command,
		"serve":          serve.Command,
		"version":        version.Command,
		"genkey":         genkey.Command,
		"gencert":        gencert.Command,
		"gencsr":         gencsr.Command,
		"gencrl":         gencrl.Command,
		"ocspdump":       ocspdump.Command,
		"ocsprefresh":    ocsprefresh.Command,
		"ocspsign":       ocspsign.Command,
		"ocspserve":      ocspserve.Command,
		"selfsign":       selfsign.Command,
		"scan":           scan.Command,
		"info":           info.Command,
		"print-defaults": printdefaults.Command,
		"revoke":         revoke.Command,
	}

	// If the CLI returns an error, exit with an appropriate status
	// code.
	err := cli.Start(cmds)
	if err != nil {
		os.Exit(1)
	}
}
1138748
func (c *CmdSimpleFSRecover) ParseArgv(ctx *cli.Context) error {
	if len(ctx.Args()) < 1 {
		return errors.New("recover requires at least one KBFS path argument")
	}

	// TODO: "rev" should be a real int64, need to update the
	// `cli` library for that.
	rev := int64(ctx.Int("rev"))
	timeString := ctx.String("time")
	relTimeString := getRelTime(ctx)
	if rev == 0 && timeString == "" && relTimeString == "" {
		return errors.New(
			"must specify exactly one of -rev, -time, or -reltime")
	}

	for _, src := range ctx.Args() {
		p, err := makeSimpleFSPathWithArchiveParams(
			src, rev, timeString, relTimeString)
		if err != nil {
			return err
		}
		c.src = append(c.src, p)
	}
	return nil
}
709161
func manuallyProcessArgs(args []string) ([]string, []string) {
	known := []string{}
	unknown := []string{}
	kvargs := []string{"--host", "--kube-context", "--home", "--tiller-namespace"}
	knownArg := func(a string) bool {
		for _, pre := range kvargs {
			if strings.HasPrefix(a, pre+"=") {
				return true
			}
		}
		return false
	}
	for i := 0; i < len(args); i++ {
		switch a := args[i]; a {
		case "--debug":
			known = append(known, a)
		case "--host", "--kube-context", "--home", "--tiller-namespace":
			known = append(known, a, args[i+1])
			i++
		default:
			if knownArg(a) {
				known = append(known, a)
				continue
			}
			unknown = append(unknown, a)
		}
	}
	return known, unknown
}
753008
func (e Entrypoint) Cmd(args ...string) *exec.Cmd {
	// append the Entrypoint as argv[0]
	args = append([]string{string(e)}, args...)
	return &exec.Cmd{
		Path: exePath,
		Args: args,
		SysProcAttr: &syscall.SysProcAttr{
			Pdeathsig: syscall.SIGTERM,
		},
	}
}
525604
func (c *CmdSimpleFSMkdir) ParseArgv(ctx *cli.Context) error {
	nargs := len(ctx.Args())
	var err error

	if nargs != 1 {
		return errors.New("mkdir requires a KBFS path argument")
	}

	p, err := makeSimpleFSPath(ctx.Args()[0])
	if err != nil {
		return err
	}

	c.path = p
	return nil
}
648807
func main() {
	os.Args = []string{os.Args[0], "-v", "install"}
	os.Exit(mage.Main())
}
1247588
func main() {
	CheckArgs("<path>")
	path := os.Args[1]

	// We instanciate a new repository targeting the given path (the .git folder)
	r, err := git.PlainOpen(path)
	CheckIfError(err)

	// Length of the HEAD history
	Info("git rev-list HEAD --count")

	// ... retrieving the HEAD reference
	ref, err := r.Head()
	CheckIfError(err)

	// ... retrieves the commit history
	cIter, err := r.Log(&git.LogOptions{From: ref.Hash()})
	CheckIfError(err)

	// ... just iterates over the commits
	var cCount int
	err = cIter.ForEach(func(c *object.Commit) error {
		cCount++

		return nil
	})
	CheckIfError(err)

	fmt.Println(cCount)
}
527228
func main() {
	// Parse arguments
	kingpin.Parse()

	if *spindleCW != 0 && *spindleCCW != 0 {
		fmt.Fprintf(os.Stderr, "Error: Cannot force both clockwise and counter clockwise rotation\n")
		os.Exit(1)
	}

	fhandle, err := ioutil.ReadFile(*inputFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: Could not open file: %s\n", err)
		os.Exit(2)
	}

	// Parse
	code := string(fhandle)
	document, err := gcode.Parse(code)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Parse error: %s\n", err)
		os.Exit(3)
	}

	// Run through the VM
	machine.Init()
	machine.IgnoreBlockDelete = *ignBlockDel
	machine.AllowRemainingWords = *allowRemainingWords
	machine.MaxArcDeviation = *maxArcDeviation
	machine.MinArcLineLength = *minArcLineLength

	if err := machine.Process(document); err != nil {
		fmt.Fprintf(os.Stderr, "VM failed: %s\n", err)
		os.Exit(3)
	}

	// Optimize as requested
	if *opt {
		if *optDrillSpeed {
			optimize.OptDrillSpeed(&machine, *drillfeed, *rapiddrill)
		}

		if *optFloatingZ {
			optimize.OptFloatingZ(&machine, *floatingzheight)
		}

		if *optPathGrouping {
			if err := optimize.OptPathGrouping(&machine, *rtolerance); err != nil {
				fmt.Fprintf(os.Stderr, "Warning: Could not execute path grouping: %s\n", err)
			}
		}

		if *optBogusMove {
			optimize.OptBogusMoves(&machine)
		}

		if *optVector {
			optimize.OptVector(&machine, *vtolerance)
		}

		if *optLiftSpeed {
			optimize.OptLiftSpeed(&machine)
		}

		if *optPrepareTool {
			optimize.OptPrepareTool(&machine)
		}
	}

	// Apply requested modifications
	if *flipXY {
		machine.FlipXY()
	}

	if *safetyHeight > 0 {
		if err := machine.SetSafetyHeight(*safetyHeight); err != nil {
			fmt.Fprintf(os.Stderr, "Warning: Could not set safety height%s\n", err)
		}
	}

	if *feedLimit > 0 {
		machine.LimitFeedrate(*feedLimit)
	}

	if *multiplyFeed != 0 {
		machine.FeedrateMultiplier(*multiplyFeed)
	}

	if *multiplyMove != 0 {
		machine.MoveMultiplier(*multiplyMove)
	}

	if *enforceReturn {
		machine.Return(true, true)
	}

	if *spindleCW > 0 {
		machine.EnforceSpindle(true, true, *spindleCW)
	} else if *spindleCCW > 0 {
		machine.EnforceSpindle(true, false, *spindleCCW)
	}

	if *stats {
		printStats(&machine)
	}

	// Handle VM output
	if *debugDump {
		machine.Dump()
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: Could not export vm state: %s\n", err)
		os.Exit(3)
	}

	if *dumpStdout {
		g := export.StringCodeGenerator{Precision: *precision}
		g.Init()
		export.HandleAllPositions(&machine, &g)
		fmt.Printf(g.Retrieve())
	}

	if *outputFile != "" {
		g := export.StringCodeGenerator{Precision: *precision}
		g.Init()
		export.HandleAllPositions(&machine, &g)

		if err := ioutil.WriteFile(*outputFile, []byte(g.Retrieve()), 0644); err != nil {
			fmt.Fprintf(os.Stderr, "Error: Could not write to file: %s\n", err)
			os.Exit(2)
		}
	}

	if *device != "" {
		mt := &ManualGenerator{}
		wt := &WaitGenerator{}
		s := &streaming.GrblStreamer{}
		s.Precision = *precision

		generators = append(generators, mt)
		generators = append(generators, wt)
		generators = append(generators, s)

		s.Init()
		mt.Init()

		if err := s.Check(&machine); err != nil {
			fmt.Fprintf(os.Stderr, "Error: Incompatibility: %s\n", err)
		}

		if !*autoStart {
			reader := bufio.NewReader(os.Stdin)
			fmt.Fprintf(os.Stderr, "Run code? (y/n) ")
			text, _ := reader.ReadString('\n')
			if text != "y\n" {
				fmt.Fprintf(os.Stderr, "Aborting\n")
				os.Exit(5)
			}
		}

		if err := s.Connect(*device, *baudrate); err != nil {
			fmt.Fprintf(os.Stderr, "Error: Unable to connect to device: %s\n", err)
			os.Exit(2)
		}

		pBar := pb.New(len(machine.Positions))
		pBar.ManualUpdate = true
		pBar.Format("[=> ]")
		pBar.Start()

		sigchan := make(chan string, 1)
		registerSignals(sigchan)

		go func() {
			for sig := range sigchan {
				switch sig {
				case "interrupt":
					fmt.Fprintf(os.Stderr, "\nStopping...\n")
					s.Stop()
					os.Exit(5)
				case "stop":
					s.Pause()
					fmt.Fprintf(os.Stderr, "\nPaused. Press <ENTER> to continue")
					reader := bufio.NewReader(os.Stdin)
					_, _ = reader.ReadString('\n')
					s.Start()
					pBar.Update()
				}
			}
		}()

		for idx := range machine.Positions {
			if err := export.HandlePositionAtIndex(&machine, idx, generators...); err != nil {
				s.Stop()
				panic(err)
			}
			pBar.Increment()
			pBar.Update()
		}
		pBar.Finish()
		pBar.Update()
	}

}