#!/bin/sh
# \
    exec wish $0 $@
package require Biff

namespace eval Cvs2Biff {
}

proc Cvs2Biff::convert { infile outfile } {
    set fd [open $infile]
    Biff::new_table tab BIFF2
    Biff::new_sheet tab cells
    Biff::Biff2
    set y 0
    Debug::printMessage information "read file $infile..."
    set maxx 0
    while { ![eof $fd] } {
        gets $fd line
        set x 0
        foreach col [split $line \;] {
            # remove leading zeros
            if { [regexp {^0+[1-9]+$} $col] } {
                regsub  ^0+ $col "" col
            }
            if { $col != "" } {
                set cells($x,$y) $col 
            }
            incr x
        }
        if { $x > $maxx } {
            set maxx $x
        }
        incr y
        if { $y % 1000 == 0} {
            Biff::pack_some_data cells
        }
    }
    close $fd
    Biff::setDimension tab 0 0 $maxx $y
    Debug::printMessage information "write file $outfile..."
    Biff::write_table $outfile tab {{$infile cells}}
}

if { [file tail $argv0] == "cvs2biff.tcl" } {
    if { [llength $argv] != 2 } {
        puts "usage: $argv0 infile.cvs outfile.xls"
        exit 1
    }
    Cvs2Biff::convert [lindex $argv 0] [lindex $argv 1]
    exit
}
         

