gdouble pfactor, xfactor, yfactor, factor; 

/* adjust the initial scale -- so that window fits on screen */
/* the 75% value is the same as in gdisplay_shrink_wrap. It  */
/* probably should be a user-configurable option.            */
s_width = gdk_screen_width () * 0.75;
s_height = gdk_screen_height () * 0.75; 

scalesrc = SCALESRC (gdisp);
scaledest = SCALEDEST (gdisp); 

n_width = SCALEX (gdisp, width);
n_height = SCALEX (gdisp, height); 

/* Limit to the size of the screen... */
if (n_width > s_width || n_height > s_height)
{
	pfactor = (gdouble) scaledest / scalesrc;
	xfactor = s_width * pfactor / n_width;        /* largest x axis scale to fit     */
	yfactor = s_height * pfactor / n_height;      /* largest y axis scale to fit     */
	factor = min(xfactor, yfactor);               /* use smaller of the two          */ 

	if (factor < (gdouble) 1 / 16)                /* but don't exceed 16X reduction  */
	{
		factor = max(xfactor, yfactor);         /* use larger of x or y axis limit */
		factor = max(factor, (gdouble) 1 / 16); /* or 16X if that is larger        */
		factor = min(factor, pfactor);          /* but don't exceed prior scale    */
	} 

	factor = max(factor, pfactor / n_width );     /* at least 1 pixel wide */
	factor = max(factor, pfactor / n_height);     /* at least 1 pixel high */ 

	if (factor > 1) {scaledest = factor; scalesrc = 1;}
	else {scaledest = 1; scalesrc = (1 / factor) % 1 ? (1 / factor) + 1 : 1 / factor;}

	n_width = width * 
		(scaledest * SCREEN_XRES (gdisp)) / (scalesrc * gdisp->gimage->xresolution);
	n_height = height *
		(scaledest * SCREEN_XRES (gdisp)) / (scalesrc * gdisp->gimage->xresolution); 
} 

gdisp->scale = (scaledest << 8) + scalesrc; 

