main.go at [90877fa64f]

File src/0dev.org/commands/mtf/main.go artifact a0aa5f4298 part of check-in 90877fa64f


package main

import (
	fib "0dev.org/encoding/fibonacci"
	mtf "0dev.org/encoding/mtf"
	iou "0dev.org/ioutil"
	"flag"
	"io"
	"os"
)

func main() {
	d := flag.Bool("d", false, "Toggle decode mode.")
	flag.Parse()

	var (
		input  io.Reader = iou.SizedReader(os.Stdin, 4096)
		output io.Writer = iou.SizedWriter(os.Stdout, 4096)
		code   int
	)

	// Exit handler
	defer func() {
		os.Exit(code)
	}()

	// Flush the output buffer
	defer output.Write(nil)

	if *d {
		input = mtf.Decoder(fib.Decoder(input))
	} else {
		input = mtf.Encoder(input)

		// Encode output as fibonacci integers
		output = fib.Encoder(output)
		defer output.Write(nil)
	}

	if _, err := io.Copy(output, input); err != nil {
		os.Stderr.WriteString("Error while transforming data.\n" + err.Error())
		code = 1
	}
}