proc print {msg} {
	puts "Tcl: $msg"
}

proc split_to_words {str} {
	return [regexp -all -inline {\S+} $str]
}

proc file_exists {path} {
	return [file exists $path]
}

proc file_get_lines {path} {
	set fp [open $path r]
	set file_data [read $fp]
	close $fp

	return [split $file_data "\n"]
}

# included contains a list of filenames that have already been included
proc process_includes {lines workingpath included} {
	set output {}
	set shaderdir "shaders/"
	set linenum 0

	foreach line $lines {
		#set line [regsub -all {;\S*$} $line ""] 

		set words [split_to_words $line]

		lappend output $line
		incr linenum

		if {[lindex $words 0] != "#include"} {
			continue
		}

		# remove double quotes from path
		set path [regsub -all {(\")(.*?)(\")} [lindex $words 1] {\2}]

		set fullpath "$workingpath$shaderdir$path"

		if {[file_exists $fullpath] == 0} {
			print "Error: Can't include file $fullpath"
			continue
		}

		# remove the latest line since it contains the #include command
		set output [lrange $output 0 [expr [llength $output] - 2]]
		
		# add the current file to the list of already included files
		lappend included "$path"

		set newfile [file_get_lines $fullpath]
		set newfile [process_includes $newfile $workingpath $included]
		# concatenate file_get_lines output to the $output list
		#lappend output "#line [expr {$linenum - 1}]"
		set output [concat $output $newfile]
	}

	return $output
}


proc process_shader {path} {
	set assetdir [getAssetSourceDir]
	set fullpath "$assetdir$path"
	#print "Parsing $fullpath"
	set filedata [file_get_lines $fullpath]
	set lines [process_includes "$filedata" "$assetdir" {"$path"}]
	set output {}
	
	return [join $lines "\n"]
}
