CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.

The CSV format is flexible but somewhat ill-defined.

For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.



Task

Read a CSV file, change some values and save the changes back to a file.

For this task we will use the following CSV file:

C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20

Suggestions


 Show how to add a column, headed 'SUM', of the sums of the rows.
 If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.



string  0;              \use zero-terminated strings
def     LF=$0A, EOF=$1A;
int     Val, Char;
char    Str(80);
 
proc    InField;
int     I;
[I:= 0;  Val:= 0;
loop    [Char:= ChIn(1);
        if Char=^, or Char=LF or Char=EOF then quit;
        Str(I):= Char;
        I:= I+1;
        if Char>=^0 and Char<=^9 then
                Val:= Val*10 + Char - ^0;
        ];
Str(I):= 0;
];
 
int     Sum;
[loop   [InField;
        Text(0, Str);
        if Char = LF then quit;
        ChOut(0, ^,);
        ];
Text(0, ",SUM");
CrLf(0);
loop    [Sum:= 0;
        loop    [InField;
                if Char = EOF then return;
                if rem(Val/5)=0 then Val:= Val*20;
                IntOut(0, Val);
                Sum:= Sum + Val;
                if Char = LF then quit;
                ChOut(0, ^,);
                ];
        Text(0, ",");
        IntOut(0, Sum);
        CrLf(0);
        ];
]