function write_line_shapefile( data, headers, filename )
% write_points_shapefile( data, headers, filename )
% 
% Writes an Esri Shapefile for simple point data. It uses the commandline
% interface of SAGA GIS. SAGA needs to be installed, and its' path needs to
% be added to your OS path variable. It might be necessary to restart 
% Matlab after adding the path to the OS search path. SAGA can be obtained 
% for free from: http://www.saga-gis.org/
% 
% - data is a cell array, which' first column contains the X coordinates, the
% second column contains Y coordinates. Other columns can contain other
% variables. 
% - The headers variable is a cell array containing the names of the data
% columns.
% - The filename argument supplies the name of the file to write.
% 
% Example: 
% x = [1:10]'; y = [1:10]'; z = rand(10,1);
% write_points_shapefile( num2cell([x, y, z]), { 'X', 'Y', 'Z' }, 'filetowrite')
% 
% Yannick Kremer 2010


[rows, cols] = size(data);

% Create a temporary file 

% Create header line
headline = 'X\tY\t';
for idx = 3: cols,
    headline = [headline, headers{ idx }, '\t'];
end

% Write Header line to temporary file
fid = fopen([filename, '.tmp'], 'w');
fprintf( fid, [headline, '\n'] );

for rowid = 1 : rows,
    for colid = 1: cols -1,
        d = data{ rowid, colid};
        if isnumeric( d ), 
            d = sprintf( '%6f', d);
        end
        fprintf( fid, '%s\t', d );
    end
    % write last one without tab character
    d = data{ rowid, cols};
    if isnumeric( d ), 
        d = sprintf( '%6f', d);
    end
    fprintf( fid, '%s\r\n', d );
end
    
fclose(fid);

% Write actual data to file
% dlmwrite( [ filename, '.tmp'], data, '-append', 'delimiter', '\t', 'newline', 'pc', 'precision', '%f');


% Call SAGA commandline to convert text file to shapefile
system( ['saga_cmd shapes_points 0 -POINTS ', filename, '_ptstmp.shp -TABLE ', filename, '.tmp -X X -Y Y']);
system( ['saga_cmd shapes_lines 1 -LINES ', filename, '.shp -POINTS ', filename, '_ptstmp.shp -ORDER Y']);
