package main

import "strings"
import "time"
import "os"
import "os/exec"
import "bufio"
import "log"

// import "io"
// import "fmt"
// import "reflect"
import "github.com/davecgh/go-spew/spew"

import "github.com/svent/go-nbreader"

func shell(cmdline string) {
	cmdArgs := strings.Fields(cmdline)

	cmd := exec.Command(cmdArgs[0], cmdArgs[1:len(cmdArgs)]...)
	stdout, _ := cmd.StdoutPipe()
	stderr, _ := cmd.StderrPipe()
	cmd.Start()

	f := bufio.NewWriter(os.Stdout)

	newreader := bufio.NewReader(stdout)
	nbr := nbreader.NewNBReader(newreader, 1024)

	newerrreader := bufio.NewReader(stderr)
	nbrerr := nbreader.NewNBReader(newerrreader, 1024)

	for {
		time.Sleep(2 * time.Millisecond)   // only check the buffer 500 times a second
		// log.Println("sleep done")

		oneByte := make([]byte, 1024)
		count, err := nbr.Read(oneByte)

		if (err != nil) {
			log.Println("Read() count = ", count, "err = ", err)
			oneByte = make([]byte, 1024)
			count, err = nbr.Read(oneByte)
			f.Write([]byte(string(oneByte)))
			f.Flush()
		}
		f.Write([]byte(string(oneByte)))
		f.Flush()

		oneByte = make([]byte, 1024)
		count, err = nbrerr.Read(oneByte)

		if (err != nil) {
			oneByte = make([]byte, 1024)
			count, err = nbrerr.Read(oneByte)
			f.Write([]byte(string(oneByte)))
			f.Flush()

			log.Println("Read() count = ", count, "err = ", err)
			spew.Dump(cmd.Process)
			spew.Dump(cmd.ProcessState)
			cmd.Wait()
			return
		} else {
			f.Write([]byte(string(oneByte)))
			f.Flush()
		}

		// spew.Dump(reflect.ValueOf(cmd.Process).Elem())
	}

	cmd.Wait()
}
