// printing of (lists of) strings

#include "stdafx.h"

/* print a Pascal-type string (prefixed with the length, no NULL terminator) */
char *XMIInspect::printlstring(unsigned char *&curptr, bool sign, int curlevel)
{
	char isneg;
	int len;

	/* read length and (if needed) the sign flag */
	if (sign) {
		len = Load::SInt32(curptr, &isneg);
		if (isneg && level >= curlevel) {
			printf("(sign flag on) ");
		}
	} else {
		len = Load::UInt32(curptr);
	}
	/* allocate mem, copy the string and NULL-term it */
	unsigned char *buffer = new unsigned char[len+1];
	memcpy(buffer, curptr, len);
	buffer[len] = '\0';

	/* print */
	if (level >= curlevel) {
		printf("%s", buffer);
	}

	/* advance pointer */
	curptr += len;

	return (char*)buffer;
}

/* print a list of lstrings */
void XMIInspect::printslist(unsigned char *&curptr, bool sign, char ***array, int *numstrings, bool extendlist)
{
	char *ptr = NULL;
	char **bla = NULL;
	int offset = 0;

	/* read list length */
	int len = Load::UInt32(curptr);
	if (level >= XMIINS_REPORT_MOREINFO) {
		printf(" %ld strings\n", len);
	}

	if (array && numstrings) {
		if (!extendlist) {
			/* drop the existing list */
			for (int i=0; i<*numstrings; i++) {
				trydela((*array)[i]);
			}
			trydela(*array);
			*array = new char*[len];
			*numstrings = len;
		} else {
			/* extend the list */
			bla = new char*[len + *numstrings];
			for (int i=0; i<*numstrings; i++) {
				bla[i] = (*array)[i];
			}
			trydela (*array);
			*array = bla;
			offset = *numstrings;
			*numstrings += len;
		}
	}
	for (int i=0; i<len; i++) {
		/* print string */
		if (level >= XMIINS_REPORT_CONTENTS) {
			printf(" string %ld/%ld: '", i+1, len);
		}
		ptr = printlstring(curptr, sign);
		if (array && *array) {
			(*array)[i+offset] = ptr;
		} else {
			delete[] ptr;
		}
		if (level >= XMIINS_REPORT_CONTENTS) {
			printf("'\n");
		}
	}
}

