File: csv.c

package info (click to toggle)
libsigrok 0.3.0-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 4,220 kB
  • ctags: 4,609
  • sloc: ansic: 40,159; sh: 11,626; makefile: 324
file content (868 lines) | stat: -rw-r--r-- 21,013 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
/*
 * This file is part of the libsigrok project.
 *
 * Copyright (C) 2013 Marc Schink <sigrok-dev@marcschink.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include "libsigrok.h"
#include "libsigrok-internal.h"

#define LOG_PREFIX "input/csv"

/*
 * The CSV input module has the following options:
 *
 * single-column: Specifies the column number which stores the sample data for
 *                single column mode and enables single column mode. Multi
 *                column mode is used if this parameter is omitted.
 *
 * numchannels:   Specifies the number of channels to use. In multi column mode
 *                the number of channels are the number of columns and in single
 *                column mode the number of bits (LSB first) beginning at
 *                'first-channel'.
 *
 * delimiter:     Specifies the delimiter for columns. Must be at least one
 *                character. Comma is used as default delimiter.
 *
 * format:        Specifies the format of the sample data in single column mode.
 *                Available formats are: 'bin', 'hex' and 'oct'. The binary
 *                format is used by default. This option has no effect in multi
 *                column mode.
 *
 * comment:       Specifies the prefix character(s) for comments. No prefix
 *                characters are used by default which disables removing of
 *                comments.
 *
 * samplerate:    Samplerate which the sample data was captured with. Default
 *                value is 0.
 *
 * first-channel: Column number of the first channel in multi column mode and
 *                position of the bit for the first channel in single column mode.
 *                Default value is 0.
 *
 * header:        Determines if the first line should be treated as header
 *                and used for channel names in multi column mode. Empty header
 *                names will be replaced by the channel number. If enabled in
 *                single column mode the first line will be skipped. Usage of
 *                header is disabled by default.
 *
 * startline:     Line number to start processing sample data. Must be greater
 *                than 0. The default line number to start processing is 1.
 */

/* Single column formats. */
enum {
	FORMAT_BIN,
	FORMAT_HEX,
	FORMAT_OCT
};

struct context {
	/* Current selected samplerate. */
	uint64_t samplerate;

	/* Number of channels. */
	gsize num_channels;

	/* Column delimiter character(s). */
	GString *delimiter;

	/* Comment prefix character(s). */
	GString *comment;

	/* Determines if sample data is stored in multiple columns. */
	gboolean multi_column_mode;

	/* Column number of the sample data in single column mode. */
	gsize single_column;

	/*
	 * Number of the first column to parse. Equivalent to the number of the
	 * first channel in multi column mode and the single column number in
	 * single column mode.
	 */
	gsize first_column;

	/*
	 * Column number of the first channel in multi column mode and position of
	 * the bit for the first channel in single column mode.
	 */
	gsize first_channel;

	/* Line number to start processing. */
	gsize start_line;

	/*
	 * Determines if the first line should be treated as header and used for
	 * channel names in multi column mode.
	 */
	gboolean header;

	/* Format sample data is stored in single column mode. */
	int format;

	/* Size of the sample buffer. */
	gsize sample_buffer_size;

	/* Buffer to store sample data. */
	uint8_t *sample_buffer;

	GIOChannel *channel;

	/* Buffer for the current line. */
	GString *buffer;

	/* Current line number. */
	gsize line_number;
};

static int format_match(const char *filename)
{
	if (!filename) {
		sr_err("%s: filename was NULL.", __func__);
		return FALSE;
	}

	if (!g_file_test(filename, G_FILE_TEST_EXISTS)) {
		sr_err("Input file '%s' does not exist.", filename);
		return FALSE;
	}

	if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR)) {
		sr_err("Input file '%s' not a regular file.", filename);
		return FALSE;
	}

	return TRUE;
}

static void free_context(struct context *ctx)
{
	if (!ctx)
		return;

	if (ctx->delimiter)
		g_string_free(ctx->delimiter, TRUE);

	if (ctx->comment)
		g_string_free(ctx->comment, TRUE);

	if (ctx->channel) {
		g_io_channel_shutdown(ctx->channel, FALSE, NULL);
		g_io_channel_unref(ctx->channel);
	}

	if (ctx->sample_buffer)
		g_free(ctx->sample_buffer);

	if (ctx->buffer)
		g_string_free(ctx->buffer, TRUE);

	g_free(ctx);
}

static void strip_comment(GString *string, const GString *prefix)
{
	char *ptr;

	if (!prefix->len)
		return;

	if (!(ptr = strstr(string->str, prefix->str)))
		return;

	g_string_truncate(string, ptr - string->str);
}

static int parse_binstr(const char *str, struct context *ctx)
{
	gsize i, j, length;

	length = strlen(str);

	if (!length) {
		sr_err("Column %zu in line %zu is empty.", ctx->single_column,
			ctx->line_number);
		return SR_ERR;
	}

	/* Clear buffer in order to set bits only. */
	memset(ctx->sample_buffer, 0, (ctx->num_channels + 7) >> 3);

	i = ctx->first_channel;

	for (j = 0; i < length && j < ctx->num_channels; i++, j++) {
		if (str[length - i - 1] == '1') {
			ctx->sample_buffer[j / 8] |= (1 << (j % 8));
		} else if (str[length - i - 1] != '0') {
			sr_err("Invalid value '%s' in column %zu in line %zu.",
				str, ctx->single_column, ctx->line_number);
			return SR_ERR;
		}
	}

	return SR_OK;
}

static int parse_hexstr(const char *str, struct context *ctx)
{
	gsize i, j, k, length;
	uint8_t value;
	char c;

	length = strlen(str);

	if (!length) {
		sr_err("Column %zu in line %zu is empty.", ctx->single_column,
			ctx->line_number);
		return SR_ERR;
	}

	/* Clear buffer in order to set bits only. */
	memset(ctx->sample_buffer, 0, (ctx->num_channels + 7) >> 3);

	/* Calculate the position of the first hexadecimal digit. */
	i = ctx->first_channel / 4;

	for (j = 0; i < length && j < ctx->num_channels; i++) {
		c = str[length - i - 1];

		if (!g_ascii_isxdigit(c)) {
			sr_err("Invalid value '%s' in column %zu in line %zu.",
				str, ctx->single_column, ctx->line_number);
			return SR_ERR;
		}

		value = g_ascii_xdigit_value(c);

		k = (ctx->first_channel + j) % 4;

		for (; j < ctx->num_channels && k < 4; k++) {
			if (value & (1 << k))
				ctx->sample_buffer[j / 8] |= (1 << (j % 8));

			j++;
		}
	}

	return SR_OK;
}

static int parse_octstr(const char *str, struct context *ctx)
{
	gsize i, j, k, length;
	uint8_t value;
	char c;

	length = strlen(str);

	if (!length) {
		sr_err("Column %zu in line %zu is empty.", ctx->single_column,
			ctx->line_number);
		return SR_ERR;
	}

	/* Clear buffer in order to set bits only. */
	memset(ctx->sample_buffer, 0, (ctx->num_channels + 7) >> 3);

	/* Calculate the position of the first octal digit. */
	i = ctx->first_channel / 3;

	for (j = 0; i < length && j < ctx->num_channels; i++) {
		c = str[length - i - 1];

		if (c < '0' || c > '7') {
			sr_err("Invalid value '%s' in column %zu in line %zu.",
				str, ctx->single_column, ctx->line_number);
			return SR_ERR;
		}

		value = g_ascii_xdigit_value(c);

		k = (ctx->first_channel + j) % 3;

		for (; j < ctx->num_channels && k < 3; k++) {
			if (value & (1 << k))
				ctx->sample_buffer[j / 8] |= (1 << (j % 8));

			j++;
		}
	}

	return SR_OK;
}

static char **parse_line(const struct context *ctx, int max_columns)
{
	const char *str, *remainder;
	GSList *list, *l;
	char **columns;
	char *column;
	gsize n, k;

	n = 0;
	k = 0;
	list = NULL;

	remainder = ctx->buffer->str;
	str = strstr(remainder, ctx->delimiter->str);

	while (str && max_columns) {
		if (n >= ctx->first_column) {
			column = g_strndup(remainder, str - remainder);
			list = g_slist_prepend(list, g_strstrip(column));

			max_columns--;
			k++;
		}

		remainder = str + ctx->delimiter->len;
		str = strstr(remainder, ctx->delimiter->str);
		n++;
	}

	if (ctx->buffer->len && max_columns && n >= ctx->first_column) {
		column = g_strdup(remainder);
		list = g_slist_prepend(list, g_strstrip(column));
		k++;
	}

	if (!(columns = g_try_new(char *, k + 1)))
		return NULL;

	columns[k--] = NULL;

	for (l = list; l; l = l->next)
		columns[k--] = l->data;

	g_slist_free(list);

	return columns;
}

static int parse_multi_columns(char **columns, struct context *ctx)
{
	gsize i;

	/* Clear buffer in order to set bits only. */
	memset(ctx->sample_buffer, 0, (ctx->num_channels + 7) >> 3);

	for (i = 0; i < ctx->num_channels; i++) {
		if (columns[i][0] == '1') {
			ctx->sample_buffer[i / 8] |= (1 << (i % 8));
		} else if (!strlen(columns[i])) {
			sr_err("Column %zu in line %zu is empty.",
				ctx->first_channel + i, ctx->line_number);
			return SR_ERR;
		} else if (columns[i][0] != '0') {
			sr_err("Invalid value '%s' in column %zu in line %zu.",
				columns[i], ctx->first_channel + i,
				ctx->line_number);
			return SR_ERR;
		}
	}

	return SR_OK;
}

static int parse_single_column(const char *column, struct context *ctx)
{
	int res;

	res = SR_ERR;

	switch(ctx->format) {
	case FORMAT_BIN:
		res = parse_binstr(column, ctx);
		break;
	case FORMAT_HEX:
		res = parse_hexstr(column, ctx);
		break;
	case FORMAT_OCT:
		res = parse_octstr(column, ctx);
		break;
	}

	return res;
}

static int send_samples(const struct sr_dev_inst *sdi, uint8_t *buffer,
			gsize buffer_size, gsize count)
{
	int res;
	struct sr_datafeed_packet packet;
	struct sr_datafeed_logic logic;
	gsize i;

	packet.type = SR_DF_LOGIC;
	packet.payload = &logic;
	logic.unitsize = buffer_size;
	logic.length = buffer_size;
	logic.data = buffer;

	for (i = 0; i < count; i++) {
		if ((res = sr_session_send(sdi, &packet)) != SR_OK)
			return res;
	}

	return SR_OK;
}

static int init(struct sr_input *in, const char *filename)
{
	int res;
	struct context *ctx;
	const char *param;
	GIOStatus status;
	gsize i, term_pos;
	char channel_name[SR_MAX_CHANNELNAME_LEN + 1];
	struct sr_channel *ch;
	char **columns;
	gsize num_columns;
	char *ptr;

	if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
		sr_err("Context malloc failed.");
		return SR_ERR_MALLOC;
	}

	/* Create a virtual device. */
	in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
	in->internal = ctx;

	/* Set default samplerate. */
	ctx->samplerate = 0;

	/*
	 * Enable auto-detection of the number of channels in multi column mode
	 * and enforce the specification of the number of channels in single
	 * column mode.
	 */
	ctx->num_channels = 0;

	/* Set default delimiter. */
	if (!(ctx->delimiter = g_string_new(","))) {
		sr_err("Delimiter malloc failed.");
		free_context(ctx);
		return SR_ERR_MALLOC;
	}

	/*
	 * Set default comment prefix. Note that an empty comment prefix
	 * disables removing of comments.
	 */
	if (!(ctx->comment = g_string_new(""))) {
		sr_err("Comment malloc failed.");
		free_context(ctx);
		return SR_ERR_MALLOC;
	}

	/* Enable multi column mode by default. */
	ctx->multi_column_mode = TRUE;

	/* Use first column as default single column number. */
	ctx->single_column = 0;

	/*
	 * In multi column mode start parsing sample data at the first column
	 * and in single column mode at the first bit.
	 */
	ctx->first_channel = 0;

	/* Start at the beginning of the file. */
	ctx->start_line = 1;

	/* Disable the usage of the first line as header by default. */
	ctx->header = FALSE;

	/* Set default format for single column mode. */
	ctx->format = FORMAT_BIN;

	if (!(ctx->buffer = g_string_new(""))) {
		sr_err("Line buffer malloc failed.");
		free_context(ctx);
		return SR_ERR_MALLOC;
	}

	if (in->param) {
		if ((param = g_hash_table_lookup(in->param, "samplerate"))) {
			res = sr_parse_sizestring(param, &ctx->samplerate);

			if (res != SR_OK) {
				sr_err("Invalid samplerate: %s.", param);
				free_context(ctx);
				return SR_ERR_ARG;
			}
		}

		if ((param = g_hash_table_lookup(in->param, "numchannels")))
			ctx->num_channels = g_ascii_strtoull(param, NULL, 10);

		if ((param = g_hash_table_lookup(in->param, "delimiter"))) {
			if (!strlen(param)) {
				sr_err("Delimiter must be at least one character.");
				free_context(ctx);
				return SR_ERR_ARG;
			}

			if (!g_ascii_strcasecmp(param, "\\t"))
				g_string_assign(ctx->delimiter, "\t");
			else
				g_string_assign(ctx->delimiter, param);
		}

		if ((param = g_hash_table_lookup(in->param, "comment")))
			g_string_assign(ctx->comment, param);

		if ((param = g_hash_table_lookup(in->param, "single-column"))) {
			ctx->single_column = g_ascii_strtoull(param, &ptr, 10);
			ctx->multi_column_mode = FALSE;

			if (param == ptr) {
				sr_err("Invalid single-colum number: %s.",
					param);
				free_context(ctx);
				return SR_ERR_ARG;
			}
		}

		if ((param = g_hash_table_lookup(in->param, "first-channel")))
			ctx->first_channel = g_ascii_strtoull(param, NULL, 10);

		if ((param = g_hash_table_lookup(in->param, "startline"))) {
			ctx->start_line = g_ascii_strtoull(param, NULL, 10);

			if (ctx->start_line < 1) {
				sr_err("Invalid start line: %s.", param);
				free_context(ctx);
				return SR_ERR_ARG;
			}
		}

		if ((param = g_hash_table_lookup(in->param, "header")))
			ctx->header = sr_parse_boolstring(param);

		if ((param = g_hash_table_lookup(in->param, "format"))) {
			if (!g_ascii_strncasecmp(param, "bin", 3)) {
				ctx->format = FORMAT_BIN;
			} else if (!g_ascii_strncasecmp(param, "hex", 3)) {
				ctx->format = FORMAT_HEX;
			} else if (!g_ascii_strncasecmp(param, "oct", 3)) {
				ctx->format = FORMAT_OCT;
			} else {
				sr_err("Invalid format: %s.", param);
				free_context(ctx);
				return SR_ERR;
			}
		}
	}

	if (ctx->multi_column_mode)
		ctx->first_column = ctx->first_channel;
	else
		ctx->first_column = ctx->single_column;

	if (!ctx->multi_column_mode && !ctx->num_channels) {
		sr_err("Number of channels needs to be specified in single column mode.");
		free_context(ctx);
		return SR_ERR;
	}

	if (!(ctx->channel = g_io_channel_new_file(filename, "r", NULL))) {
		sr_err("Input file '%s' could not be opened.", filename);
		free_context(ctx);
		return SR_ERR;
	}

	while (TRUE) {
		ctx->line_number++;
		status = g_io_channel_read_line_string(ctx->channel,
			ctx->buffer, &term_pos, NULL);

		if (status == G_IO_STATUS_EOF) {
			sr_err("Input file is empty.");
			free_context(ctx);
			return SR_ERR;
		}

		if (status != G_IO_STATUS_NORMAL) {
			sr_err("Error while reading line %zu.",
				ctx->line_number);
			free_context(ctx);
			return SR_ERR;
		}

		if (ctx->start_line > ctx->line_number) {
			sr_spew("Line %zu skipped.", ctx->line_number);
			continue;
		}

		/* Remove line termination character(s). */
		g_string_truncate(ctx->buffer, term_pos);

		if (!ctx->buffer->len) {
			sr_spew("Blank line %zu skipped.", ctx->line_number);
			continue;
		}

		/* Remove trailing comment. */
		strip_comment(ctx->buffer, ctx->comment);

		if (ctx->buffer->len)
			break;

		sr_spew("Comment-only line %zu skipped.", ctx->line_number);
	}

	/*
	 * In order to determine the number of columns parse the current line
	 * without limiting the number of columns.
	 */
	if (!(columns = parse_line(ctx, -1))) {
		sr_err("Error while parsing line %zu.", ctx->line_number);
		free_context(ctx);
		return SR_ERR;
	}

	num_columns = g_strv_length(columns);

	/* Ensure that the first column is not out of bounds. */
	if (!num_columns) {
		sr_err("Column %zu in line %zu is out of bounds.",
			ctx->first_column, ctx->line_number);
		g_strfreev(columns);
		free_context(ctx);
		return SR_ERR;
	}

	if (ctx->multi_column_mode) {
		/*
		 * Detect the number of channels in multi column mode
		 * automatically if not specified.
		 */
		if (!ctx->num_channels) {
			ctx->num_channels = num_columns;
			sr_info("Number of auto-detected channels: %zu.",
				ctx->num_channels);
		}

		/*
		 * Ensure that the number of channels does not exceed the number
		 * of columns in multi column mode.
		 */
		if (num_columns < ctx->num_channels) {
			sr_err("Not enough columns for desired number of channels in line %zu.",
				ctx->line_number);
			g_strfreev(columns);
			free_context(ctx);
			return SR_ERR;
		}
	}

	for (i = 0; i < ctx->num_channels; i++) {
		if (ctx->header && ctx->multi_column_mode && strlen(columns[i]))
			snprintf(channel_name, sizeof(channel_name), "%s",
				columns[i]);
		else
			snprintf(channel_name, sizeof(channel_name), "%zu", i);

		ch = sr_channel_new(i, SR_CHANNEL_LOGIC, TRUE, channel_name);

		if (!ch) {
			sr_err("Channel creation failed.");
			free_context(ctx);
			g_strfreev(columns);
			return SR_ERR;
		}

		in->sdi->channels = g_slist_append(in->sdi->channels, ch);
	}

	g_strfreev(columns);

	/*
	 * Calculate the minimum buffer size to store the sample data of the
	 * channels.
	 */
	ctx->sample_buffer_size = (ctx->num_channels + 7) >> 3;

	if (!(ctx->sample_buffer = g_try_malloc(ctx->sample_buffer_size))) {
		sr_err("Sample buffer malloc failed.");
		free_context(ctx);
		return SR_ERR_MALLOC;
	}

	return SR_OK;
}

static int loadfile(struct sr_input *in, const char *filename)
{
	int res;
	struct context *ctx;
	struct sr_datafeed_packet packet;
	struct sr_datafeed_meta meta;
	struct sr_config *cfg;
	GIOStatus status;
	gboolean read_new_line;
	gsize term_pos;
	char **columns;
	gsize num_columns;
	int max_columns;

	(void)filename;

	ctx = in->internal;

	/* Send header packet to the session bus. */
	std_session_send_df_header(in->sdi, LOG_PREFIX);

	if (ctx->samplerate) {
		packet.type = SR_DF_META;
		packet.payload = &meta;
		cfg = sr_config_new(SR_CONF_SAMPLERATE,
			g_variant_new_uint64(ctx->samplerate));
		meta.config = g_slist_append(NULL, cfg);
		sr_session_send(in->sdi, &packet);
		sr_config_free(cfg);
	}

	read_new_line = FALSE;

	/* Limit the number of columns to parse. */
	if (ctx->multi_column_mode)
		max_columns = ctx->num_channels;
	else
		max_columns = 1;

	while (TRUE) {
		/*
		 * Skip reading a new line for the first time if the last read
		 * line was not a header because the sample data is not parsed
		 * yet.
		 */
		if (read_new_line || ctx->header) {
			ctx->line_number++;
			status = g_io_channel_read_line_string(ctx->channel,
				ctx->buffer, &term_pos, NULL);

			if (status == G_IO_STATUS_EOF)
				break;

			if (status != G_IO_STATUS_NORMAL) {
				sr_err("Error while reading line %zu.",
					ctx->line_number);
				free_context(ctx);
				return SR_ERR;
			}

			/* Remove line termination character(s). */
			g_string_truncate(ctx->buffer, term_pos);
		}

		read_new_line = TRUE;

		if (!ctx->buffer->len) {
			sr_spew("Blank line %zu skipped.", ctx->line_number);
			continue;
		}

		/* Remove trailing comment. */
		strip_comment(ctx->buffer, ctx->comment);

		if (!ctx->buffer->len) {
			sr_spew("Comment-only line %zu skipped.",
				ctx->line_number);
			continue;
		}

		if (!(columns = parse_line(ctx, max_columns))) {
			sr_err("Error while parsing line %zu.",
				ctx->line_number);
			free_context(ctx);
			return SR_ERR;
		}

		num_columns = g_strv_length(columns);

		/* Ensure that the first column is not out of bounds. */
		if (!num_columns) {
			sr_err("Column %zu in line %zu is out of bounds.",
				ctx->first_column, ctx->line_number);
			g_strfreev(columns);
			free_context(ctx);
			return SR_ERR;
		}

		/*
		 * Ensure that the number of channels does not exceed the number
		 * of columns in multi column mode.
		 */
		if (ctx->multi_column_mode && num_columns < ctx->num_channels) {
			sr_err("Not enough columns for desired number of channels in line %zu.",
				ctx->line_number);
			g_strfreev(columns);
			free_context(ctx);
			return SR_ERR;
		}

		if (ctx->multi_column_mode)
			res = parse_multi_columns(columns, ctx);
		else
			res = parse_single_column(columns[0], ctx);

		if (res != SR_OK) {
			g_strfreev(columns);
			free_context(ctx);
			return SR_ERR;
		}

		g_strfreev(columns);

		/*
		 * TODO: Parse sample numbers / timestamps and use it for
		 * decompression.
		 */

		/* Send sample data to the session bus. */
		res = send_samples(in->sdi, ctx->sample_buffer,
			ctx->sample_buffer_size, 1);

		if (res != SR_OK) {
			sr_err("Sending samples failed.");
			free_context(ctx);
			return SR_ERR;
		}
	}

	/* Send end packet to the session bus. */
	packet.type = SR_DF_END;
	sr_session_send(in->sdi, &packet);

	free_context(ctx);

	return SR_OK;
}

SR_PRIV struct sr_input_format input_csv = {
	.id = "csv",
	.description = "Comma-separated values (CSV)",
	.format_match = format_match,
	.init = init,
	.loadfile = loadfile,
};