/* Parsing CSV data in PISC */
"Dicts.pisc" import

: parse-csv-core ( reader -- vec [ vec ] ) 
	:reader
	<vector> :results
	f :inString
	[ $inString not ] :outOfString

	/* Set up the temporary variables */
	[ "" :tempStr ] :resetCell
	[ resetCell <vector> :tempVec ] dup call :resetLine

	[ $tempVec $tempStr vec-append :tempVec resetCell ] :addCell
	[ $results $tempVec vec-append :results resetLine ] :addLine

	/* Debugging 
	"Temp Cell: " $tempStr concat print
	"Temp Vector: " $tempVec >string concat print
	*/

	[ $reader -$EOF call not nip ] :notEOF
	[ $reader -$read-rune call nip ] :readRune

	[ notEOF ] [ 
		readRune
		/* By default, append a char */
		t :default
		[ f :default ] :break

		dup "," str-eq outOfString and [ addCell break ] when
		dup "\n" str-eq outOfString and [ addCell addLine break ] when
		dup "\"" str-eq /* Toggle */ [ outOfString :inString break ] when
		$default [ $tempStr swap concat :tempStr ] [ drop ] if
	] while 
	/* Add the straggling items */
	addCell addLine 
	$results ; 

: csv-of-file ( filepath -- vec [ vec ] ) open-file-reader parse-csv-core ;
: csv-of-string ( string -- vec [ vec ] ) str>rune-reader parse-csv-core ;