/* Stack.m created by ovidiu on Sat 22-Mar-1997 */

#import <Foundation/Foundation.h>
#import "GdbDisplayController.h"
#import "DebuggerController_Protocol.h"
#import "NSScannerAddition.h"
#import "Frame.h"
#import "Stack.h"

@implementation Stack

- init
{
  self = [super init];
  frames = [NSMutableArray new];
  selectedFrame = -1;
  return self;
}

- (void)dealloc
{
  [frames release];
  [super dealloc];
}

- (void)setGdbController:(GdbDisplayController*)object
{
  gdbController = object;
}

- (void)createStackFromGdbBacktrace:(NSString*)gdbOutput
                               type:(GdbOutputType)type
{
  NSScanner* scanner;

  /* Ignore other output types. */
  if (type != GDB_OUTPUT_ANNOTATION)
    return;

  scanner = [NSScanner scannerWithString:gdbOutput];

  [frames removeAllObjects];
  while (![scanner isAtEnd]) {
    NSString* functionAnnotation;
    Frame* frame;

    if (![scanner scanUpToString:@"\032\032frame-end\n"
                      intoString:&functionAnnotation])
      break;
    [scanner scanString:@"\032\032frame-end\n" intoString:NULL];

    frame = [Frame frameWithAnnotation:functionAnnotation stack:self];
    if (frame)
      [frames addObject:frame];
  }

  [gdbController stackChanged];
//  NSLog (@"%@ output = %@", NSStringFromSelector(_cmd), frames);
}

- (void)setSelectedFrame:(int)newFrame
{
  if (selectedFrame != newFrame) {
    id frameCmd = [NSString stringWithFormat:@"frame %d", newFrame];

    [[[self gdbController] gdbManager]
            executeCmd:frameCmd withTty:YES withAnnotation:NO];
    selectedFrame = newFrame;
  }
}

- (int)selectedFrame			{ return selectedFrame; }
- (NSArray*)frames			{ return frames; }
- (GdbDisplayController*)gdbController	{ return gdbController; }

@end
