⍝
⍝ Author:      Dr. Jürgen Sauermann
⍝ Date:        2022-10-13
⍝ Copyright:   Copyright (C) 2022 by Dr. Jürgen Sauermann
⍝ License:     GPL see http://www.gnu.org/licenses/gpl-3.0.en.html
⍝ Support email: bug-apl@gnu.org
⍝ Portability:   L3 (GNU APL)
⍝
⍝ Purpose:
⍝ Conversion of CSV (Comma Separated Values) file to APL values
⍝
⍝ Description:
⍝ This library provides 2 functions Util_JSA∆READ and Util_JSA∆WRITE
⍝ that read 2-dimensional CSV files into APL matrices (and vice versa).

 ⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝
⍝                                                                    ⍝
⍝ UTIL_JSA                             2022-10-13  19:26:03 (GMT+2)  ⍝
⍝                                                                    ⍝
 ⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝

∇Z←Util_JSA∆LINE2NUM B;P
 ⍝
 ⍝⍝ Return the numeric APL vector for string B (in CSV format).
 ⍝
 B←(B≠' ')/B                    ⍝ remove any blanks
 B←B←((','≠↑B)⍴','),B           ⍝ prepend a leading comma (if needed)
 B←(-','=¯1↑B)↓B                ⍝ discard a trailing comma (if any)
 P←(+\B=',')⊂B                  ⍝ partition B at comma boundaries
 Z←,⊃{⊃',%f' ⎕FIO.sscanf ⍵}¨P   ⍝ sscanf all items of P
∇

∇Z←Util_JSA∆NUM_SCAN B
 ⍝
 ⍝⍝ Return the numeric APL scalar for string B (in C/C++ format).
 ⍝
 Z←'%f' ⎕FIO.sscanf B
∇

∇MATRIX←Util_JSA∆READ_CSV FILENAME
 ⍝
 ⍝⍝ Convert file FILENAME, which should contain a numeric matrix
 ⍝⍝ encoded in CSV (aka. Comma Separated Values) format, to an APL matrix
 ⍝
 ⍝ In the CSV matrix B: rows are lines, columns are separated by ASCII commas,
 ⍝ and negative values and exponents use ASCII - instead of ¯.
 ⍝
 MATRIX ← ⊃Util_JSA∆LINE2NUM ⎕FIO.read_text FILENAME   ⍝ read FILENAME, covert its lines
∇

∇LEN←FILENAME Util_JSA∆WRITE_CSV MATRIX
 ⍝
 ⍝⍝ write the numeric MATRIX to a CSV text file FILENAME
 ⍝
 MATRIX←⍕MATRIX ◊ ((∧⌿' '=MATRIX)/MATRIX)←','
 MATRIX←⊂[⎕IO+1]MATRIX
 LEN←MATRIX ⎕FIO.write_text FILENAME
∇

⍝ EOF