/*  GadTools layout toolkit
**
**  Copyright © 1993-1994 by Olaf `Olsen' Barthel
**  Freely distributable.
*/

#include "gtlayout_global.h"

BOOLEAN __regargs
LTP_Rescale(LayoutHandle *handle,BOOLEAN trimWidth,BOOLEAN trimHeight)
{
	STATIC struct TextAttr topazAttr =
	{
		"topaz.font",
		8,
		FS_NORMAL,
		FPF_ROMFONT | FPF_DESIGNED
	};

	LONG	oldWidth;
	LONG	oldHeight;
	UBYTE	glyph;
	LONG	glyphWidth;
	LONG	count;
	LONG	i;
	LONG	total;
	BOOLEAN found;

	oldWidth	= handle -> GlyphWidth;
	oldHeight	= handle -> RPort . TxHeight;

	if(handle -> CloseFont)
	{
		CloseFont(handle -> RPort . Font);

		handle -> CloseFont = FALSE;
	}

	/* GfxBase -> DefaultFont is guaranteed not to ever be removed from
	 * memory,so we use that fact...
	 */

	LTP_SetFont(handle,GfxBase -> DefaultFont);

	handle -> TextAttr			= &handle -> CopyTextAttr;
	handle -> CopyTextAttr . tta_Name	= handle -> RPort . Font -> tf_Message . mn_Node . ln_Name;
	handle -> CopyTextAttr . tta_YSize	= handle -> RPort . TxHeight;
	handle -> CopyTextAttr . tta_Style	= handle -> RPort . Font -> tf_Style;
	handle -> CopyTextAttr . tta_Flags	= handle -> RPort . TxFlags;

	if(handle -> RPort . Font -> tf_Style & FSF_TAGGED)
		handle -> CopyTextAttr . tta_Tags = ((struct TextFontExtension *)handle -> RPort . Font -> tf_Extension) -> tfe_Tags;

	FOREVER
	{
		count = 0;
		total = 0;

		for(i = 32 ; i < 127 ; i++)
		{
			glyph = i;
			total += TextLength(&handle -> RPort,&glyph,1);
			count++;
		}

		for(i = 160 ; i < 256 ; i++)
		{
			glyph = i;
			total += TextLength(&handle -> RPort,&glyph,1);
			count++;
		}

		glyphWidth = total / count;

		found = TRUE;

		if(trimWidth && (glyphWidth >= oldWidth))
			found = FALSE;

		if(trimHeight && (oldHeight >= handle -> RPort . TxHeight))
			found = FALSE;

		if(found)
		{
			handle -> GlyphWidth	= glyphWidth;
			handle -> Rescaled	= TRUE;

			if(glyphWidth <= 8)
				handle -> InterWidth = 4;
			else
				handle -> InterWidth = glyphWidth / 2;

			if(handle -> RPort . TxHeight <= 8)
				handle -> InterHeight = 2;
			else
				handle -> InterHeight = handle -> RPort . TxHeight / 4;

			LTP_ResetGroups(handle -> TopGroup);

			return(TRUE);
		}

		if(handle -> TextAttr == &topazAttr)
			return(FALSE);

		LTP_SetFont(handle,OpenFont(&topazAttr));

		handle -> TextAttr	= &topazAttr;
		handle -> CloseFont	= TRUE;
	}
}
