if {[llength $argv] < 1} {
  puts "makeCStructFromDirs.tcl dir1 dir2 ..."
  puts "Puts .tcl files into C code"
  exit -1
}

load libbztclLite.so

set counter 0

proc processDir {dirName} {
  global base of counter
  
  set len [string length $base]

  if {[string equal "file" [file type $dirName]]} {
      set dst "/[file tail $dirName]"
      puts $of "// $dirName"
      set dlen [dumpFile $of $dirName mem_data$counter]
      puts $of "memFileData file$counter = {\"$dst\", $dlen, mem_data$counter };"

      incr counter
    return
  }

  foreach fn [glob -nocomplain $dirName/*] {
    if {[string equal "directory" [file type $fn]]} {
      processDir $fn
    } else {
      # Skip links, and funny files, and things I know we won't need
      if {![string equal "file" [file type $fn]]} {continue}
      if {[string first .gif $fn] >= 0} {continue}
      if {[string first .ppm $fn] >= 0} {continue}
      if {[string first .eps $fn] >= 0} {continue}
      set dst [string range $fn $len end]
      puts $of "// $fn"

      set dlen [dumpFile $of $fn mem_data$counter]

      puts $of "memFileData file$counter = {\"$dst\", $dlen, mem_data$counter };"

      incr counter
    }
  }
}

proc dumpFile {of path name} {
    set if [open $path r]
    set d [read $if]
    close $if
    set cmp [bzLite compress $d]

    binary scan $cmp c[string length $cmp] d1
    foreach d $d1 {
      lappend data [expr {$d & 0xff}]
    }
    puts $of "static unsigned char $name\[\] = {[join $data ,]};"
    return [string length $cmp]
}

# Build the .h file 
# Define the structure, then fill it.
# 
#  MOVED to memFile.h
#
# set of [open memFileData.h w]
#puts $of {
#  typedef struct memFileData {
#    char *name;
#    int dataLen;
#    unsigned char data[];
#  } memFileData;
#}
#close $of

set of [open [lindex $argv 0] w]

puts $of {#include "memFile.h"}



foreach dir [lrange $argv 1 end] {
  set base $dir
  set base [file dirname $dir]
  processDir $dir
}

puts $of "memFileData *tclTkInitData\[\] = {"
for {set i 0} {$i < $counter} {incr i} {
  puts $of "&file$i, "
}
puts $of "0};"

