func replaceEnvReferences(s, refStart, refEnd string) string {
	index := strings.Index(s, refStart)
	for index != -1 {
		endIndex := strings.Index(s[index:], refEnd)
		if endIndex == -1 {
			break
		}
		endIndex += index
		if endIndex > index+len(refStart) {
			ref := s[index : endIndex+len(refEnd)]
			s = strings.Replace(s, ref, os.Getenv(ref[len(refStart):len(ref)-len(refEnd)]), -1)
		} else {
			return s
		}
		index = strings.Index(s, refStart)
	}
	return s
}
replaceEnvReferences performs the actual replacement of env variables
in s, given the placeholder start and placeholder end strings.
package casketfile
import (
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"
)
func Parse(filename string, input io.Reader, validDirectives []string) ([]ServerBlock, error) {
	p := parser{Dispenser: NewDispenser(filename, input), validDirectives: validDirectives}
	return p.parseAll()
}
func allTokens(input io.Reader) ([]Token, error) {
	l := new(lexer)
	err := l.load(input)
	if err != nil {
		return nil, err
	}
	var tokens []Token
	for l.next() {
		tokens = append(tokens, l.token)
	}
	return tokens, nil
}
type parser struct {
	Dispenser
	block           ServerBlock  
	validDirectives []string     
	eof             bool         
	definedSnippets map[string][]Token
}
func (p *parser) parseAll() ([]ServerBlock, error) {
	var blocks []ServerBlock
	for p.Next() {
		err := p.parseOne()
		if err != nil {
			return blocks, err
		}
		if len(p.block.Keys) > 0 {
			blocks = append(blocks, p.block)
		}
	}
	return blocks, nil
}
func (p *parser) parseOne() error {
	p.block = ServerBlock{Tokens: make(map[string][]Token)}
	return p.begin()
}
func (p *parser) begin() error {
	if len(p.tokens) == 0 {
		return nil
	}
	err := p.addresses()
	if err != nil {
		return err
	}
	if p.eof {
		return nil
	}
	if ok, name := p.isSnippet(); ok {
		if p.definedSnippets == nil {
			p.definedSnippets = map[string][]Token{}
		}
		if _, found := p.definedSnippets[name]; found {
			return p.Errf("redeclaration of previously declared snippet %s", name)
		}
		tokens, err := p.snippetTokens()
		if err != nil {
			return err
		}
		p.definedSnippets[name] = tokens
		p.block.Keys = nil
		return nil
	}
	return p.blockContents()
}
func (p *parser) addresses() error {
	var expectingAnother bool
	for {
		tkn := replaceEnvVars(p.Val())
		if tkn == "import" && p.isNewLine() {
			err := p.doImport()
			if err != nil {
				return err
			}
			continue
		}
		if tkn == "{" {
			if expectingAnother {
				return p.Errf("Expected another address but had '%s' - check for extra comma", tkn)
			}
			break
		}
		if tkn != "" {  
			if tkn[len(tkn)-1] == ',' {
				tkn = tkn[:len(tkn)-1]
				expectingAnother = true
			} else {
				expectingAnother = false  
			}
			p.block.Keys = append(p.block.Keys, tkn)
		}
		hasNext := p.Next()
		if expectingAnother && !hasNext {
			return p.EOFErr()
		}
		if !hasNext {
			p.eof = true
			break  
		}
		if !expectingAnother && p.isNewLine() {
			break
		}
	}
	return nil
}
func (p *parser) blockContents() error {
	errOpenCurlyBrace := p.openCurlyBrace()
	if errOpenCurlyBrace != nil {
		p.cursor--
	}
	err := p.directives()
	if err != nil {
		return err
	}
	if errOpenCurlyBrace == nil {
		err = p.closeCurlyBrace()
		if err != nil {
			return err
		}
	}
	return nil
}
func (p *parser) directives() error {
	for p.Next() {
		if p.Val() == "}" {
			break
		}
		if p.Val() == "import" {
			err := p.doImport()
			if err != nil {
				return err
			}
			p.cursor--  
			continue
		}
		if err := p.directive(); err != nil {
			return err
		}
	}
	return nil
}
func (p *parser) doImport() error {
	if !p.NextArg() {
		return p.ArgErr()
	}
	importPattern := replaceEnvVars(p.Val())
	if importPattern == "" {
		return p.Err("Import requires a non-empty filepath")
	}
	if p.NextArg() {
		return p.Err("Import takes only one argument (glob pattern or file)")
	}
	tokensBefore := p.tokens[:p.cursor-1]
	tokensAfter := p.tokens[p.cursor+1:]
	var importedTokens []Token
	if p.definedSnippets != nil && p.definedSnippets[importPattern] != nil {
		importedTokens = p.definedSnippets[importPattern]
	} else {
		absFile, err := filepath.Abs(p.Dispenser.File())
		if err != nil {
			return p.Errf("Failed to get absolute path of file: %s: %v", p.Dispenser.filename, err)
		}
		var matches []string
		var globPattern string
		if !filepath.IsAbs(importPattern) {
			globPattern = filepath.Join(filepath.Dir(absFile), importPattern)
		} else {
			globPattern = importPattern
		}
		if strings.Count(globPattern, "*") > 1 || strings.Count(globPattern, "?") > 1 ||
			(strings.Contains(globPattern, "[") && strings.Contains(globPattern, "]")) {
			return p.Errf("Glob pattern may only contain one wildcard (*), but has others: %s", globPattern)
		}
		matches, err = filepath.Glob(globPattern)
		if err != nil {
			return p.Errf("Failed to use import pattern %s: %v", importPattern, err)
		}
		if len(matches) == 0 {
			if strings.ContainsAny(globPattern, "*?[]") {
				log.Printf("[WARNING] No files matching import glob pattern: %s", importPattern)
			} else {
				return p.Errf("File to import not found: %s", importPattern)
			}
		}
		for _, importFile := range matches {
			newTokens, err := p.doSingleImport(importFile)
			if err != nil {
				return err
			}
			importedTokens = append(importedTokens, newTokens...)
		}
	}
	p.tokens = append(tokensBefore, append(importedTokens, tokensAfter...)...)
	p.cursor--
	return nil
}
func (p *parser) doSingleImport(importFile string) ([]Token, error) {
	file, err := os.Open(importFile)
	if err != nil {
		return nil, p.Errf("Could not import %s: %v", importFile, err)
	}
	defer file.Close()
	if info, err := file.Stat(); err != nil {
		return nil, p.Errf("Could not import %s: %v", importFile, err)
	} else if info.IsDir() {
		return nil, p.Errf("Could not import %s: is a directory", importFile)
	}
	importedTokens, err := allTokens(file)
	if err != nil {
		return nil, p.Errf("Could not read tokens while importing %s: %v", importFile, err)
	}
	filename, err := filepath.Abs(importFile)
	if err != nil {
		return nil, p.Errf("Failed to get absolute path of file: %s: %v", p.Dispenser.filename, err)
	}
	for i := 0; i < len(importedTokens); i++ {
		importedTokens[i].File = filename
	}
	return importedTokens, nil
}
func (p *parser) directive() error {
	dir := replaceEnvVars(p.Val())
	nesting := 0
	if !p.validDirective(dir) {
		return p.Errf("Unknown directive '%s'", dir)
	}
	p.block.Tokens[dir] = append(p.block.Tokens[dir], p.tokens[p.cursor])
	for p.Next() {
		if p.Val() == "{" {
			nesting++
		} else if p.isNewLine() && nesting == 0 {
			p.cursor--  
			break
		} else if p.Val() == "}" && nesting > 0 {
			nesting--
		} else if p.Val() == "}" && nesting == 0 {
			return p.Err("Unexpected '}' because no matching opening brace")
		} else if p.Val() == "import" && p.isNewLine() {
			if err := p.doImport(); err != nil {
				return err
			}
			p.cursor--  
			continue
		}
		p.tokens[p.cursor].Text = replaceEnvVars(p.tokens[p.cursor].Text)
		p.block.Tokens[dir] = append(p.block.Tokens[dir], p.tokens[p.cursor])
	}
	if nesting > 0 {
		return p.EOFErr()
	}
	return nil
}
func (p *parser) openCurlyBrace() error {
	if p.Val() != "{" {
		return p.SyntaxErr("{")
	}
	return nil
}
func (p *parser) closeCurlyBrace() error {
	if p.Val() != "}" {
		return p.SyntaxErr("}")
	}
	return nil
}
func (p *parser) validDirective(dir string) bool {
	if p.validDirectives == nil {
		return true
	}
	for _, d := range p.validDirectives {
		if d == dir {
			return true
		}
	}
	return false
}
func replaceEnvVars(s string) string {
	s = replaceEnvReferences(s, "{%", "%}")
	s = replaceEnvReferences(s, "{$", "}")
	return s
}