\ 4tH CSV to XLS converter - Copyright 2004, 2009 J.L. Bezemer
\ You can redistribute this file and/or modify it under
\ the terms of the GNU General Public License

include lib/xlswrite.4th
include lib/argopen.4th
include lib/quotes.4th

[hex] 1FFFFFFF constant max-xls [decimal]

: isRF? error? over abs max-xls > or 0= ;
: >XLS 2dup number isRF? if XLS. 2drop else drop -trailing XLStype then ;
: WriteLine dup 0 do over parse -quotes >XLS loop XLScr ;
: ReadLine refill tib count nip /tib -1 [+] = abort" Line too long" ;
: ProcessFile begin ReadLine while WriteLine repeat ;
: CloseFiles drop drop XLSclose close ;

\ Determine the number of fields
: ScanFile                             ( -- n)
  ReadLine 0= abort" Read error"
  0 begin over parse while drop 1+ repeat drop 0 >in ! WriteLine
;

\ Open all files and get ASCII delimiter                             
: OpenFiles                            ( -- h n)
  argn 4 < abort" Usage: csv2xls ascii csv-file xls-file"
  1 args number input 2 arg-open swap 3 args XLSopen
;

: Convert OpenFiles ScanFile ProcessFile CloseFiles ;

Convert
