## Copyright (C) 2021 Granite Devices Oy
##
## Author: Tero Kontkanen
##
## License: APACHE-2.0

## usage: ARRAY = read_granity_csv (FILENAME, COLUMNNAME)
##
## Reads scope capture csv file saved by Granity app. 
## Return array of values from column that begins with the given name.
##
## Example:
##
## t=read_granity_csv("my.csv", "Time")
##
## torq=read_granity_csv("my.csv", "Torque achieved")

function data=read_granity_csv( fn, colname )
    fid = fopen(fn,'r');
    if fid==-1
        error( "Can't open file");
    endif
    
    # read header line
    ln = fgetl(fid);
    cols=strsplit(ln,',');
    
    idx=-1;
    %find right colname, case insensitive and first chars of name will be enough
    for i=1:numel(cols)
        if strncmpi(colname,cols(1,i),numel(colname)) == 1
            idx=i;
        endif
    endfor
    if idx==-1
        error( "Given column not found");
    endif
    data=cols;
    
    # read csv data, take only one column
    data = csvread(fid)(:,idx);

    fclose(fid); 
endfunction
