-- functions for formatting spritesheet strings


local function wrapText(text, size, settings)
	local index = 1;
	local lines, words = {""}, getWords(text, true);
	local lineWidth, maxWidth = 0, abs(settings.child.AbsoluteSize.x);
	for i = 1, #words do
		local word = words[i];
		if (word ~= "\n") then
			local width = getStringWidth(word, settings.styles[settings.style][size]);
			if (width + lineWidth <= maxWidth) then
				lines[index] = lines[index] .. word;
			else
				lineWidth = 0;
				index = index + 1;
				lines[index] = word;
			end;
			lineWidth = lineWidth + width;
		else
			lineWidth = 0;
			index = index + 1;
			lines[index] = "";
		end;
	end;
	return lines;
end;

function scaleText(text, settings)
	local child = settings.child;
	local attached = settings.attached;

	sort(settings.information.sizes, function(a, b) return a > b; end);
	local bestSize = settings.information.sizes[1];
	local broke = false;
	
	for i = 1, #settings.information.sizes do
		local size = settings.information.sizes[i];
		local sizeSet = settings.styles[settings.style][size];
		local lines = child.TextWrapped and wrapText(text, size, settings) or getLines(text);
	
		local widths = {};
		local height = -sizeSet.firstAdjust;
		for j = 1, #lines do
			local line = lines[j];
			height = height + getMaxHeight(line, sizeSet)
			insert(widths, getStringWidth(line, sizeSet));
		end;
		
		local width = max(unpack(widths));
		if (width <= abs(child.AbsoluteSize.x) and height <= abs(child.AbsoluteSize.y)) then
			bestSize = size;
			broke = true;
			break;
		end;
	end;
	
	return broke and bestSize or settings.information.sizes[#settings.information.sizes];
end;
