//
//  MyDocument.m
//  TAMS Edit
//
//  Created by matthew on Thu Apr 18 2002.
//  Copyright (c) 2001 Matthew Weinstein. All rights reserved.
//
//#import "ctReadChar.h"
#ifdef MULTIMEDIA
#import "Carbon/Carbon.h"
#endif
#import "MyDocument.h"
#import "tams.h"
#import "tamsutils.h"
#import "myResults.h"
#import "myProject.h"
#import "prefBoss.h"
#import "bookmarkInfo.h"
#import "appDelegate.h"
#import "ctTagInfo.h"
#import "tableBrowser.h"
#import "TAMSCharEngine.h"
#import "stringCategories.h"
#import "MGWPopUpButton.h"
#import "MWRange.h"
#import "MWFakeFile.h"
#define NSTRIM(X) [X stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]
#import <string.h>
#define BOOKMARKBASE 3
#define DOCMACROBASE 6
#define NEWAPPLYCODE 1
#define USETIMER 0
 MyDocument *gCurrentDataSource;
 
 #define SETRAWCOLOR(X) [theDoc setTextColor: X range: [theDoc selectedRange]];
 #define SETCOLOR(X) [theDoc setTextColor: [gWorkBench colorForCode: X] range: [theDoc selectedRange]];
 #define SETBASECOLOR [theDoc setTextColor: getColorForInt([gPrefBoss tagColorValue]) range:  [theDoc selectedRange]];

@implementation MyDocument


-(id) init
{
#ifdef MULTIMEDIA
#ifdef USETIMER
    myTimer = nil;
#endif
#endif
    rawF = 1;
    emptyF = exactF = 0;
    regexCharF = nonRegexCharF = 0;
    [super init];
    myDocType = DATATYPE;
    dataFromFile = nil;
    myMovie = nil;
    myData = nil;
    savedFormat = nil;
    macroArray = [[NSMutableArray alloc] init];
//    hotCodeList = [[NSMutableArray alloc] init];
    bookmarkVault = [[NSMutableArray alloc] init];
    codeInfoStr = [[NSMutableString alloc] init];
//    [hotCodeList retain];
    return self;
}

-(void) dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver: self];
    [dataFromFile release];
    [macroArray release];
#ifdef MULTIMEDIA
#ifdef USETIMER
    if(myTimer != nil)
    {
        [myTimer invalidate];
        [myTimer release];
    }
#endif
#endif
    
    [hotCodeList dealloc];
    if(savedFormat) [savedFormat release];
    if(myMovie != nil) {[myMovie release];}
    [super dealloc];
}
-(myProject *) getGWorkBench { return gWorkBench;}

-(NSColor *) getColor: (int) col
{
    switch(col)
    {
	case red:
	    return  [NSColor redColor];
	    break;
	case yellow:
	    return [NSColor yellowColor];
	    break;
	case green:
	    return [NSColor greenColor] ;
	    break;
	case blue:
	    return [NSColor blueColor] ;
	    break;
	case ltgray:
	    return [NSColor lightGrayColor] ;
	    break;
	case gray:
	    return [NSColor grayColor] ;
	    break;
	case dkgray:
	    return [NSColor darkGrayColor];
	    break;
        case black:
             return [NSColor blackColor];
             break;
	default: ;
    }
}
-(void) newColorOn: (NSColor *) what
{
    [theDoc setTextColor: what range: [theDoc selectedRange]];

}
-(void) colorOn: (int) col
{
    switch(col)
    {
	case red:
	    [theDoc setTextColor: [NSColor redColor] range: [theDoc selectedRange]];
	    break;
	case yellow:
	    [theDoc setTextColor: [NSColor yellowColor] range: [theDoc selectedRange]];
	    break;
	case green:
	    [theDoc setTextColor: [NSColor greenColor] range: [theDoc selectedRange]];
	    break;
	case blue:
	    [theDoc setTextColor: [NSColor blueColor] range: [theDoc selectedRange]];
	    break;
	case ltgray:
	    [theDoc setTextColor: [NSColor lightGrayColor] range: [theDoc selectedRange]];
	    break;
	case gray:
	    [theDoc setTextColor: [NSColor grayColor] range: [theDoc selectedRange]];
	    break;
	case dkgray:
	    [theDoc setTextColor: [NSColor darkGrayColor] range: [theDoc selectedRange]];
	    break;
	default: ;
    }
}

-(void) colorOff
{
    [theDoc setTextColor: [NSColor blackColor] range: [theDoc selectedRange]];
}
/* 
    This is a version of find next code, but it assumes the calling function does the setup
*/
-(void) findNextCode: (TAMSCharEngine *) who
{
     ctQChar *q;
     int aloc, bloc, l;
        NSRange n;
    
   q = [[ctQChar alloc] init];
    
    //set up system
    //get selection
    //save location
    n = [theDoc selectedRange];
    l = [[theDoc string] length];
    if(n.location > l - 1) return;
 
    //set up cursor one character back
    [who setCharLocation: (aloc = n.location + n.length)];
    //loop
    while(aloc < l - 1)
    {
    //save location A read a character save location B
	aloc = [who getCharLocation];
    //is it a code?
	[who readnext: q];
	bloc = [who getCharLocation];
	if([q tokentype] == TOKEN || [q tokentype] == ENDTOKEN
	    || [q tokentype] == META)
    //Yes select from A-B
	{
	    [theDoc setSelectedRange: NSMakeRange(aloc, bloc - aloc)];
	    [theDoc scrollRangeToVisible: NSMakeRange(aloc, bloc - aloc)];

	    [q release];
	    return;
	}
         //   else aloc = bloc - 1;
	//[who setCharLocation: (aloc + 1)];
    }
    [q release];
    //else goto A-1
    

}
#define COLOR1

-(IBAction) doColorize: (id) sender
{
    NSRange r,s;
    NSTextStorage *ts = [theDoc textStorage];
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    ctQChar *q;
    
    if(!gWorkBench) return;
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    
    q = [[ctQChar alloc] init];

    r = [theDoc selectedRange];
    
    [ts beginEditing];
    while([tc scanNext: q] != ENDOFFILE)
    {
            if([q tokentype] == TOKEN || [q tokentype] == ENDTOKEN)
            {
                /*
                [ts addAttribute:
                    NSForegroundColorAttributeName 
                           value:  [gWorkBench colorForCode: [q buff]]
                           range: [q range]];
                 */
                [theDoc setTextColor: [gWorkBench colorForCode: [q buff]] range: [q range]];
            }
               
            //else if([q tokentype] == ENDOFFILE)
                else if([q tokentype] == META)
            {
                    /*
                    [ts addAttribute:
                        NSForegroundColorAttributeName 
                               value:  getColorForInt([gPrefBoss tagColorValue])
                               range: [q range]];
                     */
                    [theDoc setTextColor: [gPrefBoss metaColor] range: [q range]];
            }
            
        
    }
    //[ts processEditing];
    [ts endEditing];
    //[theDoc didChangeText];
    [theDoc setAllowsUndo: YES];
    //[theDoc setSelectedRange: r];
    //[theDoc scrollRangeToVisible: r];
    
    [self updateChangeCount: NSChangeDone];
    [q release];
    [tc release];
}
-(IBAction) doColorizeRange: (NSRange) theRange
{
    NSRange r,s;
    NSTextStorage *ts = [theDoc textStorage];
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    MWFakeFile *mff;
    ctQChar *q;
    
    if(!gWorkBench) return;
    
    mff = [[MWFakeFile alloc] initWithString: [[theDoc string] substringWithRange: theRange]];
    [tc addFileToSearchList: mff];
    [tc startSearch];
    
    q = [[ctQChar alloc] init];
    
    r = [theDoc selectedRange];
    
    [ts beginEditing];
    while([tc scanNext: q] != ENDOFFILE)
    {
        if([q tokentype] == TOKEN || [q tokentype] == ENDTOKEN)
        {
            /*
             [ts addAttribute:
                 NSForegroundColorAttributeName 
                        value:  [gWorkBench colorForCode: [q buff]]
                        range: [q range]];
             */
            s = [q range];
            [theDoc setTextColor: [gWorkBench colorForCode: [q buff]] range: NSMakeRange(s.location + theRange.location, s.length)];
        }
        
        //else if([q tokentype] == ENDOFFILE)
        else if([q tokentype] == META)
        {
            /*
             [ts addAttribute:
                 NSForegroundColorAttributeName 
                        value:  getColorForInt([gPrefBoss tagColorValue])
                        range: [q range]];
             */
            s = [q range];
            [theDoc setTextColor: [gPrefBoss metaColor] range: NSMakeRange(s.location + theRange.location, s.length)];
        }
        
        
    }
    //[ts processEditing];
    [ts endEditing];
    //[theDoc didChangeText];
    [theDoc setAllowsUndo: YES];
    //[theDoc setSelectedRange: r];
    //[theDoc scrollRangeToVisible: r];
    
    [self updateChangeCount: NSChangeDone];
    [q release];
    [tc release];
    [mff release];
}
-(IBAction) doColorOn: (id) sender
{
    NSRange r,s;
    int myColor;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    [theDoc setAllowsUndo: YES];
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    if([[sender title] isEqualToString: @"Red"] ==YES)
	myColor = red;
     else if([[sender title] isEqualToString: @"Yellow"] ==YES)
	myColor = yellow;
     else if([[sender title] isEqualToString: @"Green"] ==YES)
	myColor = green;
     else if([[sender title] isEqualToString: @"Blue"] ==YES)
	myColor = blue;
     else if([[sender title] isEqualToString: @"Light gray"] ==YES)
	myColor = ltgray;
     else if([[sender title] isEqualToString: @"Gray"] ==YES)
	myColor = gray;
     else if([[sender title] isEqualToString: @"Dark gray"] ==YES)
	myColor = dkgray;

#ifdef COLOR2
    {
        NSScanner *myscn;
        int n1, n2, nt;
        NSTextStorage *myts;
        NSString *dummm;
        NSString* theTxt;
        NSRange rrr;
        
        myts = [theDoc textStorage];
//        [myts beginEditing];
        theTxt = [theDoc string];
        nt = [theTxt length];
        myscn = [[NSScanner alloc] initWithString: theTxt];
        [myscn setScanLocation: 0];
        while ([myscn scanUpToString: @"{" intoString: nil] == YES)
        {
                n1 = [myscn scanLocation];
                if([myscn scanUpToString: @"}" intoString: nil] ==YES)
                {
                    n2 = [myscn scanLocation]+1;
                    [myts addAttribute: NSForegroundColorAttributeName
                        value: [self getColor: myColor] 
                        range: NSMakeRange(n1, n2-n1)];
                }
                else break;
             
        }
  //      [myts endEditing];
        [theDoc didChangeText];
        [myscn release];
    }
#endif
#ifdef COLOR1
    {
        ctQChar  *qq;
        NSTextStorage *ts = [theDoc textStorage];
        qq = [[ctQChar alloc] init];
        
        r = [theDoc selectedRange];
        [theDoc setSelectedRange: NSMakeRange(0,0)];
        s = NSMakeRange(0,0);
        [ts beginEditing];
        while([tc scanNext: qq] != ENDOFFILE)
        {
            if([qq tokentype] == CHAR) continue;
            //[self findNextCode: tc];
            //[theDoc setSelectedRange: [qq range]];
            //[self colorOn: myColor];
            [ts addAttribute:
                       NSForegroundColorAttributeName 
                       value: [self getColor: myColor] range: [qq range]];
        }
        [ts endEditing];
        [theDoc setAllowsUndo: YES];
        [theDoc setSelectedRange: r];
        [theDoc scrollRangeToVisible: r];
        [self updateChangeCount: NSChangeDone];
        [qq release];
        [tc release];
    }
    
#endif
#ifdef COLOR3
    r = [theDoc selectedRange];
    [theDoc setSelectedRange: NSMakeRange(0,0)];
    s = NSMakeRange(0,0);
    
    for(;;)
    {
	[self findNextCode: tc];
	t = [theDoc selectedRange];
	if(s.length == t.length && s.location == t.location) break;
	[self colorOn: myColor];
	s = t;
    }
    [theDoc setAllowsUndo: YES];
    [theDoc setSelectedRange: r];
    [theDoc scrollRangeToVisible: r];
    [self updateChangeCount: NSChangeDone];
    [tc release];
#endif
}

-(IBAction) doColorOff: (id) sender
{
    NSRange r;
    
    r = [theDoc selectedRange];
/*
    [theDoc setSelectedRange: NSMakeRange(0,0)];
    s = NSMakeRange(0,0);
    
    for(;;)
    {
	[self doFindNextCode: nil];
	t = [theDoc selectedRange];
	if(s.length == t.length && s.location == t.location) break;
	[self colorOff];
	s = [theDoc selectedRange];
    }
*/
    [theDoc setTextColor: [NSColor blackColor]];

    [theDoc setSelectedRange: r];
    [theDoc scrollRangeToVisible: r];
    [self updateChangeCount: NSChangeDone];

}

-(int) sectionF {return sectionF;}
-(int) emptyF{ return emptyF;}
-(int) exactF {return exactF;}
-(int) rawF {return rawF;}
-(int) simpleF {return simpleF;}
-(int) regexCharF {return regexCharF;} //to start with don't do this for single file searches
-(int) nonRegexCharF {return nonRegexCharF;}
-(void) printShowingPrintPanel: (BOOL) flag
{
    //NSPrintInfo *printInfo = [self printInfo];
    NSPrintOperation *printOp;
    printOp = [NSPrintOperation printOperationWithView: theDoc];
	//printInfo: printInfo];
    [printOp setShowPanels: flag];
    [printOp runOperation];
}
/*
- (void)print:(id)sender {
    NSPrintOperation *op = [NSPrintOperation printOperationWithView:theDoc];
    // Assume printAccessoryView exists and returns your custom view
    NSView *accView = [self printAccessoryView];
    [op setAccessoryView:accView];
    [op runOperation];
}
*/
-(NSString *) getTitle
{
   return  [myWindow title];
}

-(int) getDocType {return myDocType;}

- (NSString *)windowNibName
{
    // Override returning the nib file name of the document
    // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
    return @"MyPanedDocument";
}

-(void) appendString: (NSString *)what
{
    NSRange n, l;
    //save location
    n = [theDoc selectedRange];
    //find the end
    l = NSMakeRange([[theDoc string] length],0);
    //insert
    [theDoc setSelectedRange: l];
    [theDoc insertText: what];
    //restore location
    [theDoc setSelectedRange: n];
    
}
-(NSString *) theLimitString
{
    return [theLimitString stringValue];
}
- (void) assignCode
{
    [self addCode: self];
}

- (void) displayCode
{
    int who;
    //NSLog(@"in display code\n");
    who = [theCodeList selectedRow];
    if(who >= 0)
    {
    
        
        [theNewCode setStringValue: [[gWorkBench getHotCodeList] objectAtIndex: who]];
    }

}
-(IBAction) displayCode: (id) sender
{
	//NSLog(@"In display:\n");
	[self displayCode];
}

-(void) setReanalysisState: (BOOL) which;
{
    if(which == YES)
    {
            [theDoc setEditable: NO];
            [theDoc setSelectable: YES];
            if([[theDoc undoManager] isUndoRegistrationEnabled] == YES)
            {
                [[theDoc undoManager] removeAllActions];
                [[theDoc undoManager] disableUndoRegistration];
            }
    }
    else
    {
        [theDoc setEditable: YES];
        if([[theDoc undoManager] isUndoRegistrationEnabled] == NO)
            [[theDoc undoManager] enableUndoRegistration];
    }

}
-(void) goReanalysisMode: (NSNotification *) notification
{
    if([[[notification userInfo] objectForKey: @"state"] isEqualToString: @"ON"] == YES)
    {
        [self setReanalysisState: YES];
    }
    else
        [self setReanalysisState: NO];

}

- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
    [super windowControllerDidLoadNib:aController];
    //deal with the toolbar
    // Add any code here that need to be executed once the windowController has loaded the document's window.
    if(dataFromFile)
    {
	[self loadtextViewWithData: dataFromFile];
	[dataFromFile release];
	dataFromFile = nil;
    }
#ifdef OLDWORKINGCODE
    //now that the codes are built, build the button bar (this should be combined with the bookmarks
    [self doFindButtons: nil];
    //find the bookmark window
    tttt = rebuildBMenuItem = [[NSApp delegate] rebuildMenuItem];
    [self rebuildBookmarks: rebuildBMenuItem];
#endif
    //This has to be moved to the workbench since it does not have access
    //to it's mwfile yet
    //[self scanForMetas]; //loads the bookmarks and buttons--relocated to the project file
    //register
    //[gWorkBench registerWindow: self];
    //[theDoc becomeFirstResponder];
    [theDoc setImportsGraphics: YES];
#ifdef MULTIMEDIA
#ifdef USETIMER
    if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_2)
        jagFlag = YES;
    else
        jagFlag = FALSE;
    
        myTimer = [[NSTimer scheduledTimerWithTimeInterval:0.1		// interval, 0.1 seconds
                                                     target:self
                                                   selector:@selector(idleTimer:)		// call this method
                                                   userInfo:nil
                                                  repeats:YES] retain];
    
#endif
#endif
    [myWindow makeFirstResponder: theDoc];
    [self refreshCodeList: nil];
    [theCodeList reloadData];
//NSLog(@"setting action--");
    [theCodeList setTarget: self];
    [theCodeList setAction: @selector(displayCode)];
    [theCodeList setDoubleAction: @selector(assignCode)];
//NSLog(@"action set\n");

    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(rootColorChanged:) name: @"rootColorChanged" object: nil];

}
-(void) rootColorChanged: (id) notification
{
    [self doColorize: nil];
}

-(NSString *) theWindowName
{
    return [theWindowName stringValue];
}

- (BOOL)loadFileWrapperRepresentation:(NSFileWrapper *)wrapper ofType:(NSString *)docType
{
    if([docType isEqualToString: @"RTFD"] == YES)
    {

        return [self loadDataRepresentation: [wrapper serializedRepresentation] ofType: docType];
    }
    else return [super loadFileWrapperRepresentation: wrapper ofType: docType];

}

-(void) loadtextViewWithData:(NSData *) data
{
    if(rtfFlag == 0)
    {
	myData = [[NSMutableString alloc] initWithCString: [data bytes]];
	[theDoc setString: myData];
	[myData release];
    }
    else if (rtfFlag == 1)
    {
	[theDoc replaceCharactersInRange: NSMakeRange(0, [[theDoc string] length])
	    withRTF: data];
    }
    else if (rtfFlag == 2)
    {
	[theDoc replaceCharactersInRange: NSMakeRange(0, [[theDoc string] length])
	    withRTFD: data];
    }

}
- (NSFileWrapper *)fileWrapperRepresentationOfType:(NSString *)aType
{
    if([aType isEqualToString: @"RTFD"] == YES)
    {
        return [[NSFileWrapper alloc]
            initWithSerializedRepresentation:[theDoc RTFDFromRange: NSMakeRange(0, 			[[theDoc string] length])]];
    }
    else
        return [super fileWrapperRepresentationOfType: aType];

}
- (NSData *)dataRepresentationOfType:(NSString *)aType
{
    // Insert code here to write your document from the given data.  
    //You can also choose to override -fileWrapperRepresentationOfType: or -writeToFile:ofType: instead.
    if([aType isEqualToString: @"Text"] == YES)
    {
	return [NSMutableData dataWithBytes: [[theDoc string] cString] length: 
	    [[theDoc string] cStringLength]];
    }
    else if ([aType isEqualToString: @"Rich text file"] == YES)
    {
	return [theDoc RTFFromRange: NSMakeRange(0, [[theDoc string] length])];
    }
    else if ([aType isEqualToString: @"RTFD"] == YES)
    {
	return [theDoc RTFDFromRange: NSMakeRange(0, [[theDoc string] length])];
    }
    
}

- (BOOL)loadDataRepresentation:(NSData *)data ofType:(NSString *)aType
{
    // Insert code here to read your document from the given data.  You can also choose to override -loadFileWrapperRepresentation:ofType: or -readFromFile:ofType: instead.
    if(theDoc)
    {
	[self loadtextViewWithData: data];
    }
    else
    {
	dataFromFile = [data retain];
    }
    if([aType isEqualToString: @"Text"] == YES)
    {
	rtfFlag = 0;
    }
    else if([aType isEqualToString: @"Rich text file"] == YES)
    {
	rtfFlag = 1;
    }
    else if([aType isEqualToString: @"RTFD"] == YES)
    {
	rtfFlag = 2;
    }
    return YES;
}
-(void) updateCodeWindow
{
    [theCodeList removeAllToolTips];
    if(gWorkBench != nil)
    {
        if([gWorkBench isCodeSet] == YES)
        {
            NSString *ccs = [NSString stringWithFormat: @"Codes: %@",[gWorkBench currCodeSet]];
            NSSETHEADER(theCodeList, @"Codes", ccs );
        }
        else
        {
            NSSETHEADER(theCodeList, @"Codes",@"Codes");
        }
    }
    [theCodeList reloadData];
}

-(void) zapCodeWindow
{
    [theCodeList removeAllToolTips];

    [hotCodeList removeAllObjects];
    [theCodeList reloadData];
}
-(void) setDirty: (BOOL) value
{
    dirty = value;
}
-(BOOL) dirty
{
    return dirty;
}

-(NSString *) getData
{
    return [theDoc string];
}

-(void) setData
{
    //gTheData = [[theDoc string] copy];
    //resetDataStream();
}
-(IBAction) generateCount: (id) Sender
{
    NSMutableArray *hc;
    tableBrowser *mt;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];

    [self refreshCodeList: nil];
    hc = [NSMutableArray arrayWithArray: [gWorkBench getHotCodeList]];
    //Need to send over the hot code list
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    mt = [[tableBrowser alloc] init];
    [mt setHotCodeList: hc];
    [mt setDataType: @"count"];
    [mt setCharEngine: tc];
    //[NSBundle loadNibNamed: @"FreqCount" owner: mt];
    //[mt windowControllerDidLoadNib: nil];
        [mt makeWindowControllers];
        [[NSDocumentController sharedDocumentController] addDocument:mt];
        [mt showWindows];

    [[mt window] makeKeyAndOrderFront: self];
    
}
-(IBAction) generateCrossReference: (id) Sender
{
    NSMutableArray *hc;
    tableBrowser *mt;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
     
    [self refreshCodeList: nil];
    hc = [NSMutableArray arrayWithArray: [gWorkBench getHotCodeList]];
    //Need to send over the hot code list
    [tc addFileToSearchList:[self getMyMWFile]];
    [tc startSearch];
    mt = [[tableBrowser alloc] init];
    [mt setHotCodeList: hc];
    [mt setDataType: @"xref"];
    [mt setCharEngine: tc];
    //[NSBundle loadNibNamed: @"FreqCount" owner: mt];
    //[mt windowControllerDidLoadNib: nil];
        [mt makeWindowControllers];
        [[NSDocumentController sharedDocumentController] addDocument:mt];
        [mt showWindows];

    [[mt window] makeKeyAndOrderFront: self];
    
}

-(IBAction) selectAllCodeList: (id) sender
{
        if(gWorkBench != nil) [gWorkBench loadAllCodes: nil];
     
}



-(void) nameCodeSetDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    
    if(returnCode)
    {
        NSString *ss;
        ss = [NSString stringWithString: [codeSetName stringValue]];
        if([ss isEqualToString: @""]) return;
        if(gWorkBench != nil) [gWorkBench convertTempToRealCodeSet: ss];
        
    }
    
}

-(IBAction) cancelNameCodeSet: (id) Sender
{
    [codeSetSheet orderOut: Sender];
    [NSApp endSheet: codeSetSheet returnCode: 0];
    
}

-(IBAction) okNameCodeSet: (id) Sender
{
    [codeSetSheet orderOut: Sender];
    [NSApp endSheet: codeSetSheet returnCode: 1];
    
}
-(IBAction) doNameCodeSet: (id) Sender
{
    [NSApp beginSheet: codeSetSheet
       modalForWindow: myWindow
	modalDelegate: self
       didEndSelector: @selector(nameCodeSetDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}

-(IBAction) clearHotCodeStack: (id) sender
{
    if(gWorkBench == nil) [gWorkBench clearTempCodeStack];
}
-(IBAction) popHotCodeStack: (id) sender
{
    NSString *ss;
    if(gWorkBench != nil)
    {
        ss = [gWorkBench popTempCodeStack];
        if(ss != nil)
            [theNewCode setStringValue: ss];
        else [self selectAllCodeList: nil];
    }
}

-(IBAction) selectWithinCodeList: (id) sender
{
    NSString *ss;
    if(gWorkBench == nil) return;
    ss = [NSString stringWithString: [theNewCode stringValue]];
    if([ss isEqualToString: @""])
        [gWorkBench loadAllCodes: nil];
    else
        [gWorkBench selectTempCodeSetWithin: [theNewCode stringValue]];
    
}
-(IBAction) selectMoreCodeList: (id) sender
{
    NSString *ss;
    if(gWorkBench == nil) return;
    ss = [NSString stringWithString: [theNewCode stringValue]];
    if([ss isEqualToString: @""])
        [gWorkBench loadAllCodes: nil];
    else
        [gWorkBench selectTempCodeSetMore: [theNewCode stringValue]];
    
}
-(IBAction) selectFewerCodeList: (id) sender
{
    NSString *ss;
    if(gWorkBench == nil) return;
    ss = [NSString stringWithString: [theNewCode stringValue]];
    if([ss isEqualToString: @""])
        [gWorkBench loadAllCodes: nil];
    else
        [gWorkBench selectTempCodeSetFewer: [theNewCode stringValue]];
    
}
-(IBAction) refreshCodeList: (id) Sender{

    if(Sender == nil)
        {
        [theCodeList removeAllToolTips];

        [theCodeList reloadData];
    }

    else
    {
        NSString *ss;
        if(gWorkBench == nil) return;
        ss = [NSString stringWithString: [theNewCode stringValue]];
        if([ss isEqualToString: @""])
            [gWorkBench loadAllCodes: nil];
        else
            [gWorkBench loadTempCodeSet: [theNewCode stringValue]];
    }
    //[gTheData release];

}

-(NSArray *) getHotCodeList
{
    return [gWorkBench getHotCodeList];
    
}

-(void) insertString: (NSString *) what
{
    NSRange r;
    int l;
    l = [what length];
    r = [theDoc selectedRange];
    
    [theDoc insertText: what];
    if([gPrefBoss autoColorValue])
    {
        [self doColorizeRange: NSMakeRange(r.location, l)];
    }
}
-(IBAction) doTurnTextToButton: (id) sender
{
    NSMutableString *ss;
    NSRange r;
    r = [theDoc selectedRange];
    if (r.length == 0) return;
    ss = [[NSMutableString alloc] init];
    //get the text
    [ss setString: [[theDoc string] substringWithRange: r]];
    //send it to the button
    [myToolbar addText: ss];
    [self addMacroItem: ss code: NO];
    [self rebuildDocMacros: nil];
    [ss autorelease];

}
-(IBAction) insertTAMSText: (id) sender
{
    NSRange selRange;
    NSMutableString *ss;
    int loc;
    int mc;
    int len, i;
    NSMutableDictionary *txtState;
    //mc = [gPrefBoss realColor];
    ss = [[NSMutableString alloc] init];
    
    selRange = [theDoc selectedRange];
    txtState = [NSMutableDictionary dictionaryWithDictionary: [theDoc typingAttributes]];
    [ss setString: [sender title]];
    len = [ss length];
    for(i = 0, loc = -1; i < len; i++)
    {
	if([ss characterAtIndex: i] == 'X')
	{
	    loc = i;
	    break;
	}
    }
    
    [theDoc insertText: ss];
    selRange.length = [ss length];
    //if(mc != black)
    {
        [theDoc setSelectedRange: selRange];
        [self newColorOn: [gPrefBoss metaColor]];
        [theDoc setSelectedRange: NSMakeRange(selRange.location + [ss length], 0)];
        //[txtState setObject: [NSColor blackColor] forKey: NSForegroundColorAttributeName];
        [theDoc setTypingAttributes: txtState];
/*
        [[theDoc textStorage] addAttribute: NSForegroundColorAttributeName 
            value: [txtState objectForKey: NSForegroundColorAttributeName]
            range: NSMakeRange(selRange.location + [ss length], 0)];
        //[theDoc setInsertionPointColor: ipc];
*/
    }
    [ss release];
    if(loc >= 0)
	[theDoc setSelectedRange: NSMakeRange(selRange.location + loc, 1)];
    
	

}

-(BOOL) isNew: (NSString *) what
{
    NSArray *hots;
    hots = [gWorkBench getHotCodeList];
    FORALL(hots)
    {
	if([temp isEqualToString: what]==YES)
	    return NO;
    }
    ENDFORALL;
    return YES;
}

-(IBAction) doRemoveBookmarks: (id) sender
{
    NSRange currSel;
    ctQChar  *qq;
    int bTerminus, eTerminus;
    NSMenu *myMen;
    int i,n;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];

    //delete the menu options
    myMen = [sender menu];
    n = [myMen numberOfItems];
    for(i = n-1; i > BOOKMARKBASE; i--)
    {
	[myMen removeItemAtIndex: i];
    }
    
    currSel = [theDoc selectedRange];

    //set up the reader
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    //get the first and end tags with the next characters
    //first:
    qq = [[ctQChar alloc] init];
    [tc setCharLocation: (0L)];
    bTerminus = 0L;
    while([tc scanNext: (qq)] != ENDOFFILE)
    {
	if([qq tokentype] == META)
	{
	    if([[qq buff] isEqualToString: @"bookmark"] == YES)
	    {
		eTerminus = [tc getCharLocation];
		//adjust our location
		if(bTerminus < currSel.location)
		    currSel.location -= (eTerminus - bTerminus);
		//select the bookmark and delete
		[theDoc setSelectedRange: NSMakeRange(bTerminus, eTerminus - bTerminus )];
		[theDoc insertText: @""];
		[tc startSearch];
		[tc setCharLocation: (bTerminus)];
		
	    }
	}
	bTerminus = [tc getCharLocation];
    }
    //restore selection
    [theDoc setSelectedRange: currSel];
        //scroll range
    [theDoc scrollRangeToVisible: currSel];

    [qq release];
    [tc release];

	    
}

-(NSString *) stringFrom: (int) b to: (int) e
{
    int l = [[theDoc string] length];
    NSMutableString *ss = [NSMutableString string];
    if(b < 0 || b > l-1) return ss;
    if(e < 0 || e > l-1) return ss;
    if(b >= e) return ss;
    
    [ss setString: [[theDoc string] substringWithRange: NSMakeRange(b, e-b)]];
    return ss;
}

-(void) deleteCodeFromResultStartingWith: (int) bwhere endingWith: (int) ewhere from: (id) who
{
    NSRange currSel;
    ctQChar *begChar, *endChar;
    int bTerminus, eTerminus;
    int bNew, lll;
    NSMutableString *ss;
    
    [self setReanalysisState: NO];
    
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    
    ss = [[NSMutableString alloc] init];
    
    //set up the reader
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    //get the first and end tags with the next characters
    //first:
    begChar = [[ctQChar alloc] init];
    [tc setCharLocation: (bwhere)];
    [tc readnext: begChar];
    bTerminus = [tc getCharLocation];
    
    //second
    endChar = [[ctQChar alloc] init];
    [tc setCharLocation: (ewhere)];
    [tc readnext: endChar];
    eTerminus = [tc getCharLocation];
 
    //make sure they're a match
    if([endChar tokentype] == ENDTOKEN && [begChar tokentype] == TOKEN &&
	    [[endChar buff] isEqualToString: [begChar buff]] && [[endChar coder] isEqualToString: [begChar coder]])
    {

    //save the location
	currSel = [theDoc selectedRange];
	
    //select the last
	[theDoc setSelectedRange: NSMakeRange(ewhere, eTerminus - ewhere)];
	//[self colorOn];
	[ss setString: @""];
	[theDoc insertText: ss];
	
    //get adjusted end and let the results know to adjust
    //[who adjustBy: ewhere - eTerminus  startingAt: ewhere for: [self getMyMWFile]];
    [self adjustResultDocsAt: ewhere forLength: ewhere - eTerminus];
    //select the first
	[theDoc setSelectedRange: NSMakeRange(bwhere, bTerminus - bwhere)];
	[ss setString: @""];
	[theDoc insertText: ss];
    //get adjusted beginning and let the results know to adjust
	[tc setCharLocation: (bwhere)];
	[tc readnext: (begChar)];
	bNew = [tc getCharLocation];
	//[who adjustBy: bwhere - bTerminus startingAt: bwhere for: [self getMyMWFile]];
        [self adjustResultDocsAt: bwhere forLength: bwhere - bTerminus];
	//if it's new make sure to add it
        [gWorkBench broadcastCodeChange: NO];


    //restore cursor
        lll = [[theDoc string] length];
        if(currSel.location > lll -1) currSel.location = lll - 1;
        if(currSel.location + currSel.length > lll - 1) currSel.length = 0;
        [theDoc setSelectedRange: currSel];
    }
    if(gWorkBench != nil) [self setReanalysisState: [gWorkBench reanalysisMode]];
    [self updateChangeCount: NSChangeDone];
    [theDoc didChangeText];
    [begChar release];
    [endChar release];
    [ss release];
    [tc release];

}

-(void) recode: (NSString *) what first: (int) bwhere last: (int) ewhere from: (id) who withDef: (NSString *) myDef
{
    [self recode: what comment: nil first: bwhere last: ewhere from: who withDef: myDef];
}
-(void) recode: (NSString *) what comment: (NSString *)cmt  first: (int) bwhere last: (int) ewhere from: (id) who withDef: (NSString *) myDef
{
    NSRange currSel;
    ctQChar *begChar, *endChar;
    int bTerminus, eTerminus;
    int bNew, eNew, lll, ll;
    int p1, p2, pr1, pr2, po1, po2;
    NSMutableString *ss;
    NSColor *myC;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    
    [self setReanalysisState: NO];
    ss = [[NSMutableString alloc] init];
    myC = [gWorkBench colorForCode: what];
    //set up the reader
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    //get the first and end tags with the next characters
    //first:
    begChar = [[ctQChar alloc] init];
    [tc setCharLocation: (bwhere)];
    [tc readnext: begChar];
    bTerminus = [tc getCharLocation];
    
    //second
    endChar = [[ctQChar alloc] init];
    [tc setCharLocation: (ewhere)];
    [tc readnext: endChar];
    eTerminus = [tc getCharLocation];
 
    //make sure they're a match
    if([endChar tokentype] == ENDTOKEN && [begChar tokentype] == TOKEN &&
	    [[endChar buff] isEqualToString: [begChar buff]] && [[endChar coder] isEqualToString: [begChar coder]])
    {

    //save the location
	currSel = [theDoc selectedRange];
	
    //select the last
	[theDoc setSelectedRange: NSMakeRange(ewhere, eTerminus - ewhere)];
        p2 = ewhere;
        pr2 = eTerminus - ewhere;
	//[self colorOn];
	[ss setString: @""];
	[ss appendString: @"{/"];
	[ss appendString: what];
	INSERTCODER(ss);
	if([[endChar extra] length] && cmt == nil)
	{
	    [ss appendString: @": "];
	    [ss appendString: [endChar extra]];
	}
	if(cmt != nil)
	{
	    [ss appendString: @": "];
	    [ss appendString: cmt];
	}
	[ss appendString: @"}"];
    //replace
        po2 = ll = [ss length];
	[theDoc insertText: ss];
        [theDoc setSelectedRange: NSMakeRange(ewhere, ll)];
        SETRAWCOLOR(myC);
	
    //get adjusted end and let the results know to adjust
    [tc clearSearchList];
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    [tc setCharLocation: (ewhere)];
    [tc readnext: endChar];
    eNew = [tc getCharLocation];
    //[who adjustBy: eNew - eTerminus startingAt: ewhere for: [self getMyMWFile]];
    
    [self adjustResultDocsAt: p2 + 1 forLength: po2 - pr2];
    //select the first
	[theDoc setSelectedRange: NSMakeRange(bwhere, bTerminus - bwhere)];
        p1 = bwhere;
        pr1 = bTerminus - bwhere;
	//[self colorOn];
	[ss setString: @""];
	[ss appendString: @"{"];
	[ss appendString: what];
	INSERTCODER(ss);
	[ss appendString: @"}"];
    //replace
        po1 = ll = [ss length];
	[theDoc insertText: ss];
        [theDoc setSelectedRange: NSMakeRange(bwhere, ll)];
        SETRAWCOLOR(myC);
    //get adjusted beginning and let the results know to adjust
	[tc setCharLocation: (bwhere)];
	[tc readnext: (begChar)];
	bNew = [tc getCharLocation];
	//[who adjustBy: bNew - bTerminus startingAt: bwhere for: [self getMyMWFile]];
        [self adjustResultDocsAt: p1+1 forLength: po1 - pr1];
	//if it's new make sure to add it
        if([self isNew: what]  && !myDef)
        {
            [gWorkBench addCode:  what definition: @""  active: YES append: YES];
            [gWorkBench broadcastCodeChange: NO];

        }
	else if([self isNew: what])
	{
            [gWorkBench addCode:  what definition: myDef  active: YES append: YES];
            [gWorkBench broadcastCodeChange: NO];
    
	}
        else
        {
            if(!myDef)
            {
                if([myDef isEqualToString: @""] == NO)
                {
                    [gWorkBench addCode:  what definition: myDef  active: YES append: YES];
                    [gWorkBench broadcastCodeChange: NO];
                }
            }
                    
        }

    //restore cursor
        lll = [[theDoc string] length];
        if(currSel.location > lll -1) currSel.location = lll - 1;
        if(currSel.location + currSel.length > lll - 1) currSel.length = 0;
        [theDoc setSelectedRange: currSel];
    }
    if(gWorkBench != nil) [self setReanalysisState: [gWorkBench reanalysisMode]];
    [self updateChangeCount: NSChangeDone];
    [theDoc didChangeText];
    [begChar release];
    [endChar release];
    [ss release];
    [tc release];

}

-(void) recode: (NSString *) what first: (int) bwhere last: (int) ewhere from: (id) who 
{
    [self recode: what first: bwhere last: ewhere from: who withDef: nil];
}

-(IBAction) doInsertDate: (id) sender
{
    [theDoc insertText: [[NSDate date] description]];
}

-(void) addCode: (NSString *) what from: (int) bwhere to: (int) ewhere from: (id) who withDef: (NSString *) myDef
{
    NSRange rr;
    
    [theDoc setSelectedRange: NSMakeRange(bwhere, ewhere - bwhere)];
    if([self isNew: what] || (![self isNew: what] && ((!myDef) ||[myDef isEqualToString: @""] == NO)) )
    {
        if(!myDef)  [gWorkBench addCode:  what definition: @""  active: YES append: YES];
	else if([myDef isEqualToString: @""] == YES) 
            [gWorkBench addCode:  what definition: @""  active: YES append: YES];
        else 
            [gWorkBench addCode:  what definition: myDef  active: YES append: YES];
        [gWorkBench broadcastCodeChange: NO];
        [self applyCode: what];
    }
    else [self applyCode: what];
	    
    
    //go back and adjust all the numbers
    //get the new selection
    rr = [theDoc selectedRange];
    //[who adjustBy: (rr.location + rr.length) - ewhere - ([what length] + 2) startingAt: ewhere for: [self getMyMWFile]];
   // [self adjustResultDocsAt: ewhere forLength: (rr.location + rr.length) - ewhere - ([what length] + 2)];

    
    //[who adjustBy: [what length] + 2 startingAt: bwhere for: [self getMyMWFile]];
    //[self adjustResultDocsAt: bwhere forLength: [what length] + 2];
    
    [self updateChangeCount: NSChangeDone];
    [theDoc didChangeText];

}

-(BOOL) isReal{return YES;}
-(void) addCode: (NSString *) what from: (int) bwhere to: (int) ewhere from: (id) who
{
    [self setReanalysisState: NO];
    [theDoc setSelectedRange: NSMakeRange(bwhere, ewhere - bwhere)];
    [self applyCode: what];
    //go back and adjust all the numbers
    //[who adjustBy: [what length] + 2 startingAt: ewhere for: self];
    [self adjustResultDocsAt: ewhere forLength: [what length] + 2];
    //[who adjustBy: [what length] + 2 startingAt: bwhere for: self];
    [self adjustResultDocsAt: bwhere forLength: [what length] + 2];

    //what if it's new?
    
    if([self isNew: what])
    {
        [gWorkBench newCode: what definition: nil color: inheritedColor];
	[self refreshCodeList: nil];

    }
    if(gWorkBench != nil) [self setReanalysisState: [gWorkBench reanalysisMode]];
}

-(IBAction) addItemToToolbar: (id) sender
{
    int who;
    NSString *name;
    who = [theCodeList selectedRow];
    if(who >= 0)
    {
        name =  [[gWorkBench getHotCodeList] objectAtIndex: who];
        [myToolbar addItem: name ];
        [self addMacroItem: name code: YES];
        [self rebuildDocMacros: nil];
    }
   


}

-(IBAction) doToggleRuler: (id) sender
{
    [theDoc toggleRuler: self];

}

-(void) commentDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    if(returnCode == 0) return;
    else
    {
        int who;
   
        if([gPrefBoss codeFromListValue] == 0)
        {
        // This would be a great addition if we did some user preference on it
            if([[theNewCode stringValue] length])
            {
                if([self isNew: [theNewCode stringValue]] == YES)
                    [self newCode: nil];
                else
                    [self applyCode: [theNewCode stringValue] withComment: [commentView string]];
                return;
            }
        }
        who = [theCodeList selectedRow];
        if(who >= 0)
        {
            [self applyCode: [[gWorkBench getHotCodeList] objectAtIndex: who] withComment: [commentView string]];
        }

    }


}


-(IBAction) addCode: (id) Sender
{
    int who;
	NSLog(@"addCode\n");
    if([gPrefBoss commentForCode] == 1 && Sender == codeButton)
    {
	NSLog(@"in comment\n");
        [commentView setString: @""];
    	[NSApp beginSheet: commentSheet
	    modalForWindow: myWindow
	    modalDelegate: self
	    didEndSelector: @selector(commentDidEnd:returnCode:contextInfo:)
	    contextInfo: nil];
        return;
    }

    if([gPrefBoss codeFromListValue] == 0)
    {
	NSLog(@"in codeFromListValue\n");
    // This would be a great addition if we did some user preference on it
	if([[theNewCode stringValue] length])
	{
	    if([self isNew: [theNewCode stringValue]] == YES)
		[self newCode: nil];
	    else
		[self applyCode: [theNewCode stringValue]];
	    return;
	}
    }
    who = [theCodeList selectedRow];
    if(who >= 0)
    {
        [self applyCode: [[gWorkBench getHotCodeList] objectAtIndex: who]];
    }

}

-(void) applyCode: (NSString *) aCode withComment: (NSString *) comment
{
#ifdef NEWAPPLYCODE
	NSMutableString *theans, *theans1;
	NSRange where, newWhere, loc1, loc2;
        int l1, l2, r1, r2;
        NSColor *myC;
        
        [self setReanalysisState: NO];
        myC = [gWorkBench colorForCode: aCode];
	where = [theDoc selectedRange ];
        r1 = where.location;
        r2 = where.location + where.length;
	theans = [[NSMutableString alloc] init];
	theans1 = [[NSMutableString alloc] init];
        //[[theDoc textStorage] beginEditing];
	[theans appendString: @"{"];
	[theans appendString: aCode];
	INSERTCODER(theans);
	[theans appendString:@"}"];
	//[self colorOn];
	l1 = [theans length];
	[theans1 appendString: @"{/"];
	[theans1 appendString: aCode];
	INSERTCODER(theans1);
	if(comment)
	    if([comment length])
	    {
		[theans1 appendString: @": "];
		[theans1 appendString: comment];
	    }
	[theans1 appendString: @"}"];
	l2 = [theans1 length];
        
        loc1 = where;
        loc1.length = 0;
        [theDoc setSelectedRange: loc1];
	[theDoc insertText: theans];
        loc1.length = l1;
        {
            [theDoc setSelectedRange: loc1];
            SETCOLOR(aCode);//[self colorOn: mc];
        }
         
        loc2.location = where.location + where.length + l1;
        loc2.length = 0;
        [theDoc setSelectedRange: loc2];
	[theDoc insertText: theans1];
        loc2.length = l2;
        //if(mc != black) 
        {
            [theDoc setSelectedRange: loc2];
            SETCOLOR(aCode);//[self colorOn: mc];
        }
        newWhere = where;
        newWhere.length += l1 +l2;
        [theDoc setSelectedRange: newWhere];
        //[[theDoc textStorage] endEditing];
        [self adjustResultDocsAt: r2 forLength: [theans1 length]];
        [self adjustResultDocsAt: r1 forLength: [theans length]];

        [theans release];
        [theans1 release];
    if(gWorkBench != nil) [self setReanalysisState: [gWorkBench reanalysisMode]];        
	//[theDoc replaceCharactersInRange: where withString: theans];
	//[theDoc setSelectedRange: NSMakeRange(where.location,  newLen)];
	//[self updateChangeCount: NSChangeDone];

#else


	NSMutableString *theans;
	NSMutableString *theVictim;
	NSRange where;
	unsigned newLen;
	theans = [[NSMutableString alloc] init];
	[theans appendString: @"{"];
	[theans appendString: aCode];
	INSERTCODER(theans);
	[theans appendString:@"}"];
	myData = [theDoc string];
	where = [theDoc selectedRange ];
	//[self colorOn];
	theVictim = [[NSMutableString alloc] initWithString: [myData substringWithRange: where]];
	[self colorOff];
	[theans appendString: theVictim];
	//[self colorOn];
	[theans appendString: @"{/"];
	[theans appendString: aCode];
	INSERTCODER(theans);
	if(comment)
	    if([comment length])
	    {
		[theans appendString: @": "];
		[theans appendString: comment];
	    }
	
	[theans appendString: @"}"];
	[self colorOff];
	newLen = [theans length];
	[theDoc insertText: theans];
	//[theDoc replaceCharactersInRange: where withString: theans];
	[theDoc setSelectedRange: NSMakeRange(where.location,  newLen)];
	//[self updateChangeCount: NSChangeDone];
#endif
}

/* this is for fetching definitions*/
-(void) sheetDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    if(returnCode == 1)
    {
        int cc;
        //cc = [[codeColorMenu selectedItem] tag];
        if([inheritedColorSwitch state] == NSOnState)
            cc = inheritedColor;
        else
            cc = otherColor;
        [codeInfoStr setString: [codeInfo string]];
        if(cc == otherColor)
            [gWorkBench newCode: [theNewCode stringValue] definition: codeInfoStr 
                          realColor:[myColorWell color]];
        else
            [gWorkBench newCode: [theNewCode stringValue] definition: codeInfoStr 
                color:cc];
        [self applyCode: [theNewCode stringValue] withComment: nil];

    }
    [self refreshCodeList: nil];


}

-(IBAction) cancelCodeInfo: (id) sender
{
    //[codeInfoStr setString: [codeInfo stringValue]];
    [codeInfoSheet orderOut: sender];
    [NSApp endSheet: codeInfoSheet returnCode: 0];
}

-(IBAction) okCodeInfo: (id) sender
{
    //[codeInfoStr setString: [codeInfo stringValue]];
    [codeInfoSheet orderOut: sender];
    [NSApp endSheet: codeInfoSheet returnCode: 1];
}
-(IBAction) selectColorFromWell:(id)Sender
{
    [inheritedColorSwitch setState: NSOffState];
}
-(IBAction) selectColorFromSwitch:(id) sender
{
    if([inheritedColorSwitch state] == NSOnState)
        [myColorWell setColor: [NSColor blackColor]];
}
-(IBAction) newCode: (id) Sender
{
    NSMutableString *chkstr, *chk2;

    chkstr = [[NSMutableString alloc] initWithString: [theNewCode stringValue]];
    //[codeColorMenu selectItemAtIndex: [codeColorMenu indexOfItemWithTag: inheritedColor]]; 
    [inheritedColorSwitch setState: NSOnState];
    if(gWorkBench != nil)
        [myColorWell setColor: [gWorkBench colorForCode: [theNewCode stringValue]]];
    else
        [myColorWell setColor:  [NSColor blackColor]];
   
    if([chkstr length] == 1)
    {
        if([chkstr isEqualToString: @" "])
        {
            [chkstr release];
            return;
        }
    }
    else
    {
        chk2 = NSTRIM(chkstr);
        [chkstr setString: chk2];
    }
    
    //[chkstr setString: NSTRIM(chkstr)];
    if([chkstr length] == 0)
    {
	[chkstr release];
	return;
    }
    if(!isCodeNameLegal(chkstr))
    {
        NSWARNING(@"Illegal character in code name");
        return;
    }
    if([gPrefBoss promptValue])
    {
	//init the variables
	[codeInfoStr setString: @""];
	[codeInfo setString: @""];
	[newCodeName setStringValue: [theNewCode stringValue]];
	//ask for the information
	[NSApp beginSheet: codeInfoSheet
	    modalForWindow: myWindow
	    modalDelegate: self
	    didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:)
	    contextInfo: nil];
	//while([NSApp modalWindow])
	    ;
	//send it on
	//This has been relocated to the ok button action routine
	//[gWorkBench newCode: [theNewCode stringValue] definition: codeInfoStr];
    }
    else
    {
        [gWorkBench newCode: [theNewCode stringValue] definition: @"" color: inheritedColor];
        [self applyCode: [theNewCode stringValue] withComment: nil];
	    
	[self refreshCodeList: nil];

    }
 	
}

-(IBAction) integrateCodes: (id) sender
{
    NSArray *aHotCodeList;
    int n;
    //rebuild the codes
    aHotCodeList = [self remakeCodeList];
    
    n = [aHotCodeList count];
    //go through mine
    FORALL(aHotCodeList)
    {
    //if it is in theirs
	if([gWorkBench isMyCode: temp] == NO)
	{
	    [gWorkBench newCode: temp definition: [self getTitle] color: inheritedColor];
	}
    }
    ENDFORALL;
}
-(BOOL) isACode: (NSString *) who
{
    NSArray *aHotCodeList = [gWorkBench allCodeList];
    
    FORALL(aHotCodeList)
    {
	if([temp isEqualToString: who] == YES)
	    return YES;
    }
    ENDFORALL;
    return NO;
}

-(BOOL) isMyCode: (NSString *) who
{
    NSArray *aHotCodeList = [gWorkBench getHotCodeList];
    
    FORALL(aHotCodeList)
    {
	if([temp isEqualToString: who] == YES)
	    return YES;
    }
    ENDFORALL;
    return NO;
}

-(BOOL) isValidCode: (NSString *) who
{
    return [self isMyCode: who];
}

-(NSArray *) keyCodeList
{
    return [[gWorkBench getHotCodeList] retain];
}
-(NSArray *) hotCodeList
{
	//if(gWorkBench == nil) NSLog(@"Do not have a workbench.\n");

return [gWorkBench getHotCodeList];}

-(NSArray *) remakeCodeList
{
    int n;
    int insertflag;
    ctQChar *q;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
	NSRange rrr;
    NSMutableArray *hotCodeList = [NSMutableArray array];

    q = [[ctQChar alloc] init];

    [hotCodeList removeAllObjects];
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    //[self setData];

    while([tc scanNext: q] != ENDOFFILE)
    {
    //until eof
    //if it's a tag

	if([q tokentype] == ENDTOKEN)
	{
	    insertflag = 0;

	    FORALL(hotCodeList)
	    {
		if([temp isEqualToString: [q buff]])
		{
		    insertflag = -1;
		    break;
		}
		else if ((n = [temp compare: [q buff]]) == NSOrderedAscending)
                    //strcmp((char *)[temp cString],(char *) [[q buff] cString])) > 0)// ([[(NSString *)temp compare: [q buff]] isGreaterThan] == YES)
		{
		    NSString *myans;
		    rrr =[[q extra] rangeOfString: @"retired" options: NSCaseInsensitiveSearch];
		    if(rrr.location != NSNotFound) continue;
		    myans = [[[q buff] copy] autorelease];
		    [hotCodeList insertObject: myans atIndex: __i];
		    insertflag = 1;
		    break;
		}
	    }
	    ENDFORALL;
	    if(insertflag == 0)

	    { 
		NSString *myans;
		
		rrr =[[q extra] rangeOfString: @"retired" options: NSCaseInsensitiveSearch];
		if(rrr.location != NSNotFound) continue;
		 myans = [[[q buff] copy] autorelease]; 
		//[myans retain];
		[hotCodeList addObject: myans];
	    }
	}
		//check it out

    }
    [q release];
    [tc release];
    return hotCodeList;
}

-(void) adjustResultDocsAt: (int) loc forLength: (int) len
{
    NSMutableDictionary *msg;
    msg = [NSMutableDictionary dictionary];
    [msg setObject: [NSNumber numberWithInt: loc] forKey: @"location"];
    [msg setObject: [NSNumber numberWithInt: len] forKey: @"length"];
    [[NSNotificationCenter defaultCenter] postNotificationName: @"TAMSDocAddedCode"
        object: [self getMyMWFile]
        userInfo: msg
        ];
}



-(void) applyCode: (NSString *) aCode
{
#ifdef OLDNEWAPPLYCODE
	NSMutableString *theans, *theans1;
	NSRange where, newWhere, loc1, loc2;
        //int mc;
	int l1, l2;
        
        
        //mc = [gPrefBoss realColor];
	where = [theDoc selectedRange ];
        //[[theDoc textStorage] beginEditing];
	theans = [[NSMutableString alloc] init];
	theans1 = [[NSMutableString alloc] init];
	[theans appendString: @"{"];
	[theans appendString: aCode];
	INSERTCODER(theans);
	[theans appendString:@"}"];
	//[self colorOn];
	
	[theans1 appendString: @"{/"];
	[theans1 appendString: aCode];
	INSERTCODER(theans1);
	[theans1 appendString: @"}"];
	
        loc1 = where;
        loc1.length = 0;
        [theDoc setSelectedRange: loc1];
	[theDoc insertText: theans];
        l1 = loc1.length = [theans length];
        //if(mc != black) 
        {
        
            [theDoc setSelectedRange: loc1];
            [self newColorOn: [gPrefBoss realColor]];
        }
        
        loc2.location = where.location + where.length + l1;
        loc2.length = 0;
        [theDoc setSelectedRange: loc2];
	[theDoc insertText: theans1];
        l2 = loc2.length = [theans1 length];
        //if(mc != black) 
        {
            [theDoc setSelectedRange: loc2];
            [self newColorOn: [gPrefBoss realColor]];
        }
        newWhere = where;
        newWhere.length += l1 + l2;
        [theDoc setSelectedRange: newWhere];
        //[[theDoc textStorage] endEditing];
        [theans release];
        [theans1 release];
	//[theDoc replaceCharactersInRange: where withString: theans];
	//[theDoc setSelectedRange: NSMakeRange(where.location,  newLen)];
	//[self updateChangeCount: NSChangeDone];

#endif
#ifdef NEWAPPLYCODE
	NSMutableString *theans, *theans1;
	NSRange where, newWhere, loc1, loc2;
        NSDictionary *initState;
        NSMutableDictionary *myat;
        NSTextStorage *myTS;
        NSUndoManager *myUndo;
        //int mc;
	int l1, l2, r1, r2;
        NSColor *myC;
        
        
        [self setReanalysisState: NO];
        //mc = [gPrefBoss realColor];
        myC = [gWorkBench colorForCode: aCode];
	where = [theDoc selectedRange ];
        r1 = where.location;
        r2 = where.location + where.length;
        myTS = [theDoc textStorage];
        myUndo = [theDoc undoManager];
        if([myTS length] < where.location)
            initState = [myTS attributesAtIndex: where.location effectiveRange: nil];
        else
            initState = [theDoc typingAttributes];
         myat = [NSMutableDictionary dictionaryWithDictionary: [theDoc typingAttributes]];
         //[myUndo endUndoGroup];
         //[myUndo beginUndoGrouping];
       //[myTS beginEditing];
	theans = [[NSMutableString alloc] init];
	theans1 = [[NSMutableString alloc] init];
	[theans appendString: @"{"];
	[theans appendString: aCode];
	INSERTCODER(theans);
	[theans appendString:@"}"];
	//[self colorOn];
	
	[theans1 appendString: @"{/"];
	[theans1 appendString: aCode];
	INSERTCODER(theans1);
	[theans1 appendString: @"}"];
	
        loc1 = where;
        loc1.length = 0;
        [theDoc setSelectedRange: loc1];
	[theDoc insertText: theans];
            
       // [myTS insertAttributedString: [[[NSAttributedString alloc] initWithString: theans] autorelease] atIndex: loc1.location];
        l1 = loc1.length = [theans length];
        [theDoc setSelectedRange: loc1];
        //if(mc != black) 
        {
            //[myTS addAttribute: NSForegroundColorAttributeName
            //    value: [self getColor: mc] range: loc1];
           [ myTS addAttribute: NSForegroundColorAttributeName
                value: myC range: loc1];
        }
        
        loc2.location = where.location + where.length + l1;
        loc2.length = 0;
        
       // [myTS insertAttributedString: [[[NSAttributedString alloc] initWithString: theans1] autorelease] atIndex: loc2.location];
        [theDoc setSelectedRange: loc2];
	[theDoc insertText: theans1];
       l2 = loc2.length = [theans1 length];
       [theDoc setSelectedRange: loc2];
        //if(mc != black) 
        {
            //[myTS addAttribute: NSForegroundColorAttributeName
              //  value:[self getColor: mc]  range: loc2];
            [myTS addAttribute: NSForegroundColorAttributeName
                value: myC range: loc2];
        }
        newWhere = where;
        newWhere.length += l1 + l2;
        [myTS setAttributes:initState range: NSMakeRange(newWhere.location+newWhere.length, 0)];
        
        [self adjustResultDocsAt: r2 forLength: [theans1 length]];
        [self adjustResultDocsAt: r1 forLength: [theans length]];
                
        

        [theDoc setTypingAttributes: myat];
        //[myTS endEditing];
        [theDoc didChangeText];
        //[myUndo endUndoGrouping];
         [theDoc setSelectedRange: newWhere];
      [theans release];
        [theans1 release];
    if(gWorkBench != nil) [self setReanalysisState: [gWorkBench reanalysisMode]];
#endif
#ifdef LESSNEWAPPLYCODE
	NSMutableString *theans, *theans1;
	NSRange where, newWhere, loc1, loc2;
        NSDictionary *initState;
        NSMutableDictionary *myat;
        NSTextStorage *myTS;
        NSUndoManager *myUndo;
        //int mc;
	int l1, l2;
        NSColor *myC;
        
        
        //mc = [gPrefBoss r];
        myC = [gWorkBench colorForCode: aCode];
	where = [theDoc selectedRange ];
        myTS = [theDoc textStorage];
        myUndo = [theDoc undoManager];
        if([myTS length] < where.location)
            initState = [myTS attributesAtIndex: where.location effectiveRange: nil];
        else
            initState = [theDoc typingAttributes];
         myat = [NSMutableDictionary dictionaryWithDictionary: [theDoc typingAttributes]];
         //[myUndo endUndoGroup];
         //[myUndo beginUndoGrouping];
       //[myTS beginEditing];
	theans = [[NSMutableString alloc] init];
	theans1 = [[NSMutableString alloc] init];
	[theans appendString: @"{"];
	[theans appendString: aCode];
	INSERTCODER(theans);
	[theans appendString:@"}"];
	//[self colorOn];
	
	[theans1 appendString: @"{/"];
	[theans1 appendString: aCode];
	INSERTCODER(theans1);
	[theans1 appendString: @"}"];
	
        loc1 = where;
        loc1.length = 0;
        //[theDoc setSelectedRange: loc1];
	//[theDoc insertText: theans];
        [myTS insertAttributedString: [[[NSAttributedString alloc] initWithString: theans] autorelease] atIndex: loc1.location];
        l1 = loc1.length = [theans length];
        
        //if(mc != black) 
        {
            //[myTS addAttribute: NSForegroundColorAttributeName
              //  value: [self getColor: mc] range: loc1];
            [myTS addAttribute: NSForegroundColorAttributeName
                value: myC range: loc1];
        }
        
        loc2.location = where.location + where.length + l1;
        loc2.length = 0;
        [myTS insertAttributedString: [[[NSAttributedString alloc] initWithString: theans1] autorelease] atIndex: loc2.location];
       l2 = loc2.length = [theans1 length];
        //if(mc != black) 
        {
           // [myTS addAttribute: NSForegroundColorAttributeName
           //     value:[self getColor: mc]  range: loc2];
            [myTS addAttribute: NSForegroundColorAttributeName
                value:myC  range: loc2];
        }
        newWhere = where;
        newWhere.length += l1 + l2;
        [myTS setAttributes:initState range: NSMakeRange(newWhere.location+newWhere.length, 0)];
        
        

        [theDoc setTypingAttributes: myat];
        //[myTS endEditing];
        [theDoc didChangeText];
        //[myUndo endUndoGrouping];
         [theDoc setSelectedRange: newWhere];
      [theans release];
        [theans1 release];
	//[theDoc replaceCharactersInRange: where withString: theans];
	//[theDoc setSelectedRange: NSMakeRange(where.location,  newLen)];
	//[self updateChangeCount: NSChangeDone];

#endif
	
}
-(IBAction) setTypeBlack: (id) Sender
{
    NSMutableDictionary *myat;
    NSRange selrange;
    selrange = [theDoc selectedRange];
    if(selrange.length)
        [theDoc setTextColor: [NSColor blackColor] range: [theDoc selectedRange]];
    else
    {
        myat = [NSMutableDictionary dictionaryWithDictionary: [theDoc typingAttributes]];
        [myat setObject: [NSColor blackColor] forKey: NSForegroundColorAttributeName];
        [theDoc setTypingAttributes: myat];
    }
    
    
}

-(IBAction) saveFontFormat: (id) Sender
{
    if(savedFormat) [savedFormat release];
    savedFormat = [NSMutableDictionary dictionaryWithDictionary: [theDoc typingAttributes]];
    [savedFormat retain];
    
}
-(IBAction) applyFontFormat: (id) Sender
{
    NSRange selrange;
    if(savedFormat == nil) return;
    selrange = [theDoc selectedRange];
    if(selrange.length)
    {
        NSTextStorage *what;
        what = [theDoc textStorage];
        [what beginEditing];
        [what setAttributes: savedFormat range: selrange];
        [what endEditing];
        [theDoc didChangeText];
    }
    else
    {
        [theDoc setTypingAttributes: savedFormat];
    }
}

-(IBAction) clearFontFormat: (id) sender
{
    if(savedFormat != nil)
    {
        [savedFormat release];
        savedFormat = nil;
    }
}
-(IBAction) generateCodeList: (id) Sender
{
    NSRange where,theEnd;
    NSMutableString *theCodeString;
     NSMutableArray *hotCodeList;
   theCodeString = [[NSMutableString alloc] init];
    
    //save location
    where = [theDoc selectedRange];
    theEnd.location = [[theDoc string] length];
    theEnd.length = 0;
    //refresh
    hotCodeList = [self remakeCodeList];
    //go to end
    [theDoc setSelectedRange: theEnd];
    //spill out the codes
    [theCodeString appendString: [NSString stringWithFormat: @"Codes from file %@:\n",
        [[self getMyMWFile] name]]];
    FORALL(hotCodeList)
    {
	[theCodeString appendString: @"{"];
	[theCodeString appendString: [hotCodeList objectAtIndex: __i]];
	[theCodeString appendString: @"}"];
	[theCodeString appendString: @"{/"];
	[theCodeString appendString: [hotCodeList objectAtIndex: __i]];
	[theCodeString appendString: @"}"];
	[theCodeString ADDCHAR('\n')];
    
    }
    ENDFORALL;
    //restore location
    [theDoc setSelectedRange: where];
    [gWorkBench newFileWithText: theCodeString];

}

- (void)tableView:(NSTableView *)tableView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex 
{
    if([gPrefBoss useToolTipValue])
    {
	[theCodeList addToolTipRect: [theCodeList frameOfCellAtColumn: 0 row: rowIndex] owner: [[self keyCodeList] objectAtIndex: rowIndex] userData:nil];
    }
}


-(BOOL)tableView: (NSTableView *) aTable shouldEditTableColumn: (NSTableColumn *) aCol row: (unsigned) arow
{
    return NO;
}

-(void) widthSizeDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    int lw;
    int ls;
    BOOL blank, numBlank;
    
    if(returnCode == 1)
    {
        lw = [wsWidthSize intValue];
        ls = [wsStartNumber intValue];
        if ([wsBlankBreakSwitch state] == NSOnState)
            blank = YES;
        else
            blank = NO;
            
        if ([wsCountEmptyLineSwitch state] == NSOnState)
            numBlank = YES;
        else
            numBlank = NO;
            
        [self lineNumberDocWithWidth: lw startingAt: ls atBlanks: blank numberBlanks: numBlank];
    
    }
}


-(IBAction) okCodeWithComment: (id) sender
{
    [commentSheet orderOut: sender];
    [NSApp endSheet: commentSheet returnCode: 1];
}

-(IBAction) cancelCodeWithComment: (id) sender
{
    [commentSheet orderOut: sender];
    [NSApp endSheet: commentSheet returnCode: 0];
}


-(IBAction) okCountLines: (id) sender
{
    [widthSheet orderOut: sender];
    [NSApp endSheet: widthSheet returnCode: 1];
}

-(IBAction) cancelCountLines: (id) sender
{
    [widthSheet orderOut: sender];
    [NSApp endSheet: widthSheet returnCode: 0];
}


-(void) lineNumberDocWithWidth: (int) width startingAt: (int) begin atBlanks: (BOOL) blanks numberBlanks: (BOOL) cntBlanks
{
    int rcnt;
    NSString *tempStr;
    int llen, len, i;
    int spaceLoc;
    int blanklen;
    int skipMode;
    int lnum;
    NSString *ttt;

    MWCHAR cc;
   
    //give it to the char engine
    //create q

    spaceLoc = blanklen = skipMode = rcnt = llen = 0;
    //two passes once to break lines; once to number
    if(width > 0)
    {
        tempStr = [NSString stringWithString: [theDoc string]];
        len = [tempStr length];
        for(i =0; i < len; i++)
        {
            cc = [tempStr characterAtIndex: i];
            //do the ones we skip over
            if(skipMode == 1)
            {
                skipMode = 0;
                continue;
            }
            if(skipMode == 2 &&  cc == '}')
            {
                skipMode = 0;
                continue;
            }
            
            if(skipMode) continue;
            
            if(cc == '\\')
            {
                skipMode = 1;
                continue;
            }
            if(cc == '{')
            {
                skipMode = 2;
                continue;
            }
            
            if(cc == '\r' || cc == '\n')
            {
                blanklen = 0;
                spaceLoc = 0;
                llen = 0;
            }
            
            if(llen > width)
            {
                if(blanks == YES)
                {
                    if(spaceLoc)
                        i = spaceLoc;
                }
                //insert the return and do what you need to
                if(i + 1 + rcnt < len +rcnt -1)
                {
                    [theDoc setSelectedRange: NSMakeRange(i+1+rcnt, 0)];
                    [theDoc insertText: @"\n"];
                    rcnt++;
                    blanklen = 0;
                    spaceLoc = 0;
                    llen = 0;
                }
                else break;
                continue;
            }
            if(cc == ' ')
            {
                spaceLoc = i;
                blanklen =0;
            }
            llen++;
            blanklen++;
            
        }
    }
    

    //get it again and tce
    rcnt = 0;
    lnum = begin;
    tempStr = [NSString stringWithString: [theDoc string]];
    len = [tempStr length];
    if(((cc = [tempStr characterAtIndex: 0]) != '\n') && cc != '\r')
    {
        [theDoc setSelectedRange: NSMakeRange( 0, 0)];
        ttt = [NSString stringWithFormat: @"%d\t", lnum];
        [theDoc insertText: ttt];
        rcnt += [ttt length];
        lnum++;
    
    }
    for(i = 0; i < len ; i++)
    {
        if(((cc = [tempStr characterAtIndex: i]) == '\n') || cc == '\r')
        {
            if(i < len - 1)
            {
                if( ([tempStr characterAtIndex: i+1] == '\r' ||  [tempStr characterAtIndex: i+1]) == '\n' && cntBlanks == NO)
                    continue;
                [theDoc setSelectedRange: NSMakeRange( i+1 + rcnt, 0)];
                ttt = [NSString stringWithFormat: @"%d\t", lnum];
                [theDoc insertText: ttt];
                rcnt += [ttt length];
                lnum++;
            }
            
        }
    
    }
}

-(IBAction) numberLines: (id) sender
{
        [wsWidthSize setIntValue: 40];
        [wsStartNumber setIntValue: 1];
        [wsBlankBreakSwitch setState: NSOnState];
        [wsCountEmptyLineSwitch setState: NSOffState];
    
	[NSApp beginSheet: widthSheet
	    modalForWindow: myWindow
	    modalDelegate: self
	    didEndSelector: @selector(widthSizeDidEnd:returnCode:contextInfo:)
	    contextInfo: nil];


}

-(IBAction) removeLineNumbers: (id) sender
{
    NSMutableArray *numLoc;
    NSRange r;
    int i, n, fflag, nflag;
    int tpart;
    MWCHAR ch;
    NSCharacterSet *nums;
    
    nums = [NSCharacterSet decimalDigitCharacterSet];
    
    fflag = 1;
    nflag = 1;
    tpart = 0;
    r.location = r.length = 0;
    n = [[theDoc string] length];
    for(i = 0; i < n; i++)
    {
        ch = [[theDoc string] characterAtIndex: i];
        if(ch == '\r' || ch == '\n')
        {
            r.location = i+1;
            r.length = 0;
            nflag = 1;
            tpart = 0;
            continue;
        }
        if(nflag)
        {
            if(tpart == 0)
            {
                if([nums characterIsMember: ch] == YES)
                {
                    r.length++;
                    continue;
                }
                else if(ch == '\t' && r.length > 0)
                {
                    r.length++;
                    [theDoc setSelectedRange: r];
                    [theDoc insertText: @""];
                    n -= r.length;
                    i -= r.length;
                    nflag = 0;
                }
                else
                {
                    nflag = 0;
                    continue;
                }
            }
        }
    }
}
-(IBAction) doFindSelectedRange: (id) sender
{
    [theDoc scrollRangeToVisible: [theDoc selectedRange]];
}

-(void) selectAndScrollRange: (NSRange) theRange andMoveForward: (BOOL) move
{
    long ll = [[theDoc string] length];
    NSRange rr = theRange;
    
    if (rr.location >= ll)
    {
        rr.location = ll - 1 ;
        rr.length = 0;
    }
    if(rr.location+rr.length >= ll)
    {
        rr.length = ll - 1 - rr.location;
    }

    //select range
    [theDoc setSelectedRange: rr];
    
    //scroll range
    [theDoc scrollRangeToVisible: rr];
    
    
    //move forward
    if(move == YES) 
    {
	[theTabs selectFirstTabViewItem: self];
	[myWindow makeKeyAndOrderFront: self];
    }


}

- (void) moveForward
{
	[myWindow makeKeyAndOrderFront: self];
        [self updateCodeWindow];
}

- (IBAction) doFindBookmark: (id) sender
{
    int n;
    n = [[sender menu] indexOfItem: sender];
    [self selectAndScrollRange: 
	NSMakeRange([[bookmarkVault objectAtIndex: n - (BOOKMARKBASE + 1)] bmLocation] + 1,  9)
	andMoveForward: (BOOL) YES];
}
-(IBAction) moveWorkBenchForward: (id) sender
{
    [gWorkBench front];

}
-(IBAction) doFindButtons: (id) sender
{
    ctQChar *q;
    NSMutableArray *theButtonList;
    NSMutableString *ss;
    
     TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
     //clear existing macros
     [macroArray removeAllObjects];
     //[myToolbar clearButtons];
    //start search
    if([gWorkBench getInitFile] != nil)
        if([gWorkBench getInitFile] != [self getMyMWFile])
            [tc addFileToSearchList: [gWorkBench getInitFile]];
    
    [tc addFileToSearchList: [self getMyMWFile]]; (gCurrentDataSource = self);
    [tc startSearch];
    // read through and if it's a meta named bookmark...
    q = [[ctQChar alloc] init];
   theButtonList = [[NSMutableArray alloc] init];
    //go to eof
    while([tc scanNext: q] != ENDOFALLFILES)
    {
    //is it a !button
	if([q tokentype] == META && [[q buff] isEqualToString: @"button"] == YES)
    //break it up
	{
    //add it to the list
	    [theButtonList addObjectsFromArray: convertStringToArray([q extra], ',')];
	}
    }
    if([theButtonList count] == 0) return;
    ss = [[NSMutableString alloc] init];
    //trim the list
    FORALL(theButtonList)
    {
	//NSString *rrr = [NSString stringWithString: temp];
	[ss setString: temp];
	trimNSS(ss);
    
    //is it a quote? 
	if([ss isEqualToString: @"|"] == YES)
	{
	    [myToolbar addBar];
	}
        else if([ss startsWith: @"cmd::"])
        {
            [myToolbar addCmd: ss];
        }
	else if(ISQUOTE(ss))
	{
	//yes? then trim the quotes
	    trimCharNSS(ss, '\"');
	    if([myToolbar isButton: ss] == NO)
	    {
	//is it a button?
		[myToolbar addText: ss];
                [self addMacroItem: ss code: NO];
	    }
            else
                [self addMacroItem: ss code: NO];
	//no, then add it
	}
	else
	{
	    if([myToolbar isButton: ss] == NO)
	    {
    //is it already a button?
    //no, then add it with addItem
		[myToolbar addItem: ss];
                [self addMacroItem: ss code: YES];
	    }
            else
                [self addMacroItem: ss code: YES];
	}
    }
    ENDFORALL;
    [ss release];
    [tc release];
    [self rebuildDocMacros: nil];
}

//this is a combined bookmark and button scanner 
-(void) scanForMetas
{
   NSMenu *myMen;
    int i,n;
    ctQChar *q;
    bookmarkInfo *bm;
  NSMutableArray *theButtonList;
    NSMutableString *ss;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    //this is for the toolbar
   theButtonList = [[NSMutableArray alloc] init];
   //clear existing macros
   [macroArray removeAllObjects];
    //delete the menu options for bookmarks
    myMen = [ [[NSApp delegate] rebuildMenuItem] menu];
    n = [myMen numberOfItems];
    for(i = n-1; i > BOOKMARKBASE; i--)
    {
	[myMen removeItemAtIndex: i];
    }
    // go through and find all the !bookmarks
    // set the text
    if([gPrefBoss scanInitValue] && [gWorkBench getInitFile])
        if([gWorkBench getInitFile] != [self getMyMWFile])
            [tc addFileToSearchList: [gWorkBench getInitFile]];
    [tc addFileToSearchList: [self getMyMWFile]]; (gCurrentDataSource = self);
    [tc startSearch];
    // read through and if it's a meta named bookmark...
    q = [[ctQChar alloc] init];

    
    //[self setData];

    [bookmarkVault removeAllObjects];
//    while([tc readnext:q] != EOF)
    while([tc scanNext:q] != ENDOFALLFILES)
    {
    //until eof
    //if it's a tag

	if([q tokentype] == META)
	{
            if([[q buff] isEqualToString: @"mediafile"] == YES)
            {
#ifdef MULTIMEDIA
                [self loadMediaFile: [q extra]];
#endif
			;
            }
	    if([[q buff] isEqualToString: @"bookmark"] == YES)
	    {
		bm = [[bookmarkInfo alloc] init];
		[bm setLocation: [q where]];
		[bm setIdentifier: [q extra]];
	    

    //save location 
		[bookmarkVault addObject: bm];
            }
	    if( [[q buff] isEqualToString: @"button"] == YES)
	//break it up
	    {
	//add it to the list
		[theButtonList addObjectsFromArray: convertStringToArray([q extra], ',')];
	    }
	}
    }
    //put the bookmarks in the menu
    FORALL(bookmarkVault)
    {
	NSMenuItem *mm;
	
	mm = [[NSMenuItem alloc] init];
	[mm setTitle: [temp identifier]];
	[mm setAction: @selector(doFindBookmark:)];
	[myMen addItem: mm];
    }ENDFORALL;
    
    // handle the buttons
    if([theButtonList count]) 
    {
	ss = [[NSMutableString alloc] init];
	//trim the list
	FORALL(theButtonList)
	{
	    //NSString *rrr = [NSString stringWithString: temp];
	    [ss setString: temp];
	    trimNSS(ss);
	
	//is it a quote? 
	    	if([ss isEqualToString: @"|"] == YES)
	    {
		[myToolbar addBar];
	    }
                else if([ss startsWith: @"cmd::"])
            {
                    [myToolbar addCmd: ss];
            }
	    else if(ISQUOTE(ss))
	    {
	    //yes? then trim the quotes
		trimCharNSS(ss, '\"');
		if([myToolbar isButton: ss] == NO)
		{
	    //is it a button?
		    [myToolbar addText: ss];
                    [self addMacroItem: ss code: NO];
		}
	    //no, then add it
	    }
	    else
	    {
		if([myToolbar isButton: ss] == NO)
		{
	//is it already a button?
	//no, then add it with addItem
		    [myToolbar addItem: ss];
                    [self addMacroItem: ss code: YES];
		}
	    }
	}
	ENDFORALL;
	[ss release];
    }

    [q release];
    [tc release];
    [self rebuildDocMacros: nil];
    if([gPrefBoss autoColorValue])
    {
        [self doColorize: self];
        [self updateChangeCount: NSChangeCleared];//opening the document even if it changes code color should be dirty neutral

        
    }

}

-(void) renewBookmarkMenu
{
    NSMenu *myMen;
    int i,n;

    //delete the menu options
    myMen = [ [[NSApp delegate] rebuildMenuItem] menu];
    n = [myMen numberOfItems];
    for(i = n-1; i > BOOKMARKBASE; i--)
    {
	[myMen removeItemAtIndex: i];
    }
    FORALL(bookmarkVault)
    {
	NSMenuItem *mm;
	
	mm = [[NSMenuItem alloc] init];
	[mm setTitle: [temp identifier]];
	[mm setAction: @selector(doFindBookmark:)];
	[myMen addItem: mm];
    }ENDFORALL;
 
}

-(void) addMacroItem: (NSString *) ss code: (BOOL) aCode
{
    NSMutableDictionary *dd = [NSMutableDictionary dictionary];
    NSMutableString *mys = [NSMutableString string];
    NSString *itemIdentifier = [[ss copy] autorelease];
    if([itemIdentifier length] > 10)
    {
        [mys setString: [itemIdentifier substringToIndex: 3]];
        [mys appendString: @"É"];
        [mys appendString: [itemIdentifier substringFromIndex:  ([itemIdentifier length] - 7)]];
    }
    else
        [mys setString: itemIdentifier];
    [dd setObject: mys forKey: @"name"];
    [dd setObject: itemIdentifier forKey: @"text"];
    if(aCode) [dd setObject: @"C" forKey: @"type"];
    else [dd setObject: @"T" forKey: @"type"];
    [macroArray addObject: dd];
    
}
-(IBAction) handleDocMacro: (id) sender
{
    int n = [sender tag];
    NSDictionary *who;
    if(n < [macroArray count])
    {
        who = [macroArray objectAtIndex: n];
        if([[who objectForKey: @"type"] isEqualToString: @"C"] == YES)
        {
            [self applyCode: [who objectForKey: @"text"]];
        }
        else
            [self insertString: [who objectForKey: @"text"]];
    }

}
-(IBAction) clearDocMacros: (id) sender
{
    NSMenu *myMen = [[[NSApp delegate] docMacroMenu] submenu];
    int i, n;
    
    n = [myMen numberOfItems];
    for(i = n-1; i >= DOCMACROBASE; i--)
    {
	[myMen removeItemAtIndex: i];
    }
}
-(IBAction) rebuildDocMacros: (id) sender
{
    NSMenu *myMen = [[[NSApp delegate] docMacroMenu] submenu];
    [self clearDocMacros: nil];
    FORALL(macroArray)
    {
        NSMenuItem *mm;
        if(__i <= 9){
            mm = [[NSMenuItem alloc] initWithTitle:
                [temp objectForKey: @"name"]
                action: @selector(handleDocMacro:)
                keyEquivalent: [NSString stringWithFormat: @"%d", 9 - __i]];
            [mm setKeyEquivalentModifierMask:NSCommandKeyMask| NSControlKeyMask];//|NSCommandKeyMask
        }
        else
        {
            mm = [[NSMenuItem alloc] initWithTitle:
                [temp objectForKey: @"name"]
                    action: @selector(handleMacro:)
                     keyEquivalent: @""];
        }
        [mm setTag: __i];
	[myMen addItem: mm];
    }
    ENDFORALL;
    
}


-(IBAction) rebuildBookmarks: (id) sender
{
    NSMenu *myMen;
    int i,n;
    ctQChar *q;
    bookmarkInfo *bm;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];

    //delete the menu options
    myMen = [sender menu];
    n = [myMen numberOfItems];
    for(i = n-1; i > BOOKMARKBASE; i--)
    {
	[myMen removeItemAtIndex: i];
    }
    // go through and find all the !bookmarks
    // set the text
    [tc addFileToSearchList: [self getMyMWFile]]; (gCurrentDataSource = self);
    
    // read through and if it's a meta named bookmark...
    q = [[ctQChar alloc] init];

    
    [tc startSearch];

    [bookmarkVault removeAllObjects];
    while([tc scanNext:q] != ENDOFFILE)
    {
    //until eof
    //if it's a tag

	if([q tokentype] == META)
	{
	    if([[q buff] isEqualToString: @"bookmark"] == YES)
	    {
		bm = [[bookmarkInfo alloc] init];
		[bm setLocation: [q where]];
		[bm setIdentifier: [q extra]];
	    

    //save location 
		[bookmarkVault addObject: bm];
	    }
	}
    }
    //put them in the menu
    FORALL(bookmarkVault)
    {
	NSMenuItem *mm;
	
	mm = [[NSMenuItem alloc] init];
	[mm setTitle: [temp identifier]];
	[mm setAction: @selector(doFindBookmark:)];
	[myMen addItem: mm];
    }ENDFORALL;
    
    [q release];
    [tc release];

}

-(IBAction) doRemoveCodesFromSelection: (id) sender
{
    NSRange n, ll, r;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    NSMutableArray *aa= [[NSMutableArray alloc] init];
    ctQChar *qq;
    int rslt; 
    int currLoc, l;
    unsigned r1;
    r1 = 0;
    //get the boundaries
    n = [theDoc selectedRange];
    if(n.length == 0) return;
    r1 = n.length;
    //set things up
    [tc addFileToSearchList: [self getMyMWFile]];
   //clearSearchList();
   [tc startSearch];
   qq = [[ctQChar alloc] init];
     //set start location
     [tc setCharLocation: n.location ];
     do {
         rslt = [tc scanNext: qq];
         r = [qq range];
         switch(rslt)
        {
             case META:
             case TOKEN:
             case ENDTOKEN:
                 if(r.location >= n.location && r.location < n.location + n.length)
                 {
                     [aa insertObject: [[[MWRange alloc] initWithRange: r] autorelease]
                              atIndex: 0];
                     r1 -= r.length;
                 }
                     break;
             default:;
            }
          
         //scan next
         //if it is meta, tag or endtag
         //save the location in a stack
         
     }
     while(r.location < n.location + n.length && rslt != ENDOFFILE && r.location + r.length <= n.location+n.length);
     
     FORALL(aa)
    {
         NSRange rrr;
         rrr = [temp range];
         [theDoc setSelectedRange: rrr];
         [theDoc insertText: @""];
     }
     ENDFORALL;
     [theDoc setSelectedRange: NSMakeRange(n.location, r1)];
     [aa release];
     [tc release];
     [qq release];
#ifdef oldDeleteTextInRange     
         [theDoc setSelectedRange: NSMakeRange(n.location + n.length, 0)];
     l = 0;
     currLoc = n.location + n.length + 1;
     for(;;)
     {
    //loop til out of loop or hadn't move
    
    //find a code 
	[self doFindCurrentCode: self];
	ll = [theDoc selectedRange];
	if(ll.location == currLoc) break;
	if(ll.location <= n.location) break;
	else
	{
    //remove it
	    [theDoc insertText: @""];
	    currLoc = ll.location;
	}
    }
    [theDoc setSelectedRange: NSMakeRange(n.location, 0)];
#endif
}

-(IBAction) doFindNextCode: (id) sender
{
     ctQChar *q;
     int aloc, bloc, l;
        NSRange n;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    
   q = [[ctQChar alloc] init];
    
    gCurrentDataSource = self;
   [ tc  addFileToSearchList: [self getMyMWFile]]; 
   [tc  startSearch];
    //set up system
    //get selection
    //save location
    n = [theDoc selectedRange];
    l = [[theDoc string] length];
    if(n.location > l - 1) return;
 
    //set up cursor one character back
    aloc = n.location + n.length;
    [tc setCharLocation: aloc];
    //loop
    while(aloc < l - 1)
    {
    //save location A read a character save location B
	aloc = [tc getCharLocation];
    //is it a code?
	[tc readnext: q];
	bloc = [tc getCharLocation];
	if([q tokentype] == TOKEN || [q tokentype] == ENDTOKEN
	    || [q tokentype] == META)
    //Yes select from A-B
	{
	    [theDoc setSelectedRange: NSMakeRange(aloc, bloc - aloc)];
	    [theDoc scrollRangeToVisible: NSMakeRange(aloc, bloc - aloc)];

	    [q release];
	    return;
	}
	//[tc setCharLocation: (aloc + 1)];
    }
    [q release];
    [tc release];
    //else goto A-1
    

}


-(IBAction) doFindCurrentCode: (id) sender
{
     ctQChar *q;
     int aloc, bloc;
        NSRange n;
     TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
   
   q = [[ctQChar alloc] init];
    
   [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    //set up system
    //get selection
    //save location
    n = [theDoc selectedRange];
    if(n.location <= 0) return;
 
    //set up cursor one character back
    [tc setCharLocation: (aloc = n.location - 1)];
    //loop
    while(aloc >= 0)
    {
    //save location A read a character save location B
	aloc = [tc getCharLocation];
    //is it a code?
	[tc readnext: q];
	bloc = [tc getCharLocation];
	if([q tokentype] == TOKEN || [q tokentype] == ENDTOKEN
	    || [q tokentype] == META)
    //Yes select from A-B
	{
            if(aloc > 0)
            {
                int slashCnt;
                int sindex;
                
                slashCnt = 0;
                sindex = aloc - 1;
                while([tc readCharAtIndex: sindex] == '\\')
                {
                    slashCnt++;
                    sindex--;
                    if(sindex < 0) break;
                }
                if( slashCnt % 2 == 1)
                {
                    aloc--;
                    [tc setCharLocation: aloc];
                    continue;
                }
            }
                
	    [theDoc setSelectedRange: NSMakeRange(aloc, bloc - aloc)];
	    [theDoc scrollRangeToVisible: NSMakeRange(aloc, bloc - aloc)];

	    [q release];
	    return;
	}
	aloc--;
	[tc setCharLocation: aloc];
    }
    [q release];
    //else goto A-1
    
    [tc release];
}

-(IBAction) doDeleteCodePair: (id) sender
{
     ctQChar *q;
     int aloc, bloc;
     int fwdFlag;
        NSRange n;
    NSMutableString *myname = [[NSMutableString alloc] init];
    NSMutableString *mycode = [[NSMutableString alloc] init];
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    
    fwdFlag = 1;
   q = [[ctQChar alloc] init];
    [self setReanalysisState: NO];
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    //set up system
    //get selection
    //save location
    [self doFindCurrentCode: nil];
    n = [theDoc selectedRange];
    [tc setCharLocation: (n.location)];
    //get the first code
    [tc readnext: q];
    if([q tokentype] == TOKEN)
    {
	[myname setString: [q buff]];
	[mycode setString: [q coder]];
    }
    else if ([q tokentype] == ENDTOKEN)
    {
	[myname setString: [q buff]];
	[mycode setString: [q coder]];

	fwdFlag = 0;
    }
    else
    {
	[q release];
	[myname release];
	[mycode release];
	[tc release];
        if(gWorkBench != nil) 
            [self setReanalysisState: [gWorkBench reanalysisMode]];
    	return;
    }
    if(fwdFlag)
    {
	//get the current code
	bloc = [tc getCharLocation];
	while([tc readnext: q] != EOF)
	{
	    aloc = bloc; 
	    if([q tokentype] == ENDTOKEN)
		if([[q buff] isEqualToString: myname] == YES && [[q coder] isEqualToString: mycode])
		{
		    bloc = [tc getCharLocation];
		    //kill the end
		    [theDoc setSelectedRange: NSMakeRange(aloc, bloc - aloc)];
		    [theDoc insertText: @""];
                    [self adjustResultDocsAt: aloc+1 forLength: -(bloc - aloc)];
		    //kill the start
		    [theDoc setSelectedRange: n];
                    [self adjustResultDocsAt: n.location + 1 forLength: - n.length];
		    [theDoc insertText: @""];
                    
		    // clean up
		    [q release];
		    [myname release];
		    [tc release];
                    if(gWorkBench != nil) 
                        [self setReanalysisState: [gWorkBench reanalysisMode]];
		    return;
		}
		
	    bloc = [tc getCharLocation];
	}
    }
    else
    {
	[tc setCharLocation: (bloc = n.location - 1)];
	while(bloc >= 0)
	{
	    [tc readnext: q];
	    aloc = [tc getCharLocation];
	    if([q tokentype] == TOKEN)
	    {
		if([[q buff] isEqualToString: myname] == YES && [[q coder] isEqualToString: mycode] == YES)
		{
		    [theDoc setSelectedRange: n];
		    [theDoc insertText: @""];
		    [theDoc setSelectedRange: NSMakeRange(bloc, aloc - bloc)];
		    [theDoc insertText: @""];
                    [self adjustResultDocsAt: n.location + 1 forLength: - n.length];
                    [self adjustResultDocsAt: bloc+1 forLength: -(aloc - bloc)];
		    [q release];
		    [myname release];
		    [tc release];
                    if(gWorkBench != nil) 
                        [self setReanalysisState: [gWorkBench reanalysisMode]];
                    
                    return;
		}
	    }
	    bloc--;
	    [tc setCharLocation: bloc];
	}
	//get current location
	//loop backwards
	//if it's a TOKEN
	//does it match
	//get the loc's and delete
    }
    [q release];
    [myname release];
    [mycode release];
    [tc release];
    if(gWorkBench != nil) [self setReanalysisState: [gWorkBench reanalysisMode]];
    
}

-(IBAction) doFindMate: (id) sender
{
     ctQChar *q;
     int aloc, bloc;
     int fwdFlag;
        NSRange n;
    NSMutableString *myname = [[NSMutableString alloc] init];
    NSMutableString *mycname = [[NSMutableString alloc] init];
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];

    fwdFlag = 1;
   q = [[ctQChar alloc] init];
    
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    //set up system
    //get selection
    //save location
    [self doFindCurrentCode: nil];
    n = [theDoc selectedRange];
    [tc setCharLocation: n.location];
    //get the first code
    [tc readnext: q];
    if([q tokentype] == TOKEN)
    {
	[myname setString: [q buff]];
	[mycname setString: [q coder]];
    }
    else if ([q tokentype] == ENDTOKEN)
    {
	[myname setString: [q buff]];
	[mycname setString: [q coder]];
	fwdFlag = 0;
    }
    else
    {
	[q release];
	[myname release];
	[mycname release];
	[tc release];
	return;
    }
    if(fwdFlag)
    {
	//get the current code
	bloc = [tc getCharLocation];
	while([tc readnext: q] != EOF)
	{
	    aloc = bloc;
	    if([q tokentype] == ENDTOKEN)
		if([[q buff] isEqualToString: myname] == YES && [[q coder] isEqualToString: mycname] == YES)
		{
		    bloc = [tc getCharLocation];
		    //select the end
		    [theDoc setSelectedRange: NSMakeRange(aloc, bloc - aloc)];
		    [theDoc scrollRangeToVisible: NSMakeRange(aloc, bloc - aloc)];
		    // clean up
		    [q release];
		    [myname release];
		    [tc release];
		    return;
		}
		
	    bloc = [tc getCharLocation];
	}
    }
    else
    {
	[tc setCharLocation: (bloc = n.location - 1)];
	while(bloc >= 0)
	{
	    [tc readnext: q];
	    aloc = [tc getCharLocation];
	    if([q tokentype] == TOKEN)
	    {
		if([[q buff] isEqualToString: myname] == YES && [[q coder] isEqualToString: mycname] == YES)
		{
		    [theDoc setSelectedRange: NSMakeRange(bloc, aloc - bloc)];
		    [theDoc scrollRangeToVisible: NSMakeRange(bloc, aloc - bloc)];
		    [q release];
		    [myname release];
		    [tc release];
		    return;
		}
	    }
	    bloc--;
	    [tc setCharLocation: bloc];
	}
	//get current location
	//loop backwards
	//if it's a TOKEN
	//does it match
	//get the loc's and delete
    }
    [q release];
    [myname release];
    [mycname release];
    [tc release];

    
}

-(IBAction) requestCodeDefinition: (id) sender
{
   int who,t;
   NSString *theCode;
   NSMutableString *theDef;
    //get the string

    t = [theTabs indexOfTabViewItem: [theTabs selectedTabViewItem]];
    if(t == 0)
        who = [theCodeList selectedRow];
    else
        who = [searchCodeList selectedRow];
    if(who >= 0)
    {
        theCode = [[gWorkBench getHotCodeList] objectAtIndex: who];
    }
    else return;


    //ask for definition
    theDef = [gWorkBench getDefinition: theCode];
    if(!theDef) {NSWARNING(@"Need to establish a central code file"); return;}
    //if it exists retain and display it
    [theDef retain];
    NSRunAlertPanel(theCode, theDef, @"Ok", nil, nil);
    //release it
    [theDef release];
}
-(IBAction) checkForPairs: (id) sender
{
    NSMutableArray *codeHolder;
    ctQChar *q;
    ctTagInfo *ti;
    int myloc;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] initWithFileAndStart: [self getMyMWFile]];
    ti = nil;
    
    q = [[ctQChar alloc] init];
    
    codeHolder = [[NSMutableArray alloc] init];
    myloc = [tc getCharLocation];
    while([tc scanNext: q] != ENDOFFILE)
    {
    //until eof
    //if it's a tag

	if([q tokentype] == TOKEN)
	{
	    [codeHolder addObject: [[[ctTagInfo alloc] initWithName: [q buff] location: [q where] coder: [q coder]] autorelease]];
	}
	else if([q tokentype] == ENDTOKEN)
	{
	    FORALL(codeHolder)
	    {
		ti = nil;
		if([[temp name] isEqualToString: [q buff]] == YES && [[temp coder] isEqualToString: [q coder]] == YES)
		{
		    ti = temp;
		    break;
		}
	    }ENDFORALL;
	    if(ti)
		[codeHolder removeObject: ti];
	    else
	    {
		[theDoc setSelectedRange: NSMakeRange(myloc, [tc getCharLocation] - myloc)];
		
		//scroll range
		[theDoc scrollRangeToVisible: NSMakeRange(myloc, [tc getCharLocation] - myloc)];
		[q release];
		[codeHolder release];
		[tc release];
		return;
	    
	    }
	}
	myloc = [tc getCharLocation];
    }
    if([codeHolder count])
    {
	    //select range
	ti = [codeHolder objectAtIndex: 0];
	[theDoc setSelectedRange: NSMakeRange([ti location]+1, [[ti name] length])];
	
	//scroll range
	[theDoc scrollRangeToVisible: NSMakeRange([ti location]+1, [[ti name] length])];
  
    }
    else
        NSMESSAGE(@"No unmatched code pairs found");
    [q release];
    [codeHolder release];
    [tc release];
		

}

-(IBAction) checkForNested: (id) sender
{
    NSMutableArray *codeHolder;
    ctQChar *q;
    int errFlg;
    ctTagInfo *ti;
      TAMSCharEngine *tc = [[TAMSCharEngine alloc] initWithFileAndStart: [self getMyMWFile]];
      ti = nil;
    errFlg = 0;
    q = [[ctQChar alloc] init];
    
     codeHolder = [[NSMutableArray alloc] init];

    while([tc scanNext: q] != ENDOFFILE)
    {
    //until eof
    //if it's a tag

	if([q tokentype] == TOKEN)
	{
	    if([codeHolder count])
	    {
		FORALL(codeHolder)
		{
		    if([[temp name] isEqualToString: [q buff]] == YES)
		    {
			[theDoc setSelectedRange: NSMakeRange([q where]+1, [[q buff] length])];
			[theDoc scrollRangeToVisible: NSMakeRange([q where]+1, [[q buff] length])];
			[q release];
			[codeHolder release];
			return;
		    }
		}ENDFORALL;
		[codeHolder addObject: [[[ctTagInfo alloc] initWithName: [q buff] location: [q where] coder: [q coder]] autorelease]];
	    }
	    else
		[codeHolder addObject: [[[ctTagInfo alloc] initWithName: [q buff] location: [q where] coder: [q coder]] autorelease]];
	}
	else if([q tokentype] == ENDTOKEN)
	{
	    FORALL(codeHolder)
	    {
		ti = nil;
		if([[temp name] isEqualToString: [q buff]] == YES && [[temp coder] isEqualToString: [q coder]] == YES)
		{
		    ti = temp;
		    break;
		}
	    }ENDFORALL;
	    if(ti)
		[codeHolder removeObject: ti];
	}

    }
    NSMESSAGE(@"No nested codes found");
    [q release];
    [codeHolder release];
    [tc release];
		

}
#ifdef XXYY
- (void)setDocumentEdited:(BOOL)flag {
    if (flag != isDocumentEdited) {
        isDocumentEdited = flag;
        [[self window] setDocumentEdited:isDocumentEdited];
        if (transientDocument == self) transientDocument = nil;
    }
    if (!isDocumentEdited) changeCount = 0;
}

- (BOOL)isDocumentEdited {
    return isDocumentEdited;
}
#endif
/* this actually searches for results */

-(IBAction) searchForCode: (id) Sender
{
    myResults *aa;
    NSDocumentController *who;
    NSMutableString *myLimitStr = [[NSMutableString alloc] init];
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init]; //initWithFileAndStart: [self getMyMWFile]];
    //start search
    if([initFileSearchSwitch state] == NSOnState && [gWorkBench getInitFile])
        [tc addFileToSearchList: [gWorkBench getInitFile]];
    [tc addFileToSearchList: [self getMyMWFile]]; (gCurrentDataSource = self);
    [tc startSearch];    //get the flags
    if([rawButton state] == NSOnState) rawF = 1; else rawF = 0;
    if([exactButton state] == NSOnState) exactF = 1; else exactF = 0;
    if([emptyButton state] == NSOnState) emptyF = 1; else emptyF = 0;
    if([sectionButton state] == NSOnState) sectionF = 1; else sectionF = 0;
    nonRegexCharF = regexCharF = 0; //for the moment it has no interface for single files
    if([simpleButton state] == NSOnState)
    {
	int i,ln;
	int sflg;
	unichar c;
	
	sflg = 1;
	[myLimitStr setString: [theLimitString stringValue]];
	trimNSS(myLimitStr);
	if([myLimitStr isEqualToString: @""])
	    simpleF = sflg;
	else
	{
	    ln = [myLimitStr length];
	    for(i = 0; i < ln; i++)
	    {
		c = [myLimitStr characterAtIndex: i];
		//if(c == '*' || c == '+' || c == ',')
		if( c == '+' )//|| c == ',')
		{
		    sflg = 0;
		    break;
		}
	    }
	    simpleF = sflg;
	    if(simpleF)
		[simpleButton setState: NSOnState];
	    else
		[simpleButton setState: NSOffState];
	}
    }
    else
    {
	simpleF = 0;
	[myLimitStr setString: [theLimitString stringValue]];
	trimNSS(myLimitStr);
        //need to drop this for unlimited non-simple searches
//	if([myLimitStr isEqualToString: @""])
//	    simpleF = 1;
	if(simpleF)
	    [simpleButton setState: NSOnState];
	else
	    [simpleButton setState: NSOffState];
	
    }
    [myLimitStr release];
    //make me the current data source
    [tc setGCurrentDataSource: self];
    

    //find the controller
    who = [NSDocumentController sharedDocumentController];
    //make the window
    [who setShouldCreateUI: YES];
    //ans = [[myResults alloc] init];
    //[who addDocument: ans];
    aa = [who openUntitledDocumentOfType: @"TAMS Result" display: YES];
    [aa setGWorkBench: gWorkBench];
    [gWorkBench registerResult: aa];
    [aa setCharEngine: tc];
    [aa executeTAMS];
    [aa retain];
}

-(NSString *) codersList
{
    return [coderIDView stringValue];
}
-(void) setGWorkBench: (id) who { gWorkBench = who;}
-(void) setMWFile: (MWFile *) who {myFID = who;}
-(void) setTitleFromFile
{
    if([[self getMyMWFile] hasFile])
    {
        [myWindow setTitle: [[self getMyMWFile] name]];
    }
}
-(MWFile *) getMyMWFile {return myFID;}

-(void) performClose
{
    [myWindow performClose: self];
}
- (void) document:(NSDocument *)doc didSave:(BOOL)didSave contextInfo:(void *)contextInfo
{
    MWFile *mw;
    mw = [self getMyMWFile];
    if(didSave == YES)
    {

	[myWindow setDocumentEdited: NO];
	[self updateChangeCount: NSChangeCleared];
        [mw setOpenFile: self]; //reset the path
        [mw setHasFile: YES];
	NSLog(@"doc path = %@\n", [mw path]);
        if(gWorkBench != nil) [gWorkBench setDirty];
    }

}
-(IBAction) saveDocument: (id) Sender
{


    
    //[self saveToFile:nil saveOperation: NSSaveAsOperation delegate: self didSaveSelector:@selector(document:didSave:contextInfo:) contextInfo:nil ];
    if([self fileName]) [super saveDocument: nil];
	else
    [self saveDocumentWithDelegate: self didSaveSelector: @selector(document:didSave:contextInfo:) contextInfo: nil];
    return;
    /*
    [super saveDocument: self];
    path = [self fileName];
    [gWorkBench setDirty];//kludge since we're too lazy to make our own save Doc
    if([self fileName])
        if([[mw path] isEqualToString: [self fileName]] ==NO)
        {
            [mw setOpenFile: self]; //reset the path
             [mw setHasFile: YES];
           [gWorkBench setDirty];
        }
    */
}
-(IBAction) saveDocumentAs: (id) Sender
{

    [self runModalSavePanelForSaveOperation: NSSaveAsOperation delegate: self didSaveSelector: @selector(document:didSave:contextInfo:) contextInfo: nil];
        //[self saveDocumentWithDelegate: self didSaveSelector: @selector(document:didSave:contextInfo:) contextInfo: nil];
    return;
    /*
    [super saveDocumentAs: self];
    mw = [self getMWFile];
    [gWorkBench setDirty];//kludge since we're too lazy to make our own save Doc
    if([self fileName])
        if([[mw path] isEqualToString: [self fileName]] ==NO)
        {
            [mw setOpenFile: self]; //reset the path
             [mw setHasFile: YES];
            [gWorkBench setDirty];
        }
    */
}
#ifdef OLDSAVEROUTINE
-(IBAction) saveDocument: (id) Sender
{

    MWFile *mw;
    [super saveDocument: self];
    mw = [self getMyMWFile];
    if([[mw path] isEqualToString: [self fileName]] ==NO)
    {
        [mw setOpenFile: self]; //reset the path
        [gWorkBench setDirty];
    }

}
-(IBAction) saveDocumentAs: (id) Sender
{

    MWFile *mw;
    [super saveDocumentAs: self];
    mw = [self getMyMWFile];
    if([[mw path] isEqual: [self fileName]] ==NO)
    {
        [mw setOpenFile: self]; //reset the path
        [gWorkBench setDirty];
    }

}
#endif
-(IBAction) showCodeBrowser: (id) Sender
{
    [gWorkBench showCodeBrowser: self];
}
-(IBAction) niceClose: (id) Sender
{
    [myWindow performClose: self];
}


-(NSTextView*) myTextView
{
    return theDoc;
}

-(IBAction) doQuoteBraces: (id) Sender
{
    NSString *ss = [theDoc string];
    unsigned l,st,cnt;
    unichar c;
    int i;
    NSRange r;
    
    r = [theDoc selectedRange];
    if(r.length == 0)
    {
        st = 0;
        l = [ss length];
    }
    else
    {
        st = r.location;
        l = r.length + r.location;
    }
    cnt = 0;
    for (i = l - 1; i >= st; i--)
    {
        c = [ss characterAtIndex: i];
        if (c == '{')
        {
            if(i > 0)
            {
                if([ss characterAtIndex: i - 1] != '\\')
                {
                    [theDoc setSelectedRange: NSMakeRange(i,0)];
                    [theDoc insertText: @"\\"];
                    cnt++;
                }
            }
            else
            {
                [theDoc setSelectedRange: NSMakeRange(i,0)];
                [theDoc insertText: @"\\"];
                cnt++;
            }
        }
        else if (c == '}')
        {
            if(i > 0)
            {
                if([ss characterAtIndex: i - 1] != '\\')
                {
                    [theDoc setSelectedRange: NSMakeRange(i,0)];
                    [theDoc insertText: @"\\"];
                    cnt++;
                }
            }
            else
            {
                [theDoc setSelectedRange: NSMakeRange(i,0)];
                [theDoc insertText: @"\\"];
                cnt++;
            }
        }
                
    }
    [theDoc setSelectedRange: NSMakeRange(r.location, r.length+cnt)];
}
-(IBAction) doToggleReanalysisMode: (id) sender
{
    if(gWorkBench)
    {
        [gWorkBench doToggleReanalysisMode: sender];
    }
}

-(BOOL) validateMenuItem: (NSMenuItem *) menuItem
{
    NSString *name;
    //get rid of paste
    name = [menuItem title];
    if(([name isEqualToString: [[theDoc undoManager] undoMenuItemTitle]]))
    {
        //NSLog(@"Testing");
    }
    if(gWorkBench != nil)
    {
        if([gWorkBench reanalysisMode] == YES)
        {
            if([name isEqualToString: @"Cut"] ||
                [name isEqualToString: @"Paste"] ||
                ([name rangeOfString: @"Undo"].location) != NSNotFound ||
                ([name rangeOfString: @"Redo"].location) != NSNotFound ||
                [name isEqualToString: @"Clear"] ||
                [name isEqualToString: @"Escape braces"] ||
                [name isEqualToString: @"Wrap and line number"] ||
                [name isEqualToString: @"{!bookmark X}"] ||
                [[[menuItem menu] title] isEqualToString: @"Insert metatag"] ||
                [name isEqualToString: @"Insert date-time"] ||
                [name isEqualToString: @"Remove all bookmarks"]
                
                )
            {
                return NO;
            }
        }
    }
    return [super validateMenuItem: menuItem];
}
-(void) loadAllCodes: (id) sender
{
    if(gWorkBench) [gWorkBench loadAllCodes: sender];
}
-(void) loadCodeSet: (id) sender
{
    if(gWorkBench != nil) [gWorkBench loadCodeSet: sender];
}
-(IBAction) editCodeSet: (id) Sender
{
    if(gWorkBench != nil)
    {
        if(![gPrefBoss detachedSheetValue])
            [self moveWorkBenchForward: self];
        [gWorkBench editCodeSet: Sender];
    }

}
-(void) scrollToTop
{
    [theDoc scrollRangeToVisible: NSMakeRange(0,0)];
    [theDoc setSelectedRange: NSMakeRange(0,0)];
}
-(IBAction) doDotGraph: (id) sender
{
    if(gWorkBench != nil)
    {
        [gWorkBench doDotGraph: self];
    }
}
#ifdef MULTIMEDIA
-(IBAction) setMovieTime: (id) sender;
{
    long tmValue, scale;
    double tm;
    NSString *ss,*tt;
    NSRange r;
    if(myMovie == nil ) return;
    
    r=  [theDoc selectedRange];
    if (r.length == 0) return;
    ss = [theDoc string];
    tt = [ss substringWithRange: r];
    scale = (long) GetMovieTimeScale( [myMovie QTMovie]);
    if(isHHMMSS(tt))
    {
        tmValue = hhmmss2sec(tt) * scale;
    }
    else
    {
        tm = [tt doubleValue];
        tmValue = tm * scale;
    }
    SetMovieTimeValue([myMovie QTMovie], tmValue);
    
#ifdef scantimeformat    
    long scale;
    NSRange n, ll, r;
    TAMSCharEngine *tc;
    ctQChar *qq;
    int rslt; 
    double tm;
    long tmValue;
    
    if(myMovie == nil ) return;
    tc = [[TAMSCharEngine alloc] init];
    //get the boundaries
    n = [theDoc selectedRange];
    //set things up
    [tc addFileToSearchList: [self getMyMWFile]];
    //clearSearchList();
    [tc startSearch];
    qq = [[ctQChar alloc] init];
    //set start location
    [tc setCharLocation: n.location ];
    scale = GetMovieTimeScale( [myMovie QTMovie]);

    while((rslt = [tc scanNext: qq]) != ENDOFFILE)
    {
        if(rslt == META)
        {
            if([[qq buff] isEqualToString: @"time"] == YES)
            {
                tm = [[qq extra] doubleValue];
                tmValue = (long) tm * scale;
                SetMovieTimeValue([myMovie QTMovie], tmValue);
                [qq release]; [tc release]; return;
            }
        }
    }
    [qq release];
    [tc release];
    return;
#endif
}
-(void) ConvertMovieTimeToHHMMSS: (BOOL) hhmmssFormat
{
    long scale, l;
    double mt;
    NSRange rr;
    NSString *ss;
    NSMutableArray *tLoc = [[NSMutableArray alloc] init];
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    ctQChar *q;
    NSRange r,s;
    NSString *timeCode;
    int tt, i, n;
    BOOL timeMode, hfmt;
    double t1;
    NSString *theDocString;
    
    rr = [theDoc selectedRange];
    mt = GetMovieTime([myMovie QTMovie], nil) / (double)scale;
    timeCode = [gPrefBoss getAVCode];
    if(!gWorkBench) return;
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    
    q = [[ctQChar alloc] init];
    
    timeMode = NO;
    r = NSMakeRange(0,0);
    while((tt = [tc scanNext: q]) != ENDOFFILE)
    {
        //scan through doc
        if(tt == TOKEN)
        {
            if([[q buff] isEqualToString: timeCode])
            {
                timeMode = YES;
            }
            else 
                timeMode = NO;
        }
        else if(timeMode == YES)
        {
            if(tt == CHAR)
            {
                hfmt = isHHMMSS([q buff]);
                if(hhmmssFormat)
                {
                    if(hfmt == NO) //this is one we want
                        [tLoc addObject: [[[MWRange alloc] initWithRange: [q range]] autorelease]];
                }
                else
                {
                    if(hfmt == YES)
                        [tLoc addObject: [[[MWRange alloc] initWithRange: [q range]] autorelease]];
                       
                }
                  
            }
            timeMode = NO;
        }
        else timeMode = NO;                
    }
    [tc release];
    [q release];
    n = [tLoc count];
    theDocString = [theDoc string];
    for(i = n-1; i >= 0; i--)
    {
        NSString *newTime, *oldTime;
        MWRange *w;
        w = [tLoc objectAtIndex: i];
        oldTime = [theDocString substringWithRange: [w range]];
        if(hhmmssFormat)
            newTime = sec2hhmmss((unsigned) [oldTime doubleValue]);
        else
            newTime = [NSString stringWithFormat: @"%u", hhmmss2sec(oldTime)];
        [theDoc setSelectedRange: [w range]];
        [theDoc insertText: newTime];
        
    }
    [tLoc release];
    [theDoc setSelectedRange: rr];
}

-(IBAction) convertSec2HHMMSS: (id) sender
{
    [self ConvertMovieTimeToHHMMSS: YES];
}
-(IBAction) convertHHMMSS2Sec: (id) sender
{
    [self ConvertMovieTimeToHHMMSS: NO];
}

-(IBAction) findMovieTime: (id) sender
{
    long scale, l;
    double mt;
    NSRange rr;
    NSString *ss;
    if(myMovie == nil ) return;
    scale = GetMovieTimeScale( [myMovie QTMovie]);
    if([gPrefBoss codeAV])
    {
        TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
        ctQChar *q;
        NSRange r,s;
        NSString *timeCode;
        int tt;
        BOOL timeMode;
        double t1;
        
        rr = [theDoc selectedRange];
        mt = GetMovieTime([myMovie QTMovie], nil) / (double)scale;
        timeCode = [gPrefBoss getAVCode];
        if(!gWorkBench) return;
        [tc addFileToSearchList: [self getMyMWFile]];
        [tc startSearch];
        
        q = [[ctQChar alloc] init];
        
        timeMode = NO;
        r = NSMakeRange(0,0);
        while((tt = [tc scanNext: q]) != ENDOFFILE)
        {
            //scan through doc
            if(tt == TOKEN)
            {
                if([[q buff] isEqualToString: timeCode])
                {
                    timeMode = YES;
                }
                else 
                    timeMode = NO;
            }
            else if(timeMode == YES)
            {
                if(tt == CHAR)
                {
                    if(isHHMMSS([q buff]))
                    {
                        NSString *tttt;
                        tttt = [q buff];
                        t1 = hhmmss2sec(tttt);
                    }
                    else
                        t1 = [[q buff] doubleValue];
                    if(t1 > mt)
                    {
                        //Select and scroll
                        [tc release];
                        [q release];
                        [theDoc setSelectedRange: r];
                        [theDoc scrollRangeToVisible: r];
                        return;
                    }
                    else
                        r = [q range];
                    
                }
                timeMode = NO;
            }
            else timeMode = NO;                
        }
        [tc release];
        [q release];
        NSWARNING(@"Time code not found");
    }
}
-(NSString *) getMovieTimeString
{
    long scale;
    double timeSpot;
    scale = GetMovieTimeScale( [myMovie QTMovie]);
    timeSpot =  GetMovieTime([myMovie QTMovie], nil) / (double)scale;
    if([gPrefBoss timeFormatHHMMSS] == 1)
    {
        return sec2hhmmss((unsigned) timeSpot);
    }
    else
        return [NSString stringWithFormat: @"%.2lf", timeSpot];
}

-(IBAction) insertMovieTime: (id) sender
{
    long scale, l;
    NSRange rr;
    NSString *ss;
    if(myMovie == nil ) return;
    scale = GetMovieTimeScale( [myMovie QTMovie]);
    if([gPrefBoss codeAV])
    {
        rr = [theDoc selectedRange];
        ss = [NSString stringWithFormat: @"{%@}%@{/%@}", [gPrefBoss getAVCode], [self getMovieTimeString], [gPrefBoss getAVCode]];
        l = [ss length];
        [theDoc insertText: ss];
        if([gPrefBoss autoColorValue]) [self doColorizeRange: NSMakeRange(rr.location, l)]; //this may slow things down too much
    }
    else
        [theDoc insertText: [NSString stringWithFormat: @"%@", [self getMovieTimeString]]];
        
}

-(IBAction) backSpaceMovieTime: (id) sender
{
    long scale,ct;
    long bs;
    long newloc;
    bs  = [gPrefBoss getAVBackspace];
    if(myMovie == nil ) return;
    scale = GetMovieTimeScale( [myMovie QTMovie]);
    ct =  GetMovieTime([myMovie QTMovie], nil);
    newloc =  ct - (scale * bs);
    if(newloc < 0L) newloc = 0L;
    SetMovieTimeValue([myMovie QTMovie], newloc);

}
-(IBAction) fwdSpaceMovieTime: (id) sender
{
    long scale,ct;
    long bs;
    long newloc;
    bs  = [gPrefBoss getAVBackspace];
    if(myMovie == nil ) return;
    scale = GetMovieTimeScale( [myMovie QTMovie]);
    ct =  GetMovieTime([myMovie QTMovie], nil);
    newloc =  ct + (scale * bs);
    if(newloc > duration) newloc = duration;
    SetMovieTimeValue([myMovie QTMovie], newloc);
    
}
-(IBAction) stopMovie: (id) sender
{
    [myMovieView stop: nil];
}
-(IBAction) startMovie: (id) sender
{
    if([myMovieView isPlaying] == YES)
    {
        [myMovieView stop: nil];
        [stopStartButton setState: NSOffState];
    }
    else
    {
        if([gPrefBoss autoBackspace] == 1) [self backSpaceMovieTime: nil];
        [myMovieView start: nil];
        [stopStartButton setState: NSOnState];
    }
}
-(void) moviePanelDidEnd: (NSOpenPanel *) sheet returnCode: (int) returnCode contextInfo: (void*) contextInfo
{
    NSRange rr;
    if(returnCode == NSOKButton)
    {
        NSString *what;
        NSArray *who;
        //EnterMovies();

        who = [sheet filenames];
        if([who count] != 1) return;
        rr = [theDoc selectedRange];
        what = [who objectAtIndex: 0];
        if(myMovie != nil) [myMovie release];
        
        myMovie = [[NSMovie alloc] initWithURL: [NSURL fileURLWithPath: what] byReference: YES];
        if(myMovie != nil)
        {
            NSString *newTag;
            duration = GetMovieDuration([myMovie QTMovie]);
            [myMovieView showController: YES adjustingSize: YES];
            [movieTitle setStringValue: [what lastPathComponent]];
            [myMovieView setMovie: myMovie];
            [theDoc setSelectedRange: NSMakeRange(0,0)];
            newTag = [NSString stringWithFormat: @"{!mediafile %@}", what];
            [theDoc insertText: newTag ];
            [theDoc setSelectedRange: NSMakeRange(rr.location + [newTag length], rr.length)];
        }
        
    }
}
-(void) loadMediaFile: (NSString *) what
{
    NSString *path;
    if([[NSFileManager defaultManager] fileExistsAtPath: what] == YES)
    {
        if (myMovie != nil) [myMovie release];
        myMovie = [[NSMovie alloc] initWithURL: [NSURL fileURLWithPath: what] byReference: YES];
        if(myMovie != nil)
        {
            [myMovieView showController: YES adjustingSize: YES];
            duration = GetMovieDuration([myMovie QTMovie]);
            [movieTitle setStringValue: [what lastPathComponent]];
            [myMovieView setMovie: myMovie];
            return;
        }
        
    }
    else
    {
        if((path = [self fileName]) != nil)
        {
            NSMutableArray *cmp = [NSMutableArray arrayWithArray: [path pathComponents]];
            NSString *newPath;
            [cmp removeLastObject];
            [cmp addObject: [what lastPathComponent]];
            newPath = [cmp componentsJoinedByString: @"/"];
            if([[NSFileManager defaultManager] fileExistsAtPath: newPath] == YES)
            {
                if(myMovie != nil) [myMovie release];
                myMovie = [[NSMovie alloc] initWithURL: [NSURL fileURLWithPath: newPath] byReference: YES];
                if(myMovie != nil)
                {
                    [myMovieView showController: YES adjustingSize: YES];

                    duration = GetMovieDuration([myMovie QTMovie]);
                    [movieTitle setStringValue: [newPath lastPathComponent]];
                    [myMovieView setMovie: myMovie];
                    return;
                }
            }
        }
    }
    NSWARNING(@"Unable to find or open media file. Remove !mediafile metatag and relocate the file");
                
}
-(IBAction) openMovie: (id) sender
{
    NSOpenPanel *op;
    op = [NSOpenPanel openPanel];
    [op beginSheetForDirectory: nil  file: nil types: nil /*[NSMovie movieUnfilteredFileTypes]*/
                modalForWindow: myWindow modalDelegate:self 
                didEndSelector: @selector(moviePanelDidEnd:returnCode:contextInfo:) contextInfo: nil];
}
-(IBAction) setRate: (id) sender
{
    float dd;
    if(myMovie == nil) 
        return;
    dd =  [[rateMenu titleOfSelectedItem] floatValue];
    [myMovieView setRate: dd];
}
-(IBAction) fwdFrame: (id) sender
{
    if(myMovie == nil) return;
    [myMovieView stepForward: sender];
}
-(IBAction) bkFrame: (id) sender
{
    if(myMovie == nil) return;
    [myMovieView stepBack: sender];
}
-(IBAction) gotoMovieEnd: (id) sender
{
    if(myMovie == nil) return;
    [myMovieView gotoEnd: sender];
}

-(IBAction) gotoMovieStart: (id) sender;
{
    if(myMovie == nil) return;
    [myMovieView gotoBeginning: sender];
}
-(IBAction) speedUp: (id) sender
{
    if(myMovie == nil) return;
    [myMovieView setRate: [myMovieView rate] + 0.01];
}
-(IBAction) slowDown: (id) sender;
{
    if(myMovie == nil) return;
    [myMovieView setRate: [myMovieView rate] - 0.01];
}

-(IBAction) clearMediaFileTags: (id) sender
{
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    ctQChar *q;
    int t,n;
    NSMutableArray *aa;
    MWRange *mr;
    aa = [[NSMutableArray alloc] init];
    
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    
    q = [[ctQChar alloc] init];
    
    
    while((t = [tc scanNext: q]) != ENDOFFILE)
    {
        if(t == META)
        {
            if([[q buff] isEqualToString: @"mediafile"])
            {
                mr =  [[MWRange alloc] initWithRange: [q range]];
                [mr autorelease];
                [aa insertObject: mr atIndex: 0];
            }
        }
    }
    n = [aa count];
    if (n > 0)
    {
        FORALL(aa)
        {
            [theDoc setSelectedRange: [temp range]];
            [theDoc insertText: @""];
        }
        ENDFORALL;
    }
    [aa release];
    [tc release];
    [q release];
}
-(IBAction) showTimeAsHHMMSS: (id) sender
{
    NSString *ss;
    double tm;
    NSString *ans;
    NSRange r;
    long scale, ct;
    long sec, min, hr;
    r = [theDoc selectedRange];
    if(r.length)
    {
        ss = [[theDoc string] substringWithRange: r];
        if(isHHMMSS(ss) == YES) NSWARNING(@"Selected time must be in seconds.");
        tm = [ss doubleValue];
        sec = (long) tm;
        min = sec/60;
        sec = sec % 60;
        hr = min/ 60; 
        min = min%60;
        ans = [NSString stringWithFormat: @"Selected time = %2ld:%0.2ld:%0.2ld", hr, min, sec];
        NSMESSAGE(ans);
    }
    else
    {
        if(myMovie == nil) return;
        scale = GetMovieTimeScale( [myMovie QTMovie]);
        ct =  GetMovieTime([myMovie QTMovie], nil);
        sec = ct/scale;
        min = sec/60;
        sec = sec % 60;
        hr = min/ 60;
        ans = [NSString stringWithFormat: @"Media time = %2ld:%0.2ld:%0.2ld", hr, min, sec];
        NSMESSAGE(ans);
    }
}
//end MULTIMEDIA
#endif
-(void) idleTimer:(id)sender
{
#ifdef MULTIMEDIA
    long scale, ct;
    float time;
    if(myMovie == nil) return;
    scale = GetMovieTimeScale( [myMovie QTMovie]);
    ct =  GetMovieTime([myMovie QTMovie], nil);
    if([myMovieView isPlaying] && [stopStartButton state] == NSOffState)
        [stopStartButton setState: NSOnState];
    if([myMovieView isPlaying] == NO && [stopStartButton state] == NSOnState)
        [stopStartButton setState: NSOffState];
    time = (float) ct/ (float) scale;
    if([gPrefBoss timeFormatHHMMSS] == 1)
        [timeField setStringValue: sec2hhmmss((unsigned) time)];
    else
        [timeField setStringValue: [NSString stringWithFormat: @"%.2fs", (float) ct/ (float) scale]];
    if(jagFlag)
        MoviesTask([myMovie QTMovie],0);
#endif
}

-(void) endTimer
{
#ifdef MULTIMEDIA    if(myMovie == nil) return;
    [myMovie release];
    myMovie = nil;
#ifdef USETIMER
    if(myTimer == nil) return;
    [myTimer invalidate];
    [myTimer release];
    myTimer= nil;
#endif
#endif
}

-(IBAction) copyWithoutTags: (id) sender
{
    ctQChar *q;
    NSString *oText;
    NSMutableString *nText;
    NSRange r;
    MWFakeFile *ff;
    int ch;
    BOOL a;
    
    r = [theDoc selectedRange];
    if(r.length == 0) return;
    oText = [[theDoc string] substringWithRange: r];
    ff = [[MWFakeFile alloc] initWithString: oText];
    nText = [[NSMutableString alloc] init];
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    [tc setAllowTab: 1];
    [tc setNoPar: 0];
    //start search
    [tc addFileToSearchList: ff];
    
    [tc startSearch];
    q = [[ctQChar alloc] init];
    while((ch = [tc scanNext: q withWarnings: NO]) != ENDOFALLFILES)
    {
        if (ch == CHAR) [nText appendString: [q buff]];
    }
    [q release];
    [tc release];
    [ff release];
    [[NSPasteboard generalPasteboard]
	declareTypes:[NSArray arrayWithObject:NSStringPboardType]
               owner:self];
    
    a = [[NSPasteboard generalPasteboard] setString: nText forType: NSStringPboardType];
    [nText autorelease];
}        
-(IBAction) requestCodeDefinitionOfSelection: (id) sender
{
    NSRange who;
    NSString *theCode, *theSel;
    NSMutableString *theDef;
    NSString *warning;
    //get the string
    if(gWorkBench == nil) return;
    who = [theDoc selectedRange];
    if(who.length == 0) return;
    
    
    theSel = [[theDoc string] substringWithRange: who];
    
    theCode = extractFirstCode(theSel);
    if(theCode == nil) {NSWARNING(@"Cannot find code in selection."); return;}
    //ask for definition
    theDef = [gWorkBench getDefinition: theCode];
    if(!theDef) {
        warning = [NSString stringWithFormat: @"Cannot find definition for string: %@", theCode];
        NSWARNING(warning); 
        return;
    }
    //if it exists retain and display it
    [theDef retain];
    NSRunAlertPanel(theCode, theDef, @"Ok", nil, nil);
    //release it
    [theDef release];
}
-(IBAction) recolorTags: (id) sender
{
    [self doColorOff: nil];
    [self doColorize: nil];
}
-(void) setCommentDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    NSRange curr, r;
    if(returnCode)
    {
        NSString *s;
        r = curr = [theDoc selectedRange];
        int tagtype;
        tagtype = [setCommentMenu tagOfSelectedItem];
        switch(tagtype)
        {
            case 0:
                if(curr.length > 0)
                {
                    [theDoc setSelectedRange: NSMakeRange(curr.location+curr.length, 0)];
                    s = [NSString stringWithFormat: @"{!endcomment %@}", [setCommentField stringValue]];
                    [theDoc insertText: s];
                    r.length += [s length];
                }
                [theDoc setSelectedRange: NSMakeRange(curr.location, 0)];
                s = [NSString stringWithFormat: @"{!setcomment %@}", [setCommentField stringValue]];
                [theDoc insertText: s];
                r.length += [s length];
                break;
            case 1:
                if(curr.length > 0)
                {
                    [theDoc setSelectedRange: NSMakeRange(curr.location+curr.length, 0)];
                    s = [NSString stringWithFormat: @"{!endcomment %@}", [setCommentField stringValue]];
                    [theDoc insertText: s];
                    r.length += [s length];
                }
                [theDoc setSelectedRange: NSMakeRange(curr.location, 0)];
                s = [NSString stringWithFormat: @"{!setcomment %@}", [setCommentField stringValue]];
                
                [theDoc insertText: s];
                r.length += [s length];
                
                break;
                
            default:;
        }
        if([gPrefBoss autoColorValue] == 1) [self doColorizeRange: r];
        [theDoc setSelectedRange: r];
    }
    
}

-(IBAction) cancelSetComment: (id) Sender
{
    [setCommentSheet orderOut: Sender];
    [NSApp endSheet: setCommentSheet returnCode: 0];
    
}

-(IBAction) okSetComment: (id) Sender
{
    [setCommentSheet orderOut: Sender];
    [NSApp endSheet: setCommentSheet returnCode: 1];
    
}
-(IBAction) doSetComment: (id) Sender
{
    [setCommentField setStringValue: @"Ñ"];
    
    [NSApp beginSheet: setCommentSheet
       modalForWindow: myWindow
	modalDelegate: self
       didEndSelector: @selector(setCommentDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}


@end


