   dup needs-escaping? [ escape-quotes enclose-in-quotes ] when ; inline
     
 : write-row ( row -- )
-  [ delimiter> write1 ] [ escape-if-required write ] interleave nl ; inline
+  [ delimiter get write1 ] [ escape-if-required write ] interleave nl ; inline
     
 : write-csv ( rows outstream -- )
-  init-vars
   [ [ write-row ] each ] with-output-stream ;

: (csv) ( -- )
  row append-if-row-not-empty
  [ (csv) ] when ;

: init-vars ( -- )
  delimiter> [ CHAR: , >delimiter ] unless ; inline 
  
: csv-row ( stream -- row )
  init-vars
  [ row nip ] with-input-stream ;

: csv ( stream -- rows )
  init-vars
  [ [ (csv) ] { } make ] with-input-stream ;

: with-delimiter ( char quot -- )
  delimiter swap with-variable ; inline


    
: needs-escaping? ( cell -- ? )
  [ "\n\"" delimiter> suffix member? ] contains? ; inline ! "

: escape-quotes ( cell -- cell' )
  [ [ dup , CHAR: " = [ CHAR: " , ] when ] each ] "" make ; inline

! Simple CSV Parser
! Phil Dawes phil@phildawes.net

USING: kernel sequences io namespaces combinators unicode.categories ;
IN: csv

SYMBOL: delimiter

CHAR: , delimiter set-global

: delimiter> delimiter get ; inline
    
DEFER: quoted-field ( -- endchar )
    
! trims whitespace from either end of string
: trim-whitespace ( str -- str )
