/*
 *                            COPYRIGHT
 *
 *  cschem - modular/flexible schematics editor - libcschem (altium format support)
 *  Copyright (C) 2023 Tibor 'Igor2' Palinkas
 *
 *  (Supported by NLnet NGI0 Entrust in 2023)
 *
 *  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 2 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, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 *  Contact:
 *    Project page: http://repo.hu/projects/sch-rnd
 *    contact lead developer: http://www.repo.hu/projects/sch-rnd/contact.html
 *    mailing list: http://www.repo.hu/projects/sch-rnd/contact.html
 */

/* Extract lines from an almost-ascii-doc extracted from a cdf; the file
   contains of lines, each starting with a 4 byte long binary length field
   followed by a nul-terminated string */

#include <stdio.h>

#include "binlen2txt.h"

int binlen2txt_readline(vts0_t *dst, int (*read_cb)(void *ctx, void *dst, long len), void *ctx)
{
	unsigned long len;
	unsigned char raw_len[4];

	if (read_cb(ctx, raw_len, 4) != 0)
		return -1;

	/* length is 4 bytes LSB */
	len = ((unsigned long)raw_len[3]) << 24 | ((unsigned long)raw_len[2]) << 16 | ((unsigned long)raw_len[1]) << 8 | ((unsigned long)raw_len[0]);

	dst->used = 0;
	vts0_enlarge(dst, len);
	if (dst->alloced < len)
		return -1;

	if (read_cb(ctx, dst->array, len) != 0)
		return -1;

	dst->array[len] = '\0';

	return 0;
}



#ifndef BINLEN_NO_MAIN

static int read_cb(void *ctx, void *dst, long len)
{
	if (fread(dst, len, 1, (FILE *)ctx) == 1)
		return 0;
	return -1;
}

int main(int argc, char *argv[])
{
	vts0_t lin = {0};
	FILE *f;

	if (argc > 1) {
		f = fopen(argv[1], "r");
		if (f == NULL) {
			fprintf(stderr, "Error: failed to open '%s' for read\n", argv[1]);
			return 1;
		}
	}
	else
		f = stdin;

	while(binlen2txt_readline(&lin, read_cb, f) == 0)
		printf("%s\n", lin.array);
	vts0_uninit(&lin);
}
#endif
