#import  "JpegSavePanel.h"
#import  <appkit/Application.h>
#import  <appkit/Control.h>
#import  <appkit/Button.h>
#import  <appkit/Matrix.h>
#import  <appkit/tiff.h>


@implementation JpegSavePanel

static BOOL prev = NO;

#define  SqDelta	0.001

static float sqroot(float x) // sqrt() ; low precision
{
	float s, old;

	if (x <= SqDelta)
		return 0.0;
	s = (x > 1.0) ? x : 1.0;
	do {
		old = s;
		s = (x / s + s) / 2.0;
	} while (old - s > SqDelta);
	return old;
}


- initFactor:(float)factor
{
	[self loadNib];
	if (factor > 255.0) factor = 255.0;
	else if (factor < 0.0) factor = 0.0;
	[JPEGtext setIntValue: (int)factor];
	[JPEGslider setFloatValue: sqroot(factor)];
	return self;
}

- loadNib
{
	if (accessoryView == nil) {
		[NXApp loadNibSection:"JpegAccessory.nib" owner:self];
		[self setAccessoryView: [accessory contentView]];
	}
	[progrSW setState: prev];
	return self;
}


- (float)compressFactor
{
	return (float)[JPEGtext intValue];
}


- (BOOL)progressive
{
	return (prev = [progrSW state]);
}

- takeFloatValueFrom: sender
{
	/* 0 -  6 (0 -  36)   step 1
	 *   - 10 (  - 100)   step 2
	 *   - 16 (  - 255)   step 5
	 */
	int n;
	float r = [sender floatValue];
	if (r <= 6.0) n = (int)(r * r);
	else if (r <= 10.0) n = (int)(r * r) & ~1;
	else {
		n = (int)(r * r) / 5 * 5;
		if (n > 255) n = 255;
	}
	[JPEGtext setIntValue: n];
	return self;
}

@end
