// Throw away any references/handles to the output file. This probably
// means the admin wants to rotate the file out and have this process
// open a new one. Close the underlying io.Writer if that is a thing
// that it knows how to do.
482613
func (fo *FileWriterOutput) OnHup() {
	if fo.WriterOutput != nil {
		wc, ok := fo.WriterOutput.w.(io.Closer)
		if ok {
			err := wc.Close()
			if err != nil {
				fo.fallbackLog("Closing %#v failed: %s", fo.path, err)
			}
		}
		fo.WriterOutput = nil
	}
}
1104648
func (w *writeWorkerState) Cleanup() {
	w.bufferPool.Return(w.writeBuf)
	w.writeBuf = nil
	w.buf = nil
}
608203
func (fo *FileWriterOutput) Output(ll LogLevel, message []byte) {
	if fo.WriterOutput == nil {
		fh, err := fo.openFile()
		if err != nil {
			fo.fallbackLog("Could not open %#v: %s", fo.path, err)
			return
		}
		fo.WriterOutput = NewWriterOutput(fh)
	}
	fo.WriterOutput.Output(ll, message)
}
1331048
func (g *Generator) Cleanup() {
	for _, f := range g.genfiles {
		os.Remove(f)
	}
	g.genfiles = nil
}
917752
func NewFileWriterOutput(path string) (*FileWriterOutput, error) {
	fo := &FileWriterOutput{path: path}
	fh, err := fo.openFile()
	if err != nil {
		return nil, err
	}
	fo.WriterOutput = NewWriterOutput(fh)
	return fo, nil
}
588182
func (l *LogFile) Rotate() error {
	// rename dest file if it already exists.
	if _, err := os.Stat(l.name); err == nil {
		name := l.name + "." + time.Now().Format(time.RFC3339)
		if err = os.Rename(l.name, name); err != nil {
			return err
		}
	}
	// create new file.
	file, err := os.Create(l.name)
	if err != nil {
		return err
	}
	// switch dest file safely.
	l.mu.Lock()
	file, l.file = l.file, file
	l.mu.Unlock()
	// close old file if open.
	if file != nil {
		if err := file.Close(); err != nil {
			return err
		}
	}
	return nil
}
317539
func (file *File) Abort() (err error) {
	if file.closed {
		err = errors.New("abort on closed file")
		return
	}
	if file.aborted {
		err = errors.New("abort on aborted file")
		return
	}

	file.tmpfile.Close()
	err = os.Remove(file.tmpfile.Name())
	file.aborted = true
	return
}
149753
func (rd *RAMDirectory) CreateOutput(name string, context IOContext) (out IndexOutput, err error) {
	rd.EnsureOpen()
	file := rd.newRAMFile()
	rd.fileMapLock.Lock()
	defer rd.fileMapLock.Unlock()
	if existing, ok := rd.fileMap[name]; ok {
		atomic.AddInt64(&rd.sizeInBytes, -existing.sizeInBytes)
		existing.directory = nil
	}
	rd.fileMap[name] = file
	return NewRAMOutputStream(file, true), nil
}
566665
func cleanup(files ...*os.File) {
	for _, file := range files {
		_ = file.Close()
		_ = os.Remove(file.Name())
	}
}
102955
func (fs *FileSorter) Output() ([]types.Datum, []types.Datum, int64, error) {
	if fs.closed {
		return nil, nil, 0, errors.New("FileSorter has been closed")
	}
	if len(fs.files) == 0 {
		// No external files generated.
		// Perform full in-memory sort directly.
		r, err := fs.internalSort()
		if err != nil {
			return nil, nil, 0, errors.Trace(err)
		} else if r != nil {
			return r.key, r.val, r.handle, nil
		} else {
			return nil, nil, 0, nil
		}
	}
	r, err := fs.externalSort()
	if err != nil {
		return nil, nil, 0, errors.Trace(err)
	} else if r != nil {
		return r.key, r.val, r.handle, nil
	} else {
		return nil, nil, 0, nil
	}
}
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()
	}

}
440372
func (bw *BufferedFileWriter) Close() error {
	bw.quitChan <- true
	bw.mu.Lock()
	bw.done = true
	bw.bufWriter.Flush()
	bw.origWriter.f.Close()
	bw.mu.Unlock()
	return nil
}
154482
func (o *copier) Cleanup() {
	for _, path := range o.tmpPaths {
		os.RemoveAll(path)
	}
	o.tmpPaths = []string{}
	if o.activeLayer != nil {
		o.activeLayer.Release()
		o.activeLayer = nil
	}
}
957525
func (writer *baseFileWriter) Close() {
	writer.lock.Lock()
	defer writer.lock.Unlock()

	if writer.closed {
		return
	}

	writer.closed = true
	writer.blog.flush()
	writer.blog.Close()
	writer.blog = nil
	writer.file.Close()
	close(writer.logSizeChan)
	close(writer.timeRotateSig)
	close(writer.sizeRotateSig)
}
368354
func (fSource *fileSource) Cleanup() error {

	fSource.filelock.Lock()
	defer fSource.filelock.Unlock()

	if fileConfigSource == nil || fSource == nil {
		return nil
	}

	if fSource.watchPool != nil && fSource.watchPool.watcher != nil {
		fSource.watchPool.watcher.Close()
	}

	if fSource.watchPool != nil {
		fSource.watchPool.fileSource = nil
		fSource.watchPool.callback = nil
		fSource.watchPool = nil
	}
	fSource.Configurations = nil
	fSource.files = make([]file, 0)
	return nil
}
850903
func (b *Writer) dump() {
	pos := 0
	for i, line := range b.lines {
		print("(", i, ") ")
		for _, c := range line {
			print("[", string(b.buf.Bytes()[pos:pos+c.size]), "]")
			pos += c.size
		}
		print("\n")
	}
	print("\n")
}
1125406
func (file *File) Close() error {
	// Should we cancel all pending requests for the File
	return file.Fid.Clnt.Clunk(file.Fid)
}