1#! /bin/sh
2# -*- tcl -*- \
3exec tclsh "$0" ${1+"$@"}
4
5# Generate HTML table from CSV data
6
7package require csv
8package require cmdline
9package require report
10package require struct
11
12# ----------------------------------------------------
13# csv2html ?-sep sepchar? file...
14#
15# Argument processing and checks.
16
17set sepChar ,
18set title   "Title"
19set usage "Usage: $argv0 ?-sep sepchar? ?-title string? file..."
20
21while {[set ok [cmdline::getopt argv {sep.arg title.arg} opt val]] > 0} {
22    #puts stderr "= $opt $val"
23    switch -exact -- $opt {
24	sep   {set sepChar $val}
25	title {set title   $val}
26    }
27}
28if {($ok < 0) || ([llength $argv] < 1)} {
29    #puts stderr "A >>$ok<< >>[llength $argv]<<"
30    puts stderr $usage
31    exit -1
32}
33
34set files $argv
35
36if {[llength $files] == 0} {
37    set files -
38}
39
40# ----------------------------------------------------
41# Actual processing, uses the following information from the
42# commandline:
43#
44# files   - name of the files to read
45# indices - preprocessed indices
46# sepChar - separator character
47
48::report::defstyle html {} {
49    set c  [columns]
50    set cl $c ; incr cl -1
51    data set "<tr> [split [string repeat " " $cl] ""] </tr>"
52    for {set col 0} {$col < $c} {incr col} {
53	pad $col left  "<td>"
54	pad $col right "</td>"
55    }
56    return
57}
58
59set stdin 1
60set first 1
61
62struct::matrix::matrix m
63
64foreach f $files {
65    if {![string compare $f -]} {
66	if {!$stdin} {
67	    puts stderr "Cannot use - (stdin) more than once"
68	    exit -1
69	}
70	set in stdin
71	set stdin 0
72    } else {
73	set in [open $f r]
74    }
75
76    if {$first} {
77	set first 0
78	if {[gets $in line] < 0} {
79	    continue
80	}
81	set data [::csv::split $line $sepChar]
82
83	m add columns [llength $data]
84	m add row $data
85    }
86
87    csv::read2matrix $in m $sepChar
88
89    if {[string compare $f -]} {
90	close $in
91    }
92}
93
94# And writing the accumulated results
95
96report::report r [m columns] style html
97
98puts stdout "<html><head><title>$title</title></head><body>"
99puts stdout "<h1>$title</h1>"
100puts stdout "<p><table border=1>"
101r printmatrix2channel m stdout
102#m format 2chan r stdout
103puts stdout "</table></p></body></html>"
104r destroy
105
106exit
107