 CHAR: , delimiter set-global
 
 <PRIVATE
-
-: delimiter> ( -- delimiter ) delimiter get ; inline
 
 MEMO: field-delimiters ( delimiter -- field-end quoted-field )
     [ "\n" swap suffix ] [ "\"\n" swap suffix ] bi ; inline

    [ dupd needs-escaping? ] dip
    [ escape-quotes ] [ stream-write ] bi-curry if ; inline

: (write-row) ( row delimiter stream -- )
    [ '[ _ _ stream-write1 ] ] 2keep
    '[ _ _ escape-if-required ] interleave nl ; inline

PRIVATE>

: write-row ( row -- )
    delimiter> output-stream get (write-row) ; inline

<PRIVATE

: (write-csv) ( rows -- )
    delimiter> output-stream get '[ _ _ (write-row) ] each ;

PRIVATE>

: write-csv ( rows stream -- )
    [ (write-csv) ] with-output-stream ;

: csv>string ( csv -- string )
    [ (write-csv) ] with-string-writer ;

: csv>file ( rows path encoding -- )
    <file-writer> write-csv ;

        if-empty
    ] [ [ 2drop ] 2dip swap ?trim ] if ;

: (stream-read-row) ( delimiter stream field-end quoted-field -- delimiter sep/f fields )
    [ dup [ 2dup = ] ] 3dip '[ drop _ _ _ field ] produce ;

: (stream-read-csv) ( stream -- )
    delimiter get
    [ dup [ empty? ] all? [ drop ] [ , ] if ]
    rot pick field-delimiters
    '[ _ _ _ (stream-read-row) ] do while drop ;

PRIVATE>

: stream-read-row ( stream -- row )
    delimiter get swap over field-delimiters
    (stream-read-row) 2nip ; inline

: read-row ( -- row )
    input-stream get stream-read-row ; inline

: stream-read-csv ( stream -- rows )
    [ (stream-read-csv) ] { } make
    dup last { "" } = [ but-last ] when ; inline

: read-csv ( -- rows )
    input-stream get stream-read-csv ; inline

: string>csv ( string -- csv )
    [ read-csv ] with-string-reader ;

: file>csv ( path encoding -- csv )
    [ read-csv ] with-file-reader ;

: with-delimiter ( ch quot -- )
    [ delimiter ] dip with-variable ; inline
