#import "Underlay.h"
#import "Underlay_Helper.h"
#import "aGroup-inter.h"
#import "TessSketch.h"

BOOL freeImageIfNecc(id img);

@implementation Underlay
+ new
{
  self = [super new];
  image = nil;
  return self;
}

- getImage
{
  return image;
}

- printPSCode: sender
{
  group = [sender currentGroup];
  return [super printPSCode: sender];
}
-endPage
{
  PSgrestore();
  PSgsave();
  print_name([group name]);
  PSgrestore();
  PSshowpage();
  [self unlockFocus];
  return self;
}

- drawSelf:(const NXRect *)rects :(int)rectCount
{
  if(image)
    [image composite: NX_COPY toPoint: &(bounds.origin)];
  return self;
}
- setImageFromFile: (const char *) fn			// use for loading TIFF
{
  freeImageIfNecc(image);
  image = [NXImage new];
  [image initFromFile: fn];
  return self;
}

- setImage: (id) anNXImage
{
  freeImageIfNecc(image);
  image = anNXImage;
  return self;
}

- setImageMaker: (id) drawobj			// use for setting image from section
{
  NXRect superframe;

  freeImageIfNecc(image);
  image = [NXImage alloc];
  [image init];
  [image useDrawMethod: @selector(drawImage) inObject: drawobj ];
  [superview getFrame: &superframe];
  [image setSize: &(superframe.size)];
  return self;
}
@end

BOOL freeImageIfNecc(id image)
{
  if(image != nil){
    [image free];
    image = nil;
#ifdef DEBUG
    fprintf(stderr,"Freeing image in underlay\n");
#endif
    return YES;
  } else
    return NO;
}
  

