func BindEncoding(L *lua.State) {
	luar.Register(L, "carbon", luar.Map{
		"_enc_base64_enc": (func(str string) string {
			return base64.StdEncoding.EncodeToString([]byte(str))
		}),
		"_enc_base64_dec": (func(str string) (string, error) {
			data, err := base64.StdEncoding.DecodeString(str)
			return string(data), err
		}),
	})
}
BindEncoding binds functions to encode and decode between things.
package middleware
import (
	"bufio"
	"bytes"
	"crypto/tls"
	"encoding/base64"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"mime"
	"net"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"reflect"
	"regexp"
	"time"
	"github.com/carbonsrv/carbon/modules/glue"
	"github.com/carbonsrv/carbon/modules/helpers"
	"github.com/carbonsrv/carbon/modules/scheduler"
	"github.com/carbonsrv/carbon/modules/static"
	"github.com/vifino/golua/lua"
	"github.com/vifino/luar"
	"github.com/DeedleFake/Go-PhysicsFS/physfs"
	"github.com/GeertJohan/go.linenoise"
	"github.com/fzzy/radix/redis"
	"github.com/gin-gonic/gin"
	"github.com/mattn/go-runewidth"
	"github.com/nsf/termbox-go"
	"github.com/pmylund/go-cache"
	"github.com/shurcooL/github_flavored_markdown"
	"github.com/vifino/contrib/gzip"
	"database/sql"
	_ "github.com/cznic/ql/driver"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/lib/pq"
	_ "github.com/mattn/go-sqlite3"
	_ "github.com/vifino/go-yql"
)
var webroot string
func Bind(L *lua.State, root string) {
	webroot = root
	luar.Register(L, "var", luar.Map{  
		"root": root,
	})
	BindCarbon(L)
	BindMiddleware(L)
	BindRedis(L)
	BindSQL(L)
	BindKVStore(L)
	BindFS(L)
	BindIOEnhancements(L)
	BindOSEnhancements(L)
	BindThread(L)
	BindNet(L)
	BindConversions(L)
	BindMime(L)
	BindComs(L)
	BindPipe(L)
	BindExec(L)
	BindEncoding(L)
	BindMarkdown(L)
	BindLinenoise(L)
	BindTermbox(L)
	BindOther(L)
	BindRandomString(L)
}
func BindCarbon(L *lua.State) {
	luar.Register(L, "carbon", luar.Map{  
		"glue": glue.GetGlue,
	})
}
func BindEngine(L *lua.State) {
	luar.Register(L, "carbon", luar.Map{
		"_gin_new": gin.New,
	})
}
func BindMiddleware(L *lua.State) {
	luar.Register(L, "mw", luar.Map{
		"Logger":   gin.Logger,
		"Recovery": gin.Recovery,
		"Lua":       Lua,
		"DLR_NS":    DLR_NS,
		"DLR_RUS":   DLR_RUS,
		"DLRWS_NS":  DLRWS_NS,
		"DLRWS_RUS": DLRWS_RUS,
		"ExtRoute": (func(plan map[string]interface{}) func(*gin.Context) {
			newplan := make(Plan, len(plan))
			for k, v := range plan {
				newplan[k] = v.(func(*gin.Context))
			}
			return ExtRoute(newplan)
		}),
		"VHOST": (func(plan map[string]interface{}) func(*gin.Context) {
			newplan := make(Plan, len(plan))
			for k, v := range plan {
				newplan[k] = v.(func(*gin.Context))
			}
			return VHOST(newplan)
		}),
		"VHOST_Middleware": (func(plan map[string]interface{}) gin.HandlerFunc {
			newplan := make(Plan, len(plan))
			for k, v := range plan {
				newplan[k] = v.(gin.HandlerFunc)
			}
			return VHOST_Middleware(newplan)
		}),
		"if_regex":       If_Regexp,
		"if_written":     If_Written,
		"if_status":      If_Status,
		"if_not_regex":   If_Not_Regexp,
		"if_not_written": If_Not_Written,
		"if_not_status":  If_Not_Status,
		"GZip": func() func(*gin.Context) {
			return gzip.Gzip(gzip.DefaultCompression)
		},
		"Echo":     EchoHTML,
		"EchoText": Echo,
	})
	luar.Register(L, "carbon", luar.Map{
		"_mw_CGI":         CGI,          
		"_mw_CGI_Dynamic": CGI_Dynamic,  
		"_mw_combine": (func(middlewares []interface{}) func(*gin.Context) {  
			newmiddlewares := make([]func(*gin.Context), len(middlewares))
			for k, v := range middlewares {
				newmiddlewares[k] = v.(func(*gin.Context))
			}
			return Combine(newmiddlewares)
		}),
	})
	L.DoString(glue.RouteGlue())
}
func BindStatic(L *lua.State, cfe *cache.Cache) {
	luar.Register(L, "carbon", luar.Map{
		"_staticserve": (func(path, prefix string) func(*gin.Context) {
			return staticServe.ServeCached(prefix, staticServe.PhysFS(path, prefix, true, true), cfe)
		}),
	})
}
var physfs_fhandles = make(map[string]*physfs.File)
var physfs_fhandles_used = make(map[string]int)
func physfs_openfile(filename string) (*physfs.File, error) {
	fh, ok := physfs_fhandles[filename]
	if ok {
		return fh, nil
	}
	fh, err := physfs.Open(filename)
	if err != nil {
		physfs_fhandles[filename] = fh
		return fh, nil
	}
	return fh, err
}
func physfs_needfile(filename string) {
	physfs_fhandles_used[filename] += 1
}
func physfs_closefile(filename string) error {
	fh, ok := physfs_fhandles[filename]
	if ok {
		if physfs_fhandles_used[filename] == 1 {
			delete(physfs_fhandles, filename)
			delete(physfs_fhandles_used, filename)
			return fh.Close()
		}
	}
	return errors.New("File not opened.")
}
func BindFS(L *lua.State) {
	luar.Register(L, "carbon", luar.Map{  
		"_physfs_mount":       physfs.Mount,
		"_physfs_exists":      physfs.Exists,
		"_physfs_isDir":       physfs.IsDirectory,
		"_physfs_getFS":       physfs.FileSystem,
		"_physfs_mkdir":       physfs.Mkdir,
		"_physfs_umount":      physfs.RemoveFromSearchPath,
		"_physfs_delete":      physfs.Delete,
		"_physfs_setWriteDir": physfs.SetWriteDir,
		"_physfs_getWriteDir": physfs.GetWriteDir,
		"_physfs_list": func(name string) (fl []string, err error) {
			if physfs.Exists(name) {
				if physfs.IsDirectory(name) {
					return physfs.EnumerateFiles(name)
				}
				return nil, errors.New("readdirent: not a directory")
			}
			return nil, errors.New("open " + name + ": no such file or directory")
		},
		"_physfs_readfile": func(filename string) (string, error) {
			if physfs.Exists(filename) {
				physfs_needfile(filename)
				f, err := physfs_openfile(filename)
				if err != nil {
					return "", err
				}
				defer physfs_closefile(filename)
				fi, err := f.Stat()
				if err != nil {
					return "", err
				}
				r := bufio.NewReader(f)
				buf := make([]byte, fi.Size())
				_, err = r.Read(buf)
				if err != nil {
					if err.Error() == "EOF" {  
						physfs_needfile(filename)
						f2, _ := physfs_openfile(filename)
						buf := bytes.NewBuffer(nil)
						io.Copy(buf, f2)
						physfs_closefile(filename)
						return string(buf.Bytes()), nil
					}
					return "", err
				}
				return string(buf), err
			}
			return "", errors.New(filename + ": No such file or directory")
		},
		"_physfs_readat": func(filename string, at, count int64) (string, error, int) {
			if physfs.Exists(filename) {
				f, err := physfs_openfile(filename)
				if err != nil {
					return "", err, -1
				}
				buf := make([]byte, count)
				f.Seek(at, os.SEEK_SET)
				read, _ := f.Read(buf)
				return string(buf[:read]), err, read
			}
			return "", errors.New(filename + ": No such file or directory"), -1
		},
		"_physfs_readn": func(filename string, count int64) (string, error, int) {
			if physfs.Exists(filename) {
				f, err := physfs_openfile(filename)
				if err != nil {
					return "", err, -1
				}
				buf := make([]byte, count)
				read, _ := f.Read(buf)
				return string(buf[:read]), err, read
			}
			return "", errors.New(filename + ": No such file or directory"), -1
		},
		"_physfs_modtime": func(name string) (int64, error) {
			mt, err := physfs.GetLastModTime(name)
			if err != nil {
				return -1, err
			}
			return mt.UTC().Unix(), nil
		},
		"_physfs_size": func(path string) (int64, error) {
			physfs_needfile(path)
			f, err := physfs_openfile(path)
			defer physfs_closefile(path)
			if err != nil {
				return -1, err
			}
			info, err := f.Stat()
			if err != nil {
				return -1, err
			}
			return info.Size(), nil
		},
		"_physfs_needfile": physfs_needfile,
		"_physfs_close":    physfs_closefile,
	})
	luar.Register(L, "carbon", luar.Map{
		"_filesystem_readfile": func(fs http.FileSystem, filename string) (string, error) {
			f, err := fs.Open(filename)
			if err != nil {
				return "", err
			}
			defer f.Close()
			fi, err := f.Stat()
			if err != nil {
				return "", err
			}
			r := bufio.NewReader(f)
			buf := make([]byte, fi.Size())
			_, err = r.Read(buf)
			if err != nil {
				if err.Error() == "EOF" {  
					f2, _ := fs.Open(filename)
					buf := bytes.NewBuffer(nil)
					io.Copy(buf, f2)
					f2.Close()
					return string(buf.Bytes()), nil
				}
				return "", err
			}
			return string(buf), err
		},
		"_filesystem_readat": func(fs http.FileSystem, filename string, at, count int64) (string, error, int) {
			f, err := fs.Open(filename)
			if err != nil {
				return "", err, -1
			}
			defer f.Close()
			buf := make([]byte, count)
			if s, ok := f.(io.Seeker); ok {
				s.Seek(at, os.SEEK_SET)
			} else {
				io.CopyN(ioutil.Discard, f, at)
			}
			read, _ := f.Read(buf)
			return string(buf[:read]), err, read
		},
		"_filesystem_exists": func(fs http.FileSystem, filename string) bool {
			f, err := fs.Open(filename)
			if err != nil {
				return false
			}
			f.Close()
			return true
		},
		"_filesystem_isdir": func(fs http.FileSystem, filename string) bool {
			f, err := fs.Open(filename)
			if err != nil {
				return false
			}
			defer f.Close()
			fi, err := f.Stat()
			if err != nil {
				return false
			}
			return fi.IsDir()
		},
		"_filesystem_modtime": func(fs http.FileSystem, filename string) (int64, error) {
			f, err := fs.Open(filename)
			if err != nil {
				return -1, err
			}
			fi, err := f.Stat()
			if err != nil {
				return -1, err
			}
			return fi.ModTime().UTC().Unix(), nil
		},
		"_filesystem_size": func(fs http.FileSystem, filename string) (int64, error) {
			f, err := fs.Open(filename)
			if err != nil {
				return -1, err
			}
			defer f.Close()
			fi, err := f.Stat()
			if err != nil {
				return -1, err
			}
			return fi.Size(), nil
		},
		"_filesystem_list": func(fs http.FileSystem, dirname string) ([]string, error) {
			f, err := fs.Open(dirname)
			if err != nil {
				return make([]string, 0), err
			}
			defer f.Close()
			fi, err := f.Stat()
			if err != nil {
				fmt.Println("Stat")
				return make([]string, 0), err
			}
			if fi.IsDir() == false {
				fmt.Println("isdir")
				return make([]string, 0), errors.New("dirname is not dir")
			}
			files, err := f.Readdir(-1)
			if err != nil {
				fmt.Println("readdir")
				return make([]string, 0), err
			}
			list := make([]string, len(files))
			for i := range files {
				list[i] = files[i].Name()
			}
			return list, nil
		},
	})
}
func BindIOEnhancements(L *lua.State) {
	luar.Register(L, "carbon", luar.Map{  
		"_io_list": (func(path string) ([]string, error) {
			files, err := ioutil.ReadDir(path)
			if err != nil {
				return make([]string, 1), err
			}
			list := make([]string, len(files))
			for i := range files {
				list[i] = files[i].Name()
			}
			return list, nil
		}),
		"_io_glob": filepath.Glob,
		"_io_modtime": (func(path string) (int64, error) {
			info, err := os.Stat(path)
			if err != nil {
				return -1, err
			}
			return info.ModTime().UTC().Unix(), nil
		}),
		"_io_isDir": func(path string) bool {
			info, err := os.Stat(path)
			if err != nil {
				return false
			}
			return info.IsDir()
		},
		"_io_size": func(path string) (int64, error) {
			info, err := os.Stat(path)
			if err != nil {
				return -1, err
			}
			return info.Size(), nil
		},
	})
}
func BindOSEnhancements(L *lua.State) {
	luar.Register(L, "carbon", luar.Map{  
		"_os_exists": (func(path string) bool {
			if _, err := os.Stat(path); err == nil {
				return true
			}
			return false
		}),
		"_os_sleep": (func(milliseconds int64) {
			time.Sleep(time.Duration(milliseconds) * time.Millisecond)
		}),
		"_os_chdir":     os.Chdir,
		"_os_abspath":   filepath.Abs,
		"_os_pwd":       os.Getwd,
		"_os_removeall": os.RemoveAll,
		"_os_mkdir": func(path string, mode uint32) error {
			return os.Mkdir(path, os.FileMode(mode))
		},
	})
}
func BindRedis(L *lua.State) {
	luar.Register(L, "redis", luar.Map{
		"connectTimeout": (func(host string, timeout float64) (*redis.Client, error) {
			return redis.DialTimeout("tcp", host, time.Duration(timeout)*time.Second)
		}),
		"connect": (func(host string) (*redis.Client, error) {
			return redis.Dial("tcp", host)
		}),
	})
}
type sql_rows struct {
	Len  int
	Vals []map[string]interface{}
}
func BindSQL(L *lua.State) {
	luar.Register(L, "carbon", luar.Map{
		"_sql_drivers": sql.Drivers,
		"_sql_open":    sql.Open,
		"_sql_rows": (func(rows *sql.Rows) (sql_rows, error) {
			var res = make([]map[string]interface{}, 0)
			rowno := 0
			names, err := rows.Columns()
			if err != nil {
				return sql_rows{}, err
			}
			numnames := len(names)
			for rows.Next() {
				var elems = make([]interface{}, numnames)
				for i := range elems {
					var ii interface{}
					elems[i] = &ii
				}
				err := rows.Scan(elems...)
				if err != nil {
					return sql_rows{}, err
				}
				rowtmp := make(map[string]interface{})
				for i, name := range names {
					var elm_val = *(elems[i].(*interface{}))
					var elm_type = reflect.TypeOf(elm_val).String()
					if elm_type == "[]uint8" {
						rowtmp[name] = string(elm_val.([]uint8))
					} else {
						rowtmp[name] = elm_val
					}
				}
				n := len(res)
				newres := make([]map[string]interface{}, n+1)
				copy(newres, res)
				newres[n] = rowtmp
				res = newres
				rowno += 1
			}
			final := sql_rows{
				Len:  len(res),
				Vals: res,
			}
			err = rows.Err()
			if err != nil {
				return final, err
			} else {
				return final, nil
			}
		}),
		"_sql_getrow": (func(rows sql_rows, n int) (map[string]interface{}, error) {
			if n <= rows.Len && n > 0 {
				return rows.Vals[n-1], nil
			}
			return make(map[string]interface{}), errors.New("out of bounds")
		}),
	})
}
func BindKVStore(L *lua.State) {  
	luar.Register(L, "kvstore", luar.Map{
		"_set": (func(k string, v interface{}) {
			kvstore.Set(k, v, -1)
		}),
		"_set_timeout": (func(k string, v interface{}, timeout int64) {
			kvstore.Set(k, v, time.Duration(timeout)*time.Millisecond)
		}),
		"_del": (func(k string) {
			kvstore.Delete(k)
		}),
		"_get": (func(k string) interface{} {
			res, found := kvstore.Get(k)
			if found {
				return res
			}
			return nil
		}),
		"_inc": (func(k string, n int64) error {
			return kvstore.Increment(k, n)
		}),
		"_dec": (func(k string, n int64) error {
			return kvstore.Decrement(k, n)
		}),
	})
}
func BindThread(L *lua.State) {
	luar.Register(L, "thread", luar.Map{
		"_spawn": (func(bcode string, dobind bool, vals map[string]interface{}, buffer int) (chan interface{}, error) {
			var ch chan interface{}
			if buffer == -1 {
				ch = make(chan interface{})
			} else {
				ch = make(chan interface{}, buffer)
			}
			L := luar.Init()
			Bind(L, webroot)
			err := L.DoString(glue.MainGlue())
			if err != nil {
				panic(err)
			}
			luar.Register(L, "", luar.Map{
				"threadcom": ch,
			})
			if dobind {
				luar.Register(L, "", vals)
			}
			if L.LoadBuffer(bcode, len(bcode), "thread") != 0 {
				return make(chan interface{}), errors.New(L.ToString(-1))
			}
			scheduler.Add(func() {
				if L.Pcall(0, 0, 0) != 0 {  
					fmt.Println("thread error: " + L.ToString(-1))
				}
				L.Close()
				close(ch)
			})
			return ch, nil
		}),
	})
}
func BindComs(L *lua.State) {
	luar.Register(L, "com", luar.Map{
		"create": (func() chan interface{} {
			return make(chan interface{})
		}),
		"close": (func(c chan interface{}) {
			close(c)
		}),
		"createBuffered": (func(buffer int) chan interface{} {
			return make(chan interface{}, buffer)
		}),
		"receive": (func(c chan interface{}) interface{} {
			return <-c
		}),
		"try_receive": (func(c chan interface{}) interface{} {
			select {
			case msg := <-c:
				return msg
			default:
				return nil
			}
		}),
		"send": (func(c chan interface{}, val interface{}) bool {
			c <- val
			return true
		}),
		"try_send": (func(c chan interface{}, val interface{}) bool {
			select {
			case c <- val:
				return true
			default:
				return false
			}
		}),
		"size": (func(c chan interface{}) int {
			return len(c)
		}),
		"cap": (func(c chan interface{}) int {
			return cap(c)
		}),
		"pipe": (func(a, b chan interface{}) {
			for {
				b <- <-a
			}
		}),
		"pipe_background": (func(a, b chan interface{}) {
			scheduler.Add(func() {
				for {
					b <- <-a
				}
			})
		}),
	})
}
type Pipe struct {
	reader *io.PipeReader
	writer *io.PipeWriter
}
func (p *Pipe) Read(bytes int) (error, error) {
	b := make([]byte, bytes)
	_, err := p.reader.Read(b)
	if err != nil {
		return nil, err
	}
	return errors.New(string(b)), nil
}
func (p *Pipe) Write(text string) error {
	_, err := p.writer.Write([]byte(text))
	return err
}
func (p *Pipe) Close() error {
	return p.reader.Close()
}
func BindPipe(L *lua.State) {
	luar.Register(L, "io", luar.Map{
		"pipe": func() Pipe {
			r, w := io.Pipe()
			return Pipe{
				writer: w,
				reader: r,
			}
		},
	})
}
type Command struct {
	stdout io.ReadCloser
	stderr io.ReadCloser
	stdin  io.WriteCloser
	cmd    *exec.Cmd
}
func (c *Command) Read_Stdout(bytes int) (error, error) {
	b := make([]byte, bytes)
	_, err := c.stdout.Read(b)
	if err != nil {
		return nil, err
	}
	return errors.New(string(b)), nil
}
func (c *Command) Read_Stderr(bytes int) (error, error) {
	b := make([]byte, bytes)
	_, err := c.stderr.Read(b)
	if err != nil {
		return nil, err
	}
	return errors.New(string(b)), nil
}
func (c *Command) Write_Stdin(text string) error {
	_, err := c.stdin.Write([]byte(text))
	return err
}
func (c *Command) Close() {
	c.stdin.Close()
	c.stdout.Close()
	c.stderr.Close()
}
func (c *Command) Kill() error {
	e := c.cmd.Process.Kill()
	c.Close()
	return e
}
func (c *Command) State() *os.ProcessState {
	return c.cmd.ProcessState
}
func BindExec(L *lua.State) {
	luar.Register(L, "exec", luar.Map{
		"exec": func(cmd string, args ...string) (Command, error) {
			command := exec.Command(cmd, args...)
			stdin, err := command.StdinPipe()
			if err != nil {
				return Command{}, err
			}
			stdout, err := command.StdoutPipe()
			if err != nil {
				return Command{}, err
			}
			stderr, err := command.StderrPipe()
			if err != nil {
				return Command{}, err
			}
			c := Command{
				stdin:  stdin,
				stdout: stdout,
				stderr: stderr,
				cmd:    command,
			}
			if err := command.Start(); err != nil {
				return Command{}, err
			}
			return c, nil
		},
	})
}
func BindNet(L *lua.State) {
	luar.Register(L, "net", luar.Map{
		"dial": net.Dial,
		"dial_tls": func(proto, addr string) (net.Conn, error) {
			config := tls.Config{InsecureSkipVerify: true}  
			return tls.Dial(proto, addr, &config)
		},
		"listen": net.Listen,
		"write": (func(con interface{}, str string) {
			fmt.Fprintf(con.(net.Conn), str)
		}),
		"readline": (func(con interface{}) (string, error) {
			return bufio.NewReader(con.(net.Conn)).ReadString('\n')
		}),
		"read": (func(con interface{}, count int) (string, error) {
			b := make([]byte, count)
			_, err := con.(net.Conn).Read(b)
			if err != nil {
				return "", err
			}
			return string(b), nil
		}),
		"pipe_conn": (func(con interface{}, input, output chan interface{}) {
			go func() {
				reader := bufio.NewReader(con.(net.Conn))
				for {
					line, _ := reader.ReadString('\n')
					output <- line
				}
			}()
			for {
				line := <-input
				fmt.Fprintf(con.(net.Conn), line.(string))
			}
		}),
		"pipe_conn_background": (func(con interface{}, input, output chan interface{}) {
			scheduler.Add(func() {
				reader := bufio.NewReader(con.(net.Conn))
				for {
					line, _ := reader.ReadString('\n')
					output <- line
				}
			})
			scheduler.Add(func() {
				for {
					line := <-input
					fmt.Fprintf(con.(net.Conn), line.(string))
				}
			})
		}),
	})
}
func BindMime(L *lua.State) {
	luar.Register(L, "carbon", luar.Map{
		"_mime_byext":  mime.TypeByExtension,
		"_mime_bytype": mime.ExtensionsByType,
	})
}
func BindConversions(L *lua.State) {
	luar.Register(L, "convert", luar.Map{
		"stringtocharslice": (func(x string) []byte {
			return []byte(x)
		}),
		"charslicetostring": (func(x []byte) string {
			return string(x)
		}),
	})
}