//
//  myResults.m
//  TAMS Edit
//
//  Created by matthew on Sun Apr 21 2002.
//  Copyright (c) 2001 Matthew Weinstein. All rights reserved.
//

#import "myResults.h"
#import "ctReadChar.h"
#import "tams.h"
#import "ctLimitCrit.h"
#import "TAMSCharEngine.h"
#import "coderec.h"
#import "NSRecordData.h"
#import "prefBoss.h"
#import "myProject.h"
#import "docDelegate.h"
#import "appDelegate.h"
#import "utils.h"
#import "tamsutils.h"
#import "MWPath.h"
#import "MWFakeFile.h"
#import "MGWPopUpButton.h"
#import "MWKeyedResult.h"

//#import "AGRegex.h"
#import <stdio.h>
#import <stdlib.h>
#import "MWSortStackItem.h"
#import "stringCategories.h"
#import "MWTAMSStringCategories.h"
//#define SIMON 1
#define NOTIFICATIONDIRTY 1
#define CLOSEBUG 1
#define NAMEDSELMENU 140
#define COLWIDTH 90.0
#define XML 1
#define REGEXSEARCH 1
#define NAMEDSELBASE 4
#define FIELDMAP 1
#define MYGLOBAL(X)	[myGlobals findInt: X]
#define SETGLOBAL(X,Y)	[myGlobals setKey: X intValue: Y]
#define ON(X) if([X isEqualToString: [myc buff]] == YES)
#define SELECTEDCOLUMNID(X) [[[X tableColumns] objectAtIndex: [X selectedColumn]] identifier]
#define UPDATERECCOUNT	[self updateRecCount];

#define TAMSTART(X) [[X objectForKey: @"_begin_loc"] intValue]
#define TAMEND(X) [[X objectForKey: @"_end_loc"] intValue]
#define MAKEDIRTY [self updateChangeCount: NSChangeDone];
#define DIRTYWARN if([dirtySourceFlag state] == NSOnState) if(NSYESNOQUESTION(@"Results may be out of synch with data files. Proceed?") == NO) return;

NSString *dateFmt[20] =
{{@"%m/%d/%y"}, //mm/dd/yy
{@"%m/%d/%Y"}, //mm/dd/yyyy
{@"%m-%d-%y"}, //mm-dd-yyyy
{@"%d/%m/%Y"}, //dd/mm/yyyy
{@"%d/%m/%y"}, //dd/mm/yy
{@"%B %d, %Y"}, //month dd, yyyy
{@"%d %B, %Y"}, //dd month, yyyy
{@"%I:%M"}, //hh:mm
{@"%I:%M %p"}, //hh:mm AM/PM
{@"%I:%M:%S"}, //hh:mm:ss
{@"%I:%M:%S %p"},//hh:mm:ss AM/PM
    {@"%H:%M"}, //24hh:mm
{@"%H:%M:%S"}, //24hh:mm:ss
{@""} //other
};

BOOL arrayContainsString(NSArray *a, NSString *s)
{
    int i;
    int n;
    
    n  = [a count];
    for(i = 0; i < n; i++)
    {
        if([[a objectAtIndex: i] isEqualToString: s] == YES)
            return YES;
    }
    return NO;
}
//need to change this for version 2
int locationComp(id first, id second, void *key)
{
    //compare the documents
    if([first objectForKey: @"_doc"] == [second objectForKey: @"_doc"])
    {
	if([[first objectForKey: @"_begin_loc"] intValue] > 
           [[first objectForKey: @"_begin_loc"] intValue])
            return NSOrderedDescending;
	else if([[first objectForKey: @"_begin_loc"] intValue] <
		[[first objectForKey: @"_begin_loc"] intValue])
            return NSOrderedAscending;
	else return NSOrderedSame;
    }
    else
    {
        return [(MWFile *)[first objectForKey: @"_doc"] compare: [second objectForKey: @"_doc"]];
        
        
    }
}
int locationFwdComp(id first, id second, void *key)
{
    //compare the documents
    if([[first objectForKey: @"_doc"] isEqual: [second objectForKey: @"_doc"]])
    {
	if([[first objectForKey: @"_begin_loc"] intValue] < 
           [[first objectForKey: @"_begin_loc"] intValue])
            return NSOrderedDescending;
	else if([[first objectForKey: @"_begin_loc"] intValue] >
		[[first objectForKey: @"_begin_loc"] intValue])
            return NSOrderedAscending;
	else return NSOrderedSame;
    }
    else
    {
        return ([(MWFile *)[first objectForKey: @"_doc"] compare: [second objectForKey: @"_doc"]]);
        
        
    }
}



int nsStringComp(id first, id second, void *key)
{
    return([(NSString *)first compare: second]);
}
int nsMWFileComp(id first, id second, void *key)
{
    return nsStringComp([first name], [second name], key);
}


int stringComp(id first, id second, NSString *key)
{
    return [[first objectForKey: key] compare: [second objectForKey: key]];
}

int longFwdComp(id first, id second, NSString *key)
{
    int a, b;
    a = [[first objectForKey: key] intValue];
    b = [[second objectForKey: key] intValue];
    if(a < b)
	return NSOrderedAscending;
    else if(a > b)
	return NSOrderedDescending;
    else
	return NSOrderedSame;
}

@implementation myResults
-(void) updateOnlyRecCount
{
    [recCount setStringValue: 
        [NSString stringWithFormat: @"%d/%d", [myData count], [backData count]]]; 
    
}
-(void) updateRecCountVertical
{
    int n; 
    n = [myData count];
    [recCount setStringValue: 
        [NSString stringWithFormat: @"%d/%d", n, [backData count]]]; 
    [self updateChangeCount: NSChangeDone]; 
    if([theResults selectedColumn] < 0 && [theResults numberOfRows] > 0)
    {
        [theResults selectRow: 0 byExtendingSelection: NO];
    }
    [self displaySelData: 0];
    
}

-(void) updateRecCount
{
    int r, n; 
    n = [myData count];
    r = [theResults selectedRow];
    [recCount setStringValue: 
        [NSString stringWithFormat: @"%d/%d", n, [backData count]]]; 
    [self updateChangeCount: NSChangeDone]; 
	if(n>0 && [theResults numberOfRows] > 0)
    {
        [theResults selectRow: 0 byExtendingSelection: NO];
        [self displaySelData: 0];
    }
    
}
-(void) updateRecCountAtRow
{
    int r, n; 
    n = [myData count];
    r = [theResults selectedRow];
    [recCount setStringValue: 
        [NSString stringWithFormat: @"%d/%d", n, [backData count]]]; 
    [self updateChangeCount: NSChangeDone]; 
    if(r < n && r >= 0)
        [self displaySelData: r];
    else
    {
	if (n > 0 && [theResults numberOfRows] > 0)
        [theResults selectRow: 0 byExtendingSelection: NO];
        
        [self displaySelData: 0];
    }
    
}
-(BOOL) isUniversal: (NSString *) name
{
    FORALL(univList)
    {
	if([temp isEqualToString: name]) return YES;
        
    }
    ENDFORALL;
    return NO;
}

-(BOOL) isInnerRepeat: (NSString *) name
{
    FORALL(innerRepList)
    {
	if([temp isEqualToString: name]) return YES;
        
    }
    ENDFORALL;
    return NO;
}
-(BOOL) isLastRepeat: (NSString *) name
{
    FORALL(lastRepList)
    {
	if([temp isEqualToString: name]) return YES;
        
    }
    ENDFORALL;
    return NO;
}

-(BOOL) isRepeat: (NSString *) name
{
    FORALL(repList)
    {
	if([temp isEqualToString: name]) return YES;
        
    }
    ENDFORALL;
    return NO;
}
-(BOOL) isBlocked: (NSString *) name
{
    FORALL(blockList)
    {
	if([temp isEqualToString: name]) return YES;
        
    }
    ENDFORALL;
    return NO;
}

-(int) getDocType {return myDocType;}
-(void) setCharEngineWithSource: (id) src andFileList: (NSArray *) myList
{
    
    tce = [[TAMSCharEngine alloc] init];
    [tce addArrayToSearchList: myList];
    [tce setGCurrentDataSource: src];
    [tce startSearch];
}
-(void) setCharEngine: (TAMSCharEngine*) who {tce = who;}
-(void) setGlobalInt: (id) key value: (int) v
{
    [myGlobals setKey: key intValue: v];
}
-(int) global: (NSString *)name
{
    return [myGlobals findInt: name];
}
-(void) setGlobal: (NSString *) name to: (int) val
{
    [myGlobals setKey: name intValue: val];
}

-(void) initVariables
{
	builtTable = NO;
    [myGlobals setKey: @"eofIsEndFlag" intValue: [gPrefBoss EOFIsEndValue]];
    [myGlobals setKey: @"firstwriteflag" intValue: 1];
    [myGlobals setKey: @"quoteflag" intValue: 1];
    [myGlobals setKey: @"tabflag" intValue: 0];
    [myGlobals setKey: @"headerflag" intValue: 1];
    [myGlobals setKey: @"lnumflag" intValue: 0];
    [myGlobals setKey: @"lineflag" intValue: 0];
    [myGlobals setKey: @"fastflag" intValue: 0];
    [myGlobals setKey: @"basicflag" intValue: [gPrefBoss defaultUnstruct]];
    [myGlobals setKey: @"blankflag" intValue: 1];
    [myGlobals setKey: @"startflag" intValue: 1];
    [myGlobals setKey: @"nameflag" intValue: 0];
    [myGlobals setKey: @"noparflag" intValue: 1];
    [myGlobals setKey: @"cleanflag" intValue: 1];
    [myGlobals setKey: @"lastRepeat" intValue: 0];
    [myGlobals setKey: @"skipinnertopofdoc" intValue: 1];
    [myGlobals setKey: @"skipinneratend" intValue: 1];
    [myGlobals setKey: @"linecount" unsValue: 1L];
    [myGlobals setKey: @"escapeflag" unsValue: [gPrefBoss escapeBracesValue]];
    [myGlobals setKey: @"zeromark" unsValue: 0];
    SETGLOBAL(@"backloadrepeatflag", [gPrefBoss backendRepeatValue]);
    SETGLOBAL(@"zapuniversal", [gPrefBoss zapUnivValue]);
    if([self global: @"skipinnertopofdoc"] == 1)innerRFlag = 0;
    
    
}
-(id) init
{
    [super init];
    myDocType = RESULTTYPE;
    firstUpdateFlag = YES;
    exactCodeSetFlag = YES;
    stripTags = NO;
    //[[NSDocumentController sharedDocumentController] addDocument: self];
    myGlobals = [[varRegistry alloc] init];
    closePermission = NO;
    caseSortFlag = NO;
    fieldMap = [[NSMutableDictionary alloc] init];
    univVault = [[NSMutableDictionary alloc] init];
    normVault = [[NSMutableDictionary alloc] init];
    repVault = [[NSMutableDictionary alloc] init];
    univList = [[NSMutableArray alloc] init];
    fileList = [[NSMutableArray alloc] init];
    codersList = [[NSMutableArray alloc] init];
    colList = [[NSMutableArray alloc] init];
    repList = [[NSMutableArray alloc] init];
    blockList = [[NSMutableArray alloc] init];
    myData = [[NSMutableArray alloc] init];
    backData = [[NSMutableArray alloc] init];
    setStack = [[NSMutableArray alloc] init];
    fwdSetStack = [[NSMutableArray alloc] init];
    fmode = [[NSMutableString alloc] init];
    innerRepeat = [[NSMutableString alloc] init];
    markedList = [[NSMutableArray alloc] init];
    savedDataType = [[NSMutableString alloc] init];
    lastRepList = [[NSMutableArray alloc] init];
    innerRepList = [[NSMutableArray alloc] init];
    lgNewCodeName = [[NSMutableString alloc] init];
    lgNewCodeDef = [[NSMutableString alloc] init];
    sortStack = [[NSMutableArray alloc] init];
    dfString = [[NSMutableString alloc] init];
    [dfString setString: dateFmt[0]];
    browseField = [[NSMutableString alloc] initWithString: @"_data"];
    codersString = [[NSMutableString alloc] init];
    namedSelSelected = [[NSMutableString alloc] init];
    namedSelDict = [[NSMutableDictionary alloc] init];
    repCont = [[NSMutableDictionary alloc] init];
    autoSets = [[NSMutableDictionary alloc] init];
    summReports = [[NSMutableDictionary alloc] init];
    autoHistory = [[NSMutableArray alloc] init];
    autoHistoryStart = [[NSMutableString alloc] init];
    extraComment = [[NSMutableString alloc] init];
    commentArray = [[NSMutableArray alloc] init];
    mediaDict = [[NSMutableDictionary alloc] init];
    myMovie = nil;
    myTimer = nil;
    dfIndex = -1;
    
    limitString = nil;
    
    //These are set by the user and should maintain their value so we don't reset them in initVariable
    [myGlobals setKey: @"simpleflag" intValue: 0];
    [myGlobals setKey: @"limitflag" intValue: 0];
    [myGlobals setKey: @"rawflag" intValue: 1];
    [myGlobals setKey: @"exactflag" intValue: 0];
    [myGlobals setKey: @"emptyflag" intValue: 1];
    [myGlobals setKey: @"regexcharflag" intValue: 1];
    [myGlobals setKey: @"sectionsearch" intValue: 0];
    [self initVariables];
    
    return self;
}

- (void) reconnect
{
    FORALL(fileList)
    {
        [[NSNotificationCenter defaultCenter] addObserver: self 
                                                 selector: @selector(handleDirtySourceFlag:)
                                                     name: @"TAMSDocDidChange"
                                                   object: temp];
        /*
         [[NSNotificationCenter defaultCenter] addObserver: self 
                                                  selector: @selector(addCodeHandler:)
                                                      name: @"TAMSDocAddedCode"
                                                    object: temp];*/
    }
    ENDFORALL;
    
    
}
- (void) disconnect
{
    [[NSNotificationCenter defaultCenter] 
	    removeObserver:self];
    /*            
    FORALL(fileList)
    {
	[[NSNotificationCenter defaultCenter] 
	    removeObserver:self
                      name: @"TAMSDocDidChange"
                    object: temp
	    ];
    }ENDFORALL; 
    */
}

- (void) close
{
    [self disconnect];
    [super close] ;
}
-(void) dealloc {
    [self disconnect];
    [autoHistory release];
    [lastRepList release];
    [innerRepList release];
    [autoHistoryStart release];
    [autoSets release];
    [univVault release];
    [normVault release];
    [repVault release];
    [univList release];
    [fieldMap release];
    [summReports release];
    [fileList release];
    [colList release];
    [savedDataType release];
    [repList release];
    [browseField release];
    [mediaDict release];
    [extraComment release];
    [commentArray release];
    [blockList release];
    [myData release];
    [backData release];
    [fmode release];
    [markedList release];
    [lgNewCodeName release];
    [lgNewCodeDef release];
    [dfString release];
    [codersList release];
    [innerRepeat release];
    [sortStack release];
    [namedSelSelected release];
    [namedSelDict release];
    [repCont release];
    [setStack release];
    [fwdSetStack release];
    
    [super dealloc];
}

-(void) addCodeHandler: (NSNotification *) notification
{
    NSDictionary *info; 
    MWFile *who;
    
    who = [notification object];
    info = [notification userInfo];
    FORALL(backData)
    {
        if([temp objectForKey: @"_doc"] == who)
        {
            int b, e, l, loc;
            loc = [[info objectForKey: @"location"] intValue];
            l = [[info objectForKey: @"length"] intValue];
            b = [[temp objectForKey: @"_begin_loc"] intValue];
            e = [[temp objectForKey: @"_end_loc"] intValue];
            if(b >= loc)
                [temp setObject: [NSNumber numberWithLong: (b + l)]
                         forKey: @"_begin_loc"];
            if(e >= loc)
                [temp setObject: [NSNumber numberWithLong:( e + l)] 
                         forKey: @"_end_loc"];
        }
        
    }
    ENDFORALL;
    [theResults reloadData];
}


#ifdef NOTIFICATIONDIRTY
-(void) handleDirtySourceFlag: (NSNotification *) notification
{
    // if this is one of mine get dirty
    if([dirtySourceFlag state] == NSOnState) return;
    FORALL(fileList)
    {
	//if([(MWFile *)temp compare: [notification object]] == YES)
        if(temp == [notification object])
	{
	    [dirtySourceFlag setState: NSOnState];
	    return;
	}
    }
    ENDFORALL;
}
#else
//update method
- (void)windowDidBecomeKey:(NSNotification *)aNotification
{
    //do the docs exist
    FORALL(fileList)
    {
	if([gWorkBench fileExists: temp] == YES)
	{
            //if yes are dirty
	    [dirtySourceFlag setState: NSOnState];
	    return;
	}
    } ENDFORALL;
    //mark me and return
    if(gWorkBench != nil) 
    {
        if([gWorkBench reanalysisMode] == YES)
        {
            [[[NSApp delegate] reanalysisMenu] setState: NSOnState];
        }
        else
        {
            [[[NSApp delegate] reanalysisMenu] setState: NSOffState];
        }
        [gWorkBench rebuildCodeSetMenu];
    }
    
}
#endif

-(void) adjustBy: (int) amt startingAt: (int) loc for: (id) who
{
    int newLoc;
    FORALL(myData)
    {
	if([[temp objectForKey: @"_doc"] isEqual: who])
	{
	    if([[temp objectForKey: @"_begin_loc"] intValue] > loc)
	    {
		newLoc = [[temp objectForKey: @"_begin_loc"] intValue] + amt;
		[temp setObject: [NSNumber numberWithInt: newLoc] forKey: @"_begin_loc"];
	    }
	    if([[temp objectForKey: @"_end_loc"] intValue] > loc)
	    {
		newLoc = [[temp objectForKey: @"_end_loc"] intValue] + amt;
		[temp setObject: [NSNumber numberWithInt: newLoc] forKey: @"_end_loc"];
	    }
	}
    } ENDFORALL;
}

-(IBAction) doMarkAll: (id) sender
{
    [markedList setArray: myData];
    [theResults reloadData];
    [self updateChangeCount: NSChangeDone]; 
    
}

-(IBAction) doUnmarkAll: (id) sender
{
    [markedList removeAllObjects];
    [theResults reloadData];
    [self updateChangeCount: NSChangeDone]; 
    
}

-(void) markRecord: (int) row withReload: (BOOL) doit
{
    if([markedList indexOfObject: [myData objectAtIndex: row]] == NSNotFound)
    {
	[markedList addObject: [myData objectAtIndex: row]];
    }
    if(doit == YES)
        [theResults reloadData];
    [self updateChangeCount: NSChangeDone]; 
}

//array of nsnumbers
-(void) markArray: (NSArray *) rows
{
    FORALL(rows)
    {
        [self markRecord: [temp intValue] withReload: NO];
    }
    ENDFORALL;
    [theResults reloadData];
    [self updateChangeCount: NSChangeDone]; 
    
}
-(void) markBackArray: (NSArray *) rows
{
    FORALL(rows)
    {
        if([markedList indexOfObject: [backData objectAtIndex:  [temp intValue]]] == NSNotFound)
        {
            [markedList addObject: [backData objectAtIndex: [temp intValue]]];
        }
        
    }
    ENDFORALL;
    [theResults reloadData];
    [self updateChangeCount: NSChangeDone]; 
    
}

-(IBAction) doMark: (id) sender
{
    int row;
    
    row = [theResults selectedRow];
    if([markedList indexOfObject: [myData objectAtIndex: row]] == NSNotFound)
    {
	[markedList addObject: [myData objectAtIndex: row]];
    }
    [theResults reloadData];
    [self updateChangeCount: NSChangeDone]; 
    
}
-(IBAction) doUnmark: (id) sender
{
    int row;
    int selObj;
    
    row = [theResults selectedRow];
    selObj = [markedList indexOfObject: [myData objectAtIndex: row]];
    if(selObj != NSNotFound)
    {
	[markedList removeObject: [myData objectAtIndex: row]];
    }
    [theResults reloadData];
    MAKEDIRTY; 
    
}

-(IBAction) doDeleteMarked: (id) sender
{
    if([markedList count])
    {
	FORALL(markedList)
    {
	    [myData removeObject: temp];
    }
	ENDFORALL;
	[markedList removeAllObjects];
        [theResults reloadData];
        UPDATERECCOUNT;
        MAKEDIRTY;
    }
}

-(IBAction) doReverseMarked: (id) sender
{
    NSMutableArray *newMarked = [[NSMutableArray alloc] init];
    //save the total list into an array
    [newMarked setArray: myData];
    //remove the marked
    FORALL(markedList)
    {
	[newMarked removeObject: temp];
    }
    ENDFORALL;
    //set the new marked list
    [markedList setArray: newMarked];
    [newMarked release];
    //reload
    [theResults reloadData];
    MAKEDIRTY;
    
    
}

-(IBAction) doShowComment: (id) sender
{
    int row;
    id aRec;
    
    //get the key numbers
    row = [theResults selectedRow];
    //make a range
    aRec = [myData objectAtIndex: row];
    NSRunAlertPanel(@"Comment:", [aRec objectForKey: @"_comment"], @"Ok", nil, nil);
    
}

-(void) newCodeDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    if(returnCode == 1)
    {
	[lgNewCodeName setString: [newCodeName stringValue]];
	[lgNewCodeDef setString: [newCodeDef string]];
	[arBossWindow orderOut: self];
	[NSApp endSheet: arBossWindow returnCode: 1];
    }
    
    
}
-(IBAction) deleteSourceCodes: (id) Sender
{
    NSMutableArray *myLocalRecs;
    id myRec, ans;
    NSEnumerator *locList;
    DIRTYWARN;
    if([self global: @"sectionsearch"] == YES || [self global: @"regexcharflag"] == YES ||
       [self global: @"nonregexcharflag"] == YES)
    {
        NSWARNING(@"Cannot delete codes this type of search");
        return;
    }
    if([self global: @"limitflag"] && ![self global: @"simpleflag"]) 
    {
	NSWARNING(@"Only simple searches can have records removed");
	return;
    }
    ans = NSYESNOQUESTION(@"This will delete information from your source files. Should I proceed?");
    if(ans == NO) return;
    if([markedList count])
    {
	
        //is there something there?
        //refresh?
        //copy records
        myLocalRecs = [[NSMutableArray alloc] init];
        [myLocalRecs setArray: markedList];
        
        //reverse sort
        [myLocalRecs sortUsingFunction: locationComp context: nil];
        
        //go through and call the main docuement
        locList = [markedList reverseObjectEnumerator];
        while(myRec = [locList nextObject])
        {
            if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
            {
                if([gPrefBoss batchOpenFiles])
                    [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
                else
                    [(MWFile *)[myRec objectForKey: @"_doc"] setOpenFakeFileWithWorkBench: gWorkBench];
                
            }
            
            [[[myRec objectForKey: @"_doc"] filePointer ] deleteCodeFromResultStartingWith: 			[[myRec objectForKey: @"_begin_loc"] intValue]
                                                                                endingWith: [[myRec objectForKey:@"_end_loc"] intValue] from: self];
        }
        if([gPrefBoss batchOpenFiles] == 0)
        {
            locList = [myLocalRecs reverseObjectEnumerator];
            while(myRec = [locList nextObject])
            {
                [(MWFile *)[myRec objectForKey: @"_doc"] closeFakeFile];    
                
            }
        }
        //remove the files from here
        if([markedList count])
        {
            FORALL(markedList)
        {
                [myData removeObject: temp];
                [backData removeObject: temp];
        }
            ENDFORALL;
            [markedList removeAllObjects];
        }
        [theResults reloadData];
        UPDATERECCOUNT;
        
        //have it reload
        if([gPrefBoss autoReloadValue])
            [self refreshResults: self];
	
    }
    else
    {
    }
}
-(void) recodeDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    NSMutableArray *myLocalRecs;
    NSMutableString *myNewCodeName;
    id myRec;
    NSEnumerator *locList;
    
    myNewCodeName = [[NSMutableString alloc] init];
    
    
    if([markedList count])
    {
	if(returnCode == 1)
	{
	    //is there something there?
	    if([lgNewCodeName isEqualToString: @""] == YES) return;
	    //refresh?
	    //copy records
	    myLocalRecs = [[NSMutableArray alloc] init];
	    [myLocalRecs setArray: markedList];
	    
	    //reverse sort
	    [myLocalRecs sortUsingFunction: locationComp context: nil];
            
	    //go through and call the main docuement
	    locList = [markedList reverseObjectEnumerator];
	    while(myRec = [locList nextObject])
	    {
                if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
                    [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
		[[[myRec objectForKey: @"_doc"] filePointer] recode: lgNewCodeName
                                                              first: [[myRec objectForKey:@"_begin_loc"] intValue]
                                                               last: [[myRec objectForKey:@"_end_loc"] intValue] from: self
                                                            withDef: lgNewCodeDef];
	    }
            if([gPrefBoss cancelAfterRecode] == 1)
                [self doUnmarkAll: nil];
            
	    //have it reload
	    if([gPrefBoss autoReloadValue])
		[self refreshResults: self];
	}
    }
    else
    {
    }
}

//#define MODALWIND 1

-(void) setInnerRepeat: (NSString *) what
{
    [innerRepeat setString: what];
    trimNSS(innerRepeat);
    
}
-(void) buildCoderList
{
    NSString *ss;
    NSMutableArray *tempArray;
    int n;
    
    //remove objects
    [codersList removeAllObjects];
    //get the list
    ss = codersString;
    //split object
    tempArray = convertStringToArray(ss, ',');
    [tempArray retain];
    n = [tempArray count];
    FORALL(tempArray)
    {
	NSMutableString *tt;
	tt = [[NSMutableString alloc] init];
	[tt setString: temp];
	trimNSS(tt);
	[codersList addObject: tt];
    }
    ENDFORALL;
    n = [codersList count];
    //trim objects
    [tempArray release];
}
-(IBAction) doAddCodeOK: (id) sender
{
    lgNewCodeMode = CODEMODEOLD;
    [lgNewCodeName setString: [addCodeName titleOfSelectedItem]];
    [lgNewCodeDef setString: @""];
    [addCodeWindow orderOut: sender];
    [NSApp endSheet: addCodeWindow returnCode: 1];
    
}

-(IBAction) doFillName: (id) sender
{
    [newCodeName setStringValue: [addCodeName titleOfSelectedItem]];
}

-(IBAction) doNewCode: (id) sender
{
    lgNewCodeMode = CODEMODENEW;
    if([inheritedColorSwitch state] == NSOnState)
        lgNewCodeColor = inheritedColor;
    else
        lgNewCodeColor = otherColor;
    //lgNewCodeColor = [[codeColorMenu selectedItem] tag];
    lgNewRealColor = [myColorWell color];
    [lgNewCodeName setString: [newCodeName stringValue]];
    [lgNewCodeDef setString: [newCodeDef string]];
    [addCodeWindow orderOut: sender];
    [NSApp endSheet: addCodeWindow returnCode: 1];
    
}


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

-(IBAction) selectColorFromWell:(id)Sender
{
    [inheritedColorSwitch setState: NSOffState];
}
-(IBAction) selectColorFromSwitch:(id) sender
{
    if([inheritedColorSwitch state] == NSOnState)
        [myColorWell setColor: [gWorkBench colorForCode: [newCodeName stringValue]]];
}
-(NSMutableString *) escapeCommentBraces: (NSMutableString *) who
{
    NSRange r, r1;
    int i,n;
    NSMutableString *ss = [NSMutableString string];
    r = [who rangeOfString: @"{"];
    r1 = [who rangeOfString: @"}"];
    if(r1.location == NSNotFound && r.location == NSNotFound) return who;
    n = [who length];
    for(i = 0; i < n; i++)
    {
        if([who characterAtIndex: i] == '\\')
        {
            if(i < n -1)
            {
                [ss ADDCHAR([who characterAtIndex: i])];
                i++;
                [ss ADDCHAR([who characterAtIndex: i])];
                continue;
            }
        }
        if([who characterAtIndex: i] == '{')
        {
            [ss ADDCHAR('\\')];
            [ss ADDCHAR([who characterAtIndex: i])];
            continue;
        }
        if([who characterAtIndex: i] == '}')
        {
            [ss ADDCHAR('\\')];
            [ss ADDCHAR([who characterAtIndex: i])];
            continue;
        }
        [ss ADDCHAR([who characterAtIndex: i])];
    }
    [who setString: ss];
    return who;
}
-(void) addCommentDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (NSArray *) hotList
{
    NSString *lgNewCodeName;
    NSMutableString *thisCmnt, *theCmnt;
    NSMutableArray *myLocalRecs;
    id myRec;
    NSEnumerator *locList;
    if(returnCode)
    {
        if([hotList count])
	{
            thisCmnt = [[NSMutableString alloc] init];
            theCmnt = [commentField string];
            //is there something there?
            myLocalRecs = [[NSMutableArray alloc] init];
            [myLocalRecs setArray: hotList];
            
            //reverse sort
            [myLocalRecs sortUsingFunction: locationComp context: nil];
            
            //go through and call the main docuement
            locList = [myLocalRecs reverseObjectEnumerator];
            while(myRec = [locList nextObject])
            {
                if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
                {
                    if([gPrefBoss batchOpenFiles] == 1)
                        [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
                    else
                        [(MWFile *)[myRec objectForKey: @"_doc"] setOpenFakeFileWithWorkBench: gWorkBench];
                }
                lgNewCodeName = [myRec objectForKey: @"_code"] ;
                if(commentMode == 0)
                {
                    [thisCmnt setString: theCmnt];
                }
                else
                {
                    NSString *cmt1;
                    cmt1 = [myRec objectForKey: @"_comment"];
                    if(cmt1 != nil)
                        [thisCmnt setString: cmt1];
                    [thisCmnt appendString: theCmnt];
                }
                [self escapeCommentBraces: thisCmnt];
                [[[myRec objectForKey: @"_doc"] filePointer] recode: lgNewCodeName
                                                            comment: thisCmnt
                                                              first: [[myRec objectForKey:@"_begin_loc"] intValue]
                                                               last: [[myRec objectForKey:@"_end_loc"] intValue] from: self
                                                            withDef: @""];
                /*
                 This is too crude, but is the start of refreshing the actual data,
                 what would need to happen is have tce or some such object translate this*/
                
                
                
                [myRec setObject: thisCmnt
                          forKey: @"_comment"]; 
                
            }
            if([gPrefBoss batchOpenFiles] == 0)
            {
                locList = [myLocalRecs reverseObjectEnumerator];
                while(myRec = [locList nextObject])
                {
                    [(MWFile *)[myRec objectForKey: @"_doc"] closeFakeFile];    
                    
                }
            }
            //have it reload
            [self updateRecCountAtRow];
            if([gPrefBoss cancelAfterRecode] == 1)
                [self doUnmarkAll: nil];
            if([gPrefBoss autoReloadValue])
                [self refreshResults: self];
            [self displaySelData];
            [thisCmnt release];
            [myLocalRecs release];
            
	}
	else
	{
	}
        
    }
    [hotList autorelease];
}


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

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

-(IBAction) doAppendCommentToMarked: (id) sender
{
    int row;
    NSMutableArray *hitList;
    NSWindow *who;
    NSString *cmt;
    
    DIRTYWARN;
    hitList = [[NSMutableArray alloc] init];
    if([self global: @"simpleflag"] == 0)
    {
        NSWARNING(@"You can only add comments to simple searches.");
        return;
    }
    row = [theResults selectedRow];
    [hitList addObjectsFromArray: markedList];  
    [commentField setString: @""];
    /*
     row = [theResults selectedRow];
     if([markedList indexOfObject: [myData objectAtIndex: row]] == NSNotFound)
     {
         [markedList addObject: [myData objectAtIndex: row]];
     }
     [theResults reloadData];
     [self updateChangeCount: NSChangeDone]; 
     */
    commentMode=1;
    
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    
    [NSApp beginSheet: commentSheet
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(addCommentDidEnd:returnCode:contextInfo:)
          contextInfo: hitList];
    
}

-(IBAction) doAddComment: (id) sender
{
    int row;
    NSMutableArray *hitList;
    NSWindow *who;
    NSString *cmt;
    
    DIRTYWARN;
    hitList = [[NSMutableArray alloc] init];
    if([self global: @"simpleflag"] == 0)
    {
        NSWARNING(@"You can only add comments to simple searches.");
        return;
    }
    row = [theResults selectedRow];
    if(row >=0)
        [hitList addObject: [myData objectAtIndex: row]];  
    cmt = [[myData objectAtIndex: row] objectForKey: @"_comment"];
    if(cmt != nil) [commentField setString: cmt];
    commentMode = 0;
    /*
     row = [theResults selectedRow];
     if([markedList indexOfObject: [myData objectAtIndex: row]] == NSNotFound)
     {
         [markedList addObject: [myData objectAtIndex: row]];
     }
     [theResults reloadData];
     [self updateChangeCount: NSChangeDone]; 
     */
    
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    
    [NSApp beginSheet: commentSheet
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(addCommentDidEnd:returnCode:contextInfo:)
          contextInfo: hitList];
    
}
-(IBAction) doRecode: (id) sender
{
    NSArray *clist;
    NSWindow *who;
    NSString *hcode;
    DIRTYWARN;
    if(![markedList count]) return;
    hcode = [[markedList objectAtIndex: 0] objectForKey: @"_code"];
    if([self global: @"sectionsearch"] == YES || [self global: @"regexcharflag"] == YES ||
       [self global: @"nonregexcharflag"] == YES)
    {
        NSWARNING(@"Cannot recode this type of search");
        return;
    }
    if([self global: @"limitflag"] && ![self global: @"simpleflag"]) 
    {
	NSWARNING(@"Only simple searches can be recoded");
	return;
    }
    //delete the menu items
    if([addCodeName numberOfItems])
        [addCodeName removeAllItems];
    //get a fresh list
    //add new
    //[addCodeName addItemWithTitle: @"New"];
    //build up the menu
    clist = [gWorkBench getHotCodeList];
    [addCodeName addItemsWithTitles: clist];
    [addCodeName selectItemAtIndex: 0];
    recodeFlag = 1;
    if([self global: @"simpleflag"])
    {
        [newCodeName setStringValue: hcode];
        if([addCodeName itemWithTitle: hcode] != nil)
            [addCodeName selectItemWithTitle: hcode];
        else
            [addCodeName selectItemAtIndex: 0];
    }
    else
    {
        [addCodeName selectItemAtIndex: 0];
        [newCodeName setStringValue: @""];
    }
    
    [newCodeDef setString: @""];
    [inheritedColorSwitch setState: NSOnState];
    //   [codeColorMenu selectItemAtIndex:  [codeColorMenu indexOfItemWithTag: inheritedColor]];
    [myColorWell setColor: [gPrefBoss realColor]];
    
    [codePrompt setStringValue: @"Recode to:"];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    
    [NSApp beginSheet: addCodeWindow
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(addCodeDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}

-(BOOL) isOverlapped: (id) r1 and: (id) r2
{
    int b1, b2, e1, e2;
    
    b1 = TAMSTART(r1);
    b2 = TAMSTART(r2);
    e1 = TAMEND(r1);
    e2 = TAMEND(r2);
    
    if([r1 objectForKey: @"_doc"] != [r2 objectForKey: @"_doc"]) return NO;
    //if (r1 == r2) return NO;
    
    if( b1 <= b2 && e1 <= b2) return NO;
    if(b1 >= e2 && e1 >= e2) return NO;
    return YES;
    
}
-(NSString *) processRecodeWithOldCode: (NSString *) oldCode newCode: (NSString *) newCode onRecord: (NSString *) r1 range: (NSRange) rr
{
    BOOL pmode, q4ct;
    int tcnt;
    TAMSCharEngine *tx = [[TAMSCharEngine alloc] initWithString: r1];
    ctQChar *qq = [[ctQChar alloc] init];
    NSMutableString *newData = [NSMutableString string];
    
    [tx setEscFlag: 0];
    [tx startSearch];
    tcnt = 0;
    q4ct = NO;
    //[tx setCharLocation: rr.location];
    if(([tx getCharLocation] <= rr.location + rr.length) 
       && [tx getCharLocation] >= rr.location) pmode = YES; else pmode = NO;
       while([tx readnext: qq] != EOF)
       {
           switch([qq tokentype])
           {
               case TOKEN: 
               case ENDTOKEN:
                   if( [[qq buff] isEqualToString: oldCode] == YES && ((pmode && tcnt < 2) || q4ct ==YES))
                   {
                       tcnt++;
                       if([qq tokentype] == TOKEN) q4ct = YES;
                       [qq setBuff: newCode];
                       [newData appendString: stringForQChar(qq, NO)];
                   }
                   else
                       [newData appendString: stringForQChar(qq, NO)];
                   break;
               default: [newData appendString: stringForQChar(qq, NO)];
                   
           };
           if(([tx getCharLocation] <= rr.location + rr.length) 
              && [tx getCharLocation] >= rr.location) pmode = YES; else pmode = NO;
              
       }
       [tx release];
       [qq release];
       return newData;
       
}
-(NSString *) processAddcodeWithOldCode: (NSString *) oldCode newCode: (NSString *) newCode onRecord: (NSString *) r1 range: (NSRange) rr
{
    TAMSCharEngine *tx = [[TAMSCharEngine alloc] initWithString: r1];
    ctQChar *qq = [[ctQChar alloc] init];
    NSMutableString *newData = [NSMutableString string];
    int tcnt;
    BOOL pmode, q4ct;
    q4ct = NO;
    [tx setEscFlag: 0];
    [tx startSearch];
    //[tx setCharLocation: rr.location];
    tcnt =0;
    if(([tx getCharLocation] <= rr.location + rr.length) 
       && [tx getCharLocation] >= rr.location) pmode = YES; else pmode = NO;
       while([tx readnext: qq] != EOF)
       {
           switch([qq tokentype])
           {
               case TOKEN: 
               case ENDTOKEN:
                   if( [[qq buff] isEqualToString: oldCode] == YES && ((pmode && tcnt < 2) || q4ct))
                   {
                       if([qq tokentype] == TOKEN) q4ct = YES;
                       tcnt++;
                       [newData appendString: code2tag(newCode, (([qq tokentype] == TOKEN)? YES : NO),
                                                       YES, nil)];
                       [newData appendString: stringForQChar(qq, NO)];
                   }
                   else
                       [newData appendString: stringForQChar(qq, NO)];
                   break;
               default: [newData appendString: stringForQChar(qq, NO)];
                   
           };
           
           if(([tx getCharLocation] <= rr.location + rr.length) 
              && [tx getCharLocation] >= rr.location) pmode = YES; else pmode = NO;
              
       }
       [tx release];
       [qq release];
       return newData;
       
}
-(void) adjustAllToRecodeWithNewCode: (NSString *) newCode oldCode: (NSString *) oldCode keyRecord: (id) rr keyData: (NSString *) kd
{
    NSRange rrr;
    NSString * rstr;    
    FORALL(backData)
    {
        int b1, b2, e1, e2, l1, l2;
        b1 = TAMSTART(rr);
        b2 = TAMSTART(temp);
        e1 = TAMEND(rr);
        e2 = TAMEND(temp);
        l2 = [[temp objectForKey: @"_data"] length];
        l1 = [kd length];
        if(TAMSTART(rr) == TAMSTART(temp) && TAMEND(rr) == TAMEND(temp))
        {
            [temp setObject: [[newCode copy] autorelease] forKey: @"_code"];
        }
        if([self isOverlapped: temp and: rr])
        {
            if(b1 <= b2) rrr.location = 0;
            else
                rrr.location = b1 - b2;
            if(e1 >= e2) rrr.length = 1+e2 - (b2 + rrr.location)  + ((l1 - (e2 - b2) > 0) ? l1 - (e2 -b2) : (e2-b2) - l1);
            
            else  rrr.length = 1+e1 - (b2 + rrr.location) + 
                ((l1 - (e2 - b2) > 0) ? l1 - (e2 -b2) : (e2-b2) - l1);
            rstr = [self processRecodeWithOldCode: oldCode 
                                          newCode: newCode onRecord: [temp objectForKey: @"_data"] range: rrr];
            [temp setObject: rstr forKey: @"_data"];
        }
        
    }
    ENDFORALL;
}
-(void) adjustAllToAddcodeWithNewCode: (NSString *) newCode oldCode: (NSString *) oldCode keyRecord: (id) rr keyData: (NSString *) kd
{
    NSRange rrr;
    NSString * rstr;    
    FORALL(backData)
    {
        int b1, b2, e1, e2, l1, l2;
        b1 = TAMSTART(rr);
        b2 = TAMSTART(temp);
        e1 = TAMEND(rr);
        e2 = TAMEND(temp);
        l2 = [[temp objectForKey: @"_data"] length];
        l1 = [kd length];
        if([self isOverlapped: temp and: rr])
        {
            if(b1 < b2) rrr.location = 0;
            else
                rrr.location = b2 - b1;
            if(e2 >= e1) rrr.length = 1+b2 - (b2 + rrr.location)  + ((l1 - (e2 - b2) > 0) ? l1 - (e2 -b2) : (e2-b2) - l1);
            else  rrr.length = 1+e1 - (b2 + rrr.location)  + ((l1 - (e2 - b2) > 0) ? l1 - (e2 -b2) : (e2-b2) - l1);
            rstr = [self processAddcodeWithOldCode: oldCode 
                                           newCode: newCode onRecord: [temp objectForKey: @"_data"] range: rrr];
            [temp setObject: rstr forKey: @"_data"];
        }
        
    }
    ENDFORALL;
}
-(void)handleResultsDidChange: (NSNotification *) not
{
    NSDictionary *myDat = [not userInfo];
    if([[myDat objectForKey: @"type"] isEqualToString: @"r"] == YES)
    {
        [self adjustAllToRecodeWithNewCode:
            [myDat objectForKey: @"newCode"]
                                   oldCode: [myDat objectForKey: @"oldCode"]
                                 keyRecord: [myDat objectForKey: @"keyRecord"]
                                   keyData: [myDat objectForKey: @"keyData"]];//[[myDat objectForKey: @"keyRecord"] objectForKey: @"_data"]];
    }
    else
    {
        [self adjustAllToAddcodeWithNewCode:
            [myDat objectForKey: @"newCode"]
                                    oldCode: [myDat objectForKey: @"oldCode"]
                                  keyRecord: [myDat objectForKey: @"keyRecord"]
                                    keyData: [myDat objectForKey: @"keyData"]];
    }
    
}

-(void) addCodeDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    NSMutableArray *myLocalRecs;
    id myRec;
    NSEnumerator *locList;
    NSMutableString *oldCode;
    NSMutableString *newData;
    oldCode = [NSMutableString string];
    
    if(recodeFlag == 0) //this is addcode
    {
	if([markedList count])
	{
	    if(returnCode == 1)
	    {
		//Something there?
		if([lgNewCodeName isEqualToString: @""] == YES) return;
		//is it a new definition?
                if(lgNewCodeMode == CODEMODENEW)
                {
                    if(lgNewCodeColor == otherColor)
                        [gWorkBench newCode: lgNewCodeName definition: lgNewCodeDef
                                  realColor: lgNewRealColor];
                    else
                        [gWorkBench newCode: lgNewCodeName definition: lgNewCodeDef
                                      color: lgNewCodeColor];
                }
		//copy records
		myLocalRecs = [[NSMutableArray alloc] init];
		[myLocalRecs setArray: markedList];
		
		//reverse sort
		[myLocalRecs sortUsingFunction: locationFwdComp context: nil];
                
		//go through and call the main docuement
		locList = [myLocalRecs reverseObjectEnumerator];
		while(myRec = [locList nextObject])
		{
                    if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
                    {
                        if([gPrefBoss batchOpenFiles])
                            [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
                        else
                            [(MWFile *)[myRec objectForKey: @"_doc"] setOpenFakeFileWithWorkBench: gWorkBench];
                    }
                    
		    [[[myRec objectForKey: @"_doc"] filePointer] addCode: lgNewCodeName
                                                                    from: [[myRec objectForKey:@"_begin_loc"] intValue]
                                                                      to: [[myRec objectForKey:@"_end_loc"] intValue] from: self
                                                                 withDef: @""];
                    if([self global: @"simpleflag"])
                    {
                        NSString *rstr;
                        [oldCode setString: [myRec objectForKey: @"_code"]];
                        if([gPrefBoss guessUpdate] == NO)
                        {
                            rstr = [self processAddcodeWithOldCode: oldCode newCode: lgNewCodeName
                                                          onRecord: [myRec objectForKey: @"_data"] range: NSMakeRange(0, [[myRec objectForKey: @"_data"] length])];
                            
                            [myRec setObject: rstr
                                      forKey: @"_data"];
                        }
                        else
                        {
                            NSMutableDictionary *mynots = [NSMutableDictionary dictionary];
                            [mynots setObject: self forKey: @"origin"];
                            [mynots setObject: [[lgNewCodeName copy] autorelease] forKey: @"newCode"];
                            [mynots setObject: @"a" forKey: @"type"];
                            [mynots setObject: [[oldCode copy] autorelease] forKey: @"oldCode"];
                            [mynots setObject: myRec forKey: @"keyRecord"];
                            [mynots setObject: [myRec objectForKey: @"_data"] 
                                       forKey: @"keyData"];
                            
                            
                            [[NSNotificationCenter defaultCenter] postNotificationName: @"TAMSResultDidChange"
                                                                                object: gWorkBench userInfo: mynots];
                            /*[self adjustAllToAddcodeWithNewCode: lgNewCodeName 
oldCode: oldCode keyRecord: myRec];*/
                        }
                    }
		}
                if([gPrefBoss batchOpenFiles] == 0)
                {
                    locList = [myLocalRecs reverseObjectEnumerator];
                    while(myRec = [locList nextObject])
                    {
                        [(MWFile *)[myRec objectForKey: @"_doc"] closeFakeFile];    
                        
                    }
                }
                [self updateRecCountAtRow];
                if([gPrefBoss cancelAfterAddCode] == 1)
                    [self doUnmarkAll: nil];
		//have it reload
		if([gPrefBoss autoReloadValue])
		    [self refreshResults: self];
                [self displaySelData];
	    }
	}
	else
	{
	}
    }
    else if (recodeFlag == 1)
    {
	if([markedList count])
	{
	    if(returnCode == 1)
	    {
                
		//is there something there?
		if([lgNewCodeName isEqualToString: @""] == YES) return;
		//refresh?
                if(lgNewCodeMode == CODEMODENEW)
                {
                    if(lgNewCodeColor == otherColor)
                        [gWorkBench newCode: lgNewCodeName definition: lgNewCodeDef
                                  realColor: lgNewRealColor];
                    else
                        [gWorkBench newCode: lgNewCodeName definition: lgNewCodeDef
                                      color: lgNewCodeColor];
                }
		//copy records
		myLocalRecs = [[NSMutableArray alloc] init];
		[myLocalRecs setArray: markedList];
		
		//reverse sort
		[myLocalRecs sortUsingFunction: locationComp context: nil];
                
		//go through and call the main docuement
		locList = [markedList reverseObjectEnumerator];
		while(myRec = [locList nextObject])
		{
                    if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
                    {
                        if([gPrefBoss batchOpenFiles] == 1)
                            [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
                        else
                            [(MWFile *)[myRec objectForKey: @"_doc"] setOpenFakeFileWithWorkBench: gWorkBench];
                    }
                    
		    [[[myRec objectForKey: @"_doc"] filePointer] recode: lgNewCodeName
                                                                  first: [[myRec objectForKey:@"_begin_loc"] intValue]
                                                                   last: [[myRec objectForKey:@"_end_loc"] intValue] from: self
                                                                withDef: @""];
                    [oldCode setString: [myRec objectForKey: @"_code"]];
                    /*
                     This is too crude, but is the start of refreshing the actual data,
                     what would need to happen is have tce or some such object translate this*/
                    
                    
                    {
                        NSString *rstr;
                        if([gPrefBoss guessUpdate] == NO)
                        {
                            [myRec setObject: [[lgNewCodeName copy] autorelease] forKey: @"_code"]; 
                            rstr = [self processRecodeWithOldCode: oldCode newCode: lgNewCodeName
                                                         onRecord: [myRec objectForKey: @"_data"] range: NSMakeRange(0, [[myRec objectForKey: @"_data"] length])];
                            
                            [myRec setObject: rstr
                                      forKey: @"_data"]; 
                        }
                        else
                        {
                            NSMutableDictionary *mynots = [NSMutableDictionary dictionary];
                            [mynots setObject: self forKey: @"origin"];
                            [mynots setObject: [[lgNewCodeName copy]autorelease] forKey: @"newCode"];
                            [mynots setObject: @"r" forKey: @"type"];
                            [mynots setObject: [[oldCode copy] autorelease] forKey: @"oldCode"];
                            [mynots setObject: myRec forKey: @"keyRecord"];
                            [mynots setObject: [[[myRec objectForKey: @"_data"] copy] autorelease] forKey: @"keyData"];
                            
                            /*[self adjustAllToRecodeWithNewCode: lgNewCodeName 
oldCode: oldCode keyRecord: myRec];*/
                            
                            [[NSNotificationCenter defaultCenter] postNotificationName: @"TAMSResultDidChange"
                                                                                object: gWorkBench userInfo: mynots];
                        }
                    }
		}
                if([gPrefBoss batchOpenFiles] == 0)
                {
                    locList = [myLocalRecs reverseObjectEnumerator];
                    while(myRec = [locList nextObject])
                    {
                        [(MWFile *)[myRec objectForKey: @"_doc"] closeFakeFile];    
                        
                    }
                }
		//have it reload
                [self updateRecCountAtRow];
                if([gPrefBoss cancelAfterRecode] == 1)
                    [self doUnmarkAll: nil];
		if([gPrefBoss autoReloadValue])
		    [self refreshResults: self];
                [self displaySelData];
                [myLocalRecs autorelease];
	    }
	}
	else
	{
	}
    }
    else if (recodeFlag == 2) //add root class
    {
	if([markedList count])
	{
	    if(returnCode == 1)
	    {
                NSMutableString *myNewPrefix;
                int m, i;
		//is there something there?
		if([lgNewCodeName isEqualToString: @""] == YES) return;
                myNewPrefix = [[NSMutableString alloc] initWithString: lgNewCodeName];
                m = [myNewPrefix length];
                
                trimNSS(myNewPrefix);
                
                for(i = m -1; i >= 0; i--) 
                {
                    if([myNewPrefix characterAtIndex: i] == '>')
                        [myNewPrefix deleteCharactersInRange: NSMakeRange(i,1)];
                    else
                        break;
                }
                
                {
                    if(lgNewCodeColor == otherColor)
                        [gWorkBench newCode: myNewPrefix definition: @""
                                  realColor: lgNewRealColor];
                    else
                        [gWorkBench newCode: myNewPrefix definition: @""
                                      color: lgNewCodeColor];
                }
		//refresh?
		//copy records
		myLocalRecs = [[NSMutableArray alloc] init];
		[myLocalRecs setArray: markedList];
		
		//reverse sort
		[myLocalRecs sortUsingFunction: locationComp context: nil];
		//go through and call the main docuement
		locList = [markedList reverseObjectEnumerator];
		while(myRec = [locList nextObject])
		{
                    NSString *myHierCode;
                    if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
                    {
                        if([gPrefBoss batchOpenFiles] == 1)
                            [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
                        else
                            [(MWFile *)[myRec objectForKey: @"_doc"] setOpenFakeFileWithWorkBench: gWorkBench];
                    }
                    myHierCode = [NSString stringWithFormat: @"%@>%@", myNewPrefix, [myRec objectForKey: @"_code"]];
                    [myHierCode retain];
		    [[[myRec objectForKey: @"_doc"] filePointer] recode: myHierCode
                                                                  first: [[myRec objectForKey:@"_begin_loc"] intValue]
                                                                   last: [[myRec objectForKey:@"_end_loc"] intValue] from: self
                                                                withDef: @""];
                    [oldCode setString: [myRec objectForKey: @"_code"]];
                    /*
                     This is too crude, but is the start of refreshing the actual data,
                     what would need to happen is have tce or some such object translate this*/
                    
                    
                    {
                        NSString *rstr;
                        if([gPrefBoss guessUpdate] == NO)
                        {
                            [myRec setObject: [[myHierCode copy] autorelease] forKey: @"_code"]; 
                            rstr = [self processRecodeWithOldCode: oldCode newCode: myHierCode
                                                         onRecord: [myRec objectForKey: @"_data"] range: NSMakeRange(0, [[myRec objectForKey: @"_data"] length])];
                            
                            [myRec setObject: rstr
                                      forKey: @"_data"]; 
                        }
                        else
                        {
                            NSMutableDictionary *mynots = [NSMutableDictionary dictionary];
                            [mynots setObject: self forKey: @"origin"];
                            [mynots setObject: [[myHierCode copy]autorelease] forKey: @"newCode"];
                            [mynots setObject: @"r" forKey: @"type"];
                            [mynots setObject: [[oldCode copy] autorelease] forKey: @"oldCode"];
                            [mynots setObject: myRec forKey: @"keyRecord"];
                            [mynots setObject: [[[myRec objectForKey: @"_data"] copy] autorelease] forKey: @"keyData"];
                            
                            /*[self adjustAllToRecodeWithNewCode: lgNewCodeName 
oldCode: oldCode keyRecord: myRec];*/
                            
                            [[NSNotificationCenter defaultCenter] postNotificationName: @"TAMSResultDidChange"
                                                                                object: gWorkBench userInfo: mynots];
                        }
                    }
                    [myHierCode autorelease];
		}
                if([gPrefBoss batchOpenFiles] == 0)
                {
                    locList = [myLocalRecs reverseObjectEnumerator];
                    while(myRec = [locList nextObject])
                    {
                        [(MWFile *)[myRec objectForKey: @"_doc"] closeFakeFile];    
                        
                    }
                }
		//have it reload
                [self updateRecCountAtRow];
                if([gPrefBoss cancelAfterRecode] == 1)
                    [self doUnmarkAll: nil];
		if([gPrefBoss autoReloadValue])
		    [self refreshResults: self];
                [self displaySelData];
                [myNewPrefix release];
                [myLocalRecs autorelease];
	    }
	}
	else
	{
	}
    }
    else if (recodeFlag == 3) //del root code
    {
	if([markedList count])
	{
	    if(returnCode == 1)
	    {
                NSMutableString *oldDataCode;
                int m, i;
                int clevel;
		//is there something there?
                clevel = [delRootLevels intValue];
                if(clevel <= 0) return;
                
                oldDataCode = [[NSMutableString alloc] init];
		//refresh?
		//copy records
		myLocalRecs = [[NSMutableArray alloc] init];
		[myLocalRecs setArray: markedList];
		
		//reverse sort
		[myLocalRecs sortUsingFunction: locationComp context: nil];
		//go through and call the main docuement
		locList = [markedList reverseObjectEnumerator];
		while(myRec = [locList nextObject])
		{
                    int oclevel;
                    NSString *myHierCode;
                    if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
                    {
                        if([gPrefBoss batchOpenFiles] == 1)
                            [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
                        else
                            [(MWFile *)[myRec objectForKey: @"_doc"] setOpenFakeFileWithWorkBench: gWorkBench];
                    }
                    [oldDataCode setString: [myRec objectForKey: @"_code"]];
                    oclevel = [oldDataCode numberOfCodeComponents];
                    if(clevel < oclevel)
                        myHierCode = [oldDataCode lastCodeComponents: oclevel - clevel];
                    else
                        myHierCode = [oldDataCode lastCodeComponent];
                    [myHierCode retain];
		    [[[myRec objectForKey: @"_doc"] filePointer] recode: myHierCode
                                                                  first: [[myRec objectForKey:@"_begin_loc"] intValue]
                                                                   last: [[myRec objectForKey:@"_end_loc"] intValue] from: self
                                                                withDef: @""];
                    [oldCode setString: [myRec objectForKey: @"_code"]];
                    /*
                     This is too crude, but is the start of refreshing the actual data,
                     what would need to happen is have tce or some such object translate this*/
                    
                    
                    {
                        NSString *rstr;
                        if([gPrefBoss guessUpdate] == NO)
                        {
                            [myRec setObject: [[lgNewCodeName copy] autorelease] forKey: @"_code"]; 
                            rstr = [self processRecodeWithOldCode: oldDataCode newCode: myHierCode
                                                         onRecord: [myRec objectForKey: @"_data"] range: NSMakeRange(0, [[myRec objectForKey: @"_data"] length])];
                            
                            [myRec setObject: rstr
                                      forKey: @"_data"]; 
                        }
                        else
                        {
                            NSMutableDictionary *mynots = [NSMutableDictionary dictionary];
                            [mynots setObject: self forKey: @"origin"];
                            [mynots setObject: [[myHierCode copy]autorelease] forKey: @"newCode"];
                            [mynots setObject: @"r" forKey: @"type"];
                            [mynots setObject: [[oldDataCode copy] autorelease] forKey: @"oldCode"];
                            [mynots setObject: myRec forKey: @"keyRecord"];
                            [mynots setObject: [[[myRec objectForKey: @"_data"] copy] autorelease] forKey: @"keyData"];
                            
                            /*[self adjustAllToRecodeWithNewCode: lgNewCodeName 
oldCode: oldCode keyRecord: myRec];*/
                            
                            [[NSNotificationCenter defaultCenter] postNotificationName: @"TAMSResultDidChange"
                                                                                object: gWorkBench userInfo: mynots];
                        }
                    }
                    [myHierCode autorelease];
		}
                if([gPrefBoss batchOpenFiles] == 0)
                {
                    locList = [myLocalRecs reverseObjectEnumerator];
                    while(myRec = [locList nextObject])
                    {
                        [(MWFile *)[myRec objectForKey: @"_doc"] closeFakeFile];    
                        
                    }
                }
		//have it reload
                [self updateRecCountAtRow];
                if([gPrefBoss cancelAfterRecode] == 1)
                    [self doUnmarkAll: nil];
		if([gPrefBoss autoReloadValue])
		    [self refreshResults: self];
                [self displaySelData];
                [oldDataCode release];
                [myLocalRecs autorelease];
	    }
	}
	else
	{
	}
    }
    
}
-(IBAction) doAddCode: (id) sender
{
    NSArray *clist;
    NSWindow *who;
    NSString *hcode;
    
    if(![markedList count]) return;
    DIRTYWARN;
    hcode = [[markedList objectAtIndex: 0] objectForKey: @"_code"];
    //delete the menu items
    if([addCodeName numberOfItems])
        [addCodeName removeAllItems];
    //get a fresh list
    //add new
    //[addCodeName addItemWithTitle: @"New"];
    clist = [gWorkBench getHotCodeList];
    [addCodeName addItemsWithTitles: clist];
    [addCodeName selectItemAtIndex: 0];
    recodeFlag = 0;
    [codePrompt setStringValue: @"Code to add:"];
    if([self global: @"simpleflag"])
    {
	[newCodeName setStringValue: hcode];
        if([addCodeName itemWithTitle: hcode] != nil)
            [addCodeName selectItemWithTitle: hcode];
        else
            [addCodeName selectItemAtIndex: 0];
    }
    else
    {
	[newCodeName setStringValue: @""];
        [addCodeName selectItemAtIndex: 0];
        
    }
    [newCodeDef setString: @""];
    [inheritedColorSwitch setState: NSOnState];
    //        [codeColorMenu selectItemAtIndex: 
    //           [codeColorMenu indexOfItemWithTag: inheritedColor]];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    
    
    [NSApp beginSheet: addCodeWindow
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(addCodeDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
    //return if nothing there
    //copy the records
    //reverse sort them
    //go through and call the main document
    //have it add a code
    
}

-(IBAction) cancelAddRoot: (id) sender
{
    [addRootPane orderOut: sender];
    [NSApp endSheet: addRootPane returnCode: 0];
    
}
-(IBAction) okAddRoot: (id) sender
{
    if([addRootInherited state] == NSOnState)
        lgNewCodeColor = inheritedColor;
    else
        lgNewCodeColor = otherColor;
    //lgNewCodeColor = [[codeColorMenu selectedItem] tag];
    lgNewRealColor = [addRootColor color];
    [lgNewCodeName setString: [addRootName stringValue]];
    [addRootPane orderOut: sender];
    [NSApp endSheet: addRootPane returnCode: 1];
    
}
-(IBAction) toggleAddRootColor: (id) sender
{
    [addRootInherited setState: NSOffState];
}
-(IBAction) doAddRootCode: (id) sender
{
    NSArray *clist;
    NSWindow *who;
    NSString *hcode;
    
    if(![markedList count]) return;
    if(![self global: @"simpleflag"])
    {
        NSWARNING(@"Add root code only works with simple searches.");
        return;
    }
    recodeFlag = 2;
    
    [addRootName setStringValue: @""];
    [addRootInherited setState: NSOnState];
    //        [codeColorMenu selectItemAtIndex: 
    //           [codeColorMenu indexOfItemWithTag: inheritedColor]];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    
    
    [NSApp beginSheet: addRootPane
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(addCodeDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
    //return if nothing there
    //copy the records
    //reverse sort them
    //go through and call the main document
    //have it add a code
    
}
-(IBAction) cancelDelRoot: (id) sender
{
    [delRootPane orderOut: sender];
    [NSApp endSheet: delRootPane returnCode: 0];
    
}
-(IBAction) okDelRoot: (id) sender
{
    [delRootPane orderOut: sender];
    [NSApp endSheet: delRootPane returnCode: 1];
    
}

-(IBAction) doDelRootCode: (id) sender
{
    NSArray *clist;
    NSWindow *who;
    NSString *hcode;
    
    if(![markedList count]) return;
    if(![self global: @"simpleflag"])
    {
        NSWARNING(@"Delete root code only works with simple searches.");
        return;
    }
    recodeFlag = 3;
    
    [delRootLevels setStringValue: @"1"];
    //        [codeColorMenu selectItemAtIndex: 
    //           [codeColorMenu indexOfItemWithTag: inheritedColor]];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    
    
    [NSApp beginSheet: delRootPane
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(addCodeDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
    //return if nothing there
    //copy the records
    //reverse sort them
    //go through and call the main document
    //have it add a code
    
}

-(BOOL) isMarked: (int) row
{
    if([markedList indexOfObject: [myData objectAtIndex: row]] == NSNotFound)
	return NO;
    else return YES;
}

-(BOOL) isMarkedRecord: (id) theRecord
{
    if([markedList indexOfObject: theRecord] == NSNotFound)
	return NO;
    else return YES;
}

-(void) printShowingPrintPanel: (BOOL) flag
   //-(IBAction) printDocument: (id) sender
   //-(IBAction) print: (id) Sender
{
    NSPrintInfo *printInfo = [self printInfo];
    NSPrintOperation *printOp;
    [printInfo setOrientation: NSLandscapeOrientation];
    [printInfo setHorizontalPagination: NSFitPagination];
    printOp = [NSPrintOperation printOperationWithView: theResults
                                             printInfo: printInfo];
    [printOp setShowPanels: YES];//flag];
        [printOp runOperation];
}


- (NSString *)windowNibName {
    // Implement this to return a nib to load OR implement -makeWindowControllers to manually create your controllers.
    return @"myPanedResults";
}
-(NSMutableArray *) arrayFromSubset: (NSArray *) who
{
    int n;
    NSMutableArray *newArr = [[NSMutableArray alloc] init];
    
    FORALL(who)
    {
        if((n = [backData indexOfObject: temp]) != NSNotFound)
        {
            
            [newArr addObject: [NSString stringWithFormat: @"%d", n]];
        }
    }
    ENDFORALL;
    return newArr;
    
}
- (NSData *)dataRepresentationOfType:(NSString *)type {
    // Implement to provide a persistent data representation of your document OR remove this and implement the file-wrapper or file path based save methods.
    NSMutableData *dd;
    
    int first;
    int ab;
    int cnt;
    MWFile *theDPtr;
    NSMutableArray *nameList, *fixedDataArray, *rootArray, *nKeys;
    NSMutableDictionary *nSets;
    unichar newLineChar;
    dd = [[NSMutableData alloc] init];
#ifdef USESXML

    if([type isEqualToString: @"XML TAMS Result"])
    {
        return [self keyedDataRepresentation];
    }
#endif
    if([type isEqualToString: @"TAMS Result"])
    {
        rootArray = [[NSMutableArray alloc] init];
        if(gWorkBench)
        {
            ab = [gWorkBench absPath];
        }
        else
            ab = ABSPATHMODE;
        //1. save the version
        [rootArray addObject: @"10"];
        FORALL(fileList)
        {
            if([temp hasFile] == NO)
            {
                NSWARNING(@"Cannot save in TAMS format until all source files have been saved.");
                return nil;
            }
        }
        ENDFORALL;
        
        //2. save the globals
        [rootArray addObject: [myGlobals getGlobals]];
        //3. save the file list
        nameList = [[NSMutableArray alloc] init];
        FORALL(fileList)
        {
            [nameList addObject: [[(MWFile *) temp name] copy]];
        }
        ENDFORALL;
        [rootArray addObject: nameList];
        
        //4. save the data
        fixedDataArray = [[NSMutableArray alloc] init];
        FORALL(backData)
        {
            NSMutableDictionary *what;
            MWFile *myObj;
            
            what = [[NSMutableDictionary alloc] init];
            [what addEntriesFromDictionary: temp];
            myObj = [temp objectForKey: @"_doc"];
            [what setObject: [[myObj name] copy] forKey: @"_doc"];
            [fixedDataArray addObject: what];
        }
        ENDFORALL;
        [rootArray addObject: fixedDataArray];
        
        //5. save the visible data
        [rootArray addObject: [self arrayFromSubset: myData]];	
        
        //6. save the named sets
        nSets = [[NSMutableDictionary alloc] init];
        nKeys = [namedSelDict allKeys];
        FORALL(nKeys)
        {
            [nSets setObject: [self arrayFromSubset: 
                [namedSelDict objectForKey: temp]] forKey: temp];
        }
        ENDFORALL;
        [rootArray addObject: nSets];
        //7. the limit string
        if(limitString)
            [rootArray addObject: limitString];
        else
            [rootArray addObject: @""];
        //8. the list of columns
        [rootArray addObject: colList];
        //9. the current string
        [rootArray addObject: [[[limitField stringValue] copy] autorelease]];
        //10. save the coder
        [rootArray addObject: [[codersString copy] autorelease]];
        //11. save autosets
        [rootArray addObject: [self autoSets]];
        //12. save the selected row
        [rootArray addObject: [NSNumber numberWithInt: [theResults selectedRow]]];
        //13. save marked list
        [rootArray addObject: [self arrayFromSubset: markedList]];
        //14. save summary reports
        [rootArray addObject: summReports];
        //15. save date string
        [rootArray addObject: [[dfString copy] autorelease]];
        [rootArray addObject: [NSNumber numberWithInt: dfIndex]];
        //16. save auto history
        [rootArray addObject: autoHistory];
        [rootArray addObject: [[autoHistoryStart copy] autorelease]];
        //17. save media dictionary
        [rootArray addObject: [[mediaDict copy] autorelease]];
        dd = [NSArchiver archivedDataWithRootObject: rootArray];
        return dd;
    }
    
#ifdef HIER
    if([type isEqualToString: @"HierFormat1"] == YES)
    {
	//make an array
	unichar retChar;
	NSMutableArray aaa = [[NSMutableArray alloc] init];
	NSMutableString sss = [[NSMutableString alloc] init];
	if([gPrefBoss macNLValue])
	{
	    retchar = '\n';
	    newLineChar = '\r';
	}
	else
	{
	    retchar = '\r';
	    newLineChar = '\n';
	}
	if([myData count] == 0) {[dd release]; [aaa release]; return nil;}
	[aaa addObjectsFromArray: myData];
	//sort it
	[aaa sortUsingFunction: stringComp context: @"_code"];
        
	//set the first tag
	[sss setString: [[myData objectAtIndex: 0] objectForKey @"_code"]];
	//print the head of the tree
	DATASTRING(dd, limitString);
	DATACHAR(dd, newLineChar);
	//print the first tag
	DATATAB(dd);
	DATASTRING(dd, sss);
	//loop til end of array
	FORALL(aaa)
	{
	    NSMutableString *thisTag = [[NSMutableString alloc] init];
	    //set this tag
	    [thisTag setString: [temp objectForKey: @"_code"]];
	    
	    //if this tag is != to last tag
	    if([thisTag isEqualToString: sss] == NO)
	    {
		//print new tag
		DATATAB(dd);
		DATASTRING(dd, thisTag);
		[sss setString: thisTag];
	    }
	    //print the data
	    DATATAB(dd);DATATAB(dd);
	    DATASTRING(dd, [temp objectForKey: @"_data"]);
	    //add all the extra stuff
	    DATACHAR(dd, '['); DATASTRING(dd, thisTab); DATACHAR(dd, ']');
	    //and a return
	    DATACHAR(dd, newLineChar);
	}
    }
    else
#endif
#ifdef XML
	;
    if([type isEqualToString: @"XML"] == YES)
    {
	DATASTRING(dd,@"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
	DATANL(dd);
	DATASTRING(dd,@"<tamsdata>"); DATANL(dd);
	cnt = 0;
	FORALL(myData)
	{
	    id key;
	    id ans;
	    NSEnumerator *ns;
	    NSMutableString *sss=[[NSMutableString alloc] init];
	    
            // DATASTRING(dd, [[NSNumber numberWithInt: cnt] stringValue]);
	    cnt++;
	    ns = [colList objectEnumerator];
	    DATATAB(dd); DATASTRING(dd, @"<tamsrecord recnum=\"");
	    DATASTRING(dd, [[NSNumber numberWithInt: cnt] stringValue]);
	    DATASTRING(dd,@"\">");DATANL(dd);
	    while(key = [ns nextObject])
	    {
		ans = [temp objectForKey: key];
		//if([ans length] == 0) continue;
		DATATAB(dd);
		DATATAB(dd);
		if([key isEqualToString: @"_begin_loc"] == YES)
		{
		    DATASTRING(dd, @"<");DATASTRING(dd, key); DATASTRING(dd, @">");
		    DATASTRING(dd, ans);
		    DATASTRING(dd, @"</");DATASTRING(dd, key); DATASTRING(dd, @">");DATANL(dd);
                    
		    DATATAB(dd);
		    DATATAB(dd);
		    DATASTRING(dd, @"<_end_loc>");
		    DATASTRING(dd, [temp objectForKey: @"_end_loc"]);
		    DATASTRING(dd, @"</_end_loc>");DATANL(dd);
                    
		    //do the document stuff here
		}
                else if([key isEqualToString: @"_line_number"] == YES)
                {
		    DATASTRING(dd, @"<");DATASTRING(dd, key); DATASTRING(dd, @">");
		    DATASTRING(dd, ans);
		    DATASTRING(dd, @"</");DATASTRING(dd, key); DATASTRING(dd, @">");DATANL(dd);
                    
                }
                else if([key isEqualToString: @"_doc"] == YES)
                {
		    theDPtr = [temp objectForKey: @"_doc"];
		    
		    DATATAB(dd);
		    DATATAB(dd);
		    DATASTRING(dd, @"<_document>");
		    if([gWorkBench mwFileExists: (MWFile*)theDPtr] == YES)
		    {
                        if([theDPtr hasFile] == YES)
                            DATASTRING(dd, [theDPtr path]);
                        else
                            DATASTRING(dd, [theDPtr name]);
		    }
		    else
		    {
			DATASTRING(dd,@"???");
		    }
		    DATASTRING(dd, @"</_document>");DATANL(dd);
                    
                }
		else
		{
		    [sss setString: ans];
                    if([sss length] > 0)
                        [sss replaceOccurrencesOfString: @">" withString: @":" options: NSCaseInsensitiveSearch range: NSMakeRange(0, [sss length])];
		    DATASTRING(dd, @"<");DATASTRING(dd, key); DATASTRING(dd, @">");
                    if([key isEqualToString: @"_data"] == YES)
                    {
                        //this just inserts the line number and an escaped tab if appropriate
                        NSNumber * what;
                        
                        what = [temp objectForKey: @"_line_number"];
                        if(what != nil)
                        {
                            if([what intValue] > 0 && [gPrefBoss TAScanForLN] == 1)
                            {
                                DATASTRING(dd, what);
                                DATASTRING(dd, @"\\t");
                            }
                        }
                    }
                    
                    DATASTRING(dd, sss);
                    DATASTRING(dd, @"</");DATASTRING(dd, key); DATASTRING(dd, @">");DATANL(dd);
                    
		}
	    }
	    [sss release];
            
	    DATATAB(dd); DATASTRING(dd, @"</tamsrecord>");DATANL(dd);
	}
	ENDFORALL;
	DATASTRING(dd,@"</tamsdata>"); DATANL(dd);
        
    }
    else
#endif
        //This is text
    {
	if([gPrefBoss macNLValue])
	    newLineChar = '\r';
	else
	    newLineChar = '\n';
	first = 1;
	cnt = 1;
	if([myData count] == 0) {[dd release]; return nil;}
	//write the headers
	if([self global: @"headerflag"])
	{
	    DATACHAR(dd, '#');
	    FORALL(colList)
	    {
		DATACHAR(dd,'\t');
		DATASTRING(dd, temp);
	    }
	    ENDFORALL;
	    DATATAB(dd); 
	    DATASTRING(dd, @"_end_loc");
	    DATACHAR(dd, newLineChar);
	}
	
	FORALL(myData)
	{
	    id key;
	    id ans;
	    NSEnumerator *ns;
	    
	    DATASTRING(dd, [[NSNumber numberWithInt: cnt] stringValue]);
	    cnt++;
	    ns = [colList objectEnumerator];
	    while(key = [ns nextObject])
	    {
		DATATAB(dd);
		ans = [temp objectForKey: key];
		if([key isEqualToString: @"_data"] == YES)
                {
                    //this just inserts the line number and an escaped tab if appropriate
                    NSNumber * what;
                    
                    what = [temp objectForKey: @"_line_number"];
                    if(what != nil)
                    {
                        if([what intValue] > 0 && [gPrefBoss TAScanForLN] == 1)
                        {
                            DATASTRING(dd, what);
                            DATASTRING(dd, @"\\t");
                        }
                    }
                }
		if([key isEqualToString: @"_begin_loc"] == YES)
		{
		    DATASTRING(dd, ans /*[ans stringValue] */);
		    DATATAB(dd);
		    DATASTRING(dd, [temp objectForKey: @"_end_loc"] );
		    //do the document stuff here
		}
                else if( [key isEqualToString: @"_line_number"] == YES)
                {
		    DATASTRING(dd, ans /*[ans stringValue]*/);
                    
                }
                else if([key isEqualToString: @"_doc"] == YES)
                {
		    theDPtr = [temp objectForKey: @"_doc"];
		    if([gWorkBench mwFileExists: (MWFile *)theDPtr] == YES)
		    {
                        if([(MWFile *) theDPtr hasFile] == YES)
                        {
                            DATASTRING(dd, [theDPtr path]);
                        }
                        else
                        {
                            DATASTRING(dd, [theDPtr name]);
                        }
                        
		    }
		    else
		    {
			DATASTRING(dd,@"???");
		    }
                    
                }
		else
		{
		    DATASTRING(dd, ans);
                    
		}
	    }
	    DATACHAR(dd, newLineChar);;
	}
	ENDFORALL;
    }
    //[myWindow setDocumentEdited: NO];
    //[self updateChangeCount: NSChangeCleared];
    
    [dd retain];
    return dd;
}
/*
 - (void)document:(NSDocument *)doc didSave:(BOOL)didSave contextInfo:(void *)contextInfo
 {
     if(didSave == YES)
     {
         [myWindow setDocumentEdited: NO];
         [self updateChangeCount: NSChangeCleared];
	 NSLog(@"result name $@\n",[self fileName]);
         //[self autorelease];
     }
     
     
 }
 */
-(IBAction) niceClose: (id) Sender
{
    [myWindow performClose: self];
}

-(void) setTitleFromFile
{
    if([[self getMWFile] hasFile])
    {
        [myWindow setTitle: [[self getMWFile] name]];
    }
}

-(void) willClose
{
    // [self saveDocumentWithDelegate: self didSaveSelector: 
    //    @selector(document:didSave:contextInfo:) contextInfo:(void *)nil];	    
    if(gWorkBench)
    {
        if([self fileName])
        {
            [[self getMWFile] setOpenFile: self];
            [[self getMWFile] setHasFile: YES];
        }
        else
        {
            [[self getMWFile] setOpen: NO];
            [[self getMWFile] setHasFile: NO];
        }
    }
    if(gWorkBench){
        if([[self getMWFile] hasFile] == NO) 
        {
            [[self getMWFile] setOpen: NO];
            [gWorkBench unregisterResult: [self getMWFile]];
            gWorkBench = nil;
            //should release it as well
        }
        else
        {
            [[self getMWFile] setOpen: NO];
        }
    }
    else
        [[self getMWFile] setOpen: NO];
    
    //[self disconnect];
    [[NSNotificationCenter defaultCenter] removeObserver: self name: @"TAMSResultDidChange" object: nil ];
    
    ;
}

- (void)windowWillClose:(NSNotification *)aNotification
{
#if CLOSEBUG
#else
    [self willClose];
#endif
}

-(void)handleAnEOF: (MWFile *) mf
{ 
    NSString *ss;
    [self clearComments];
    [self setCurrMWFile: mf];
    if([self global: @"sectionsearch"] && ([gWorkBench isInitFile: mf] == YES))
    {
        [[tce ctRunVault] removeAllObjects];
    }
    
    if([self global: @"eofIsEndFlag"] && ([gWorkBench isInitFile: mf] == NO))
        [self handleEnd: NO flush: NO];
    if(mf)
        ss = [NSString stringWithFormat: @"%@ has unterminated coded passages", [mf name]];
    else ss = [NSString stringWithString: @"There are unterminated coded passages"];
    
    [tce ctDelAllZones];
    
    if([self global: @"zapuniversal"]) //([gPrefBoss zapUnivValue])
    {
        int i, n;
        NSArray *who;
        who = [univVault allKeys];
        n = [who count];
        for(i = 0; i < n; i++)
        {
            
            [univVault setObject: @"" forKey: [who objectAtIndex: i]];
        }
    }
    
    FORALL([tce ctRunVault])
    {
        if([temp openRun])
        {
            [tce ctCloseAllOpenRuns];
            if([self global: @"sectionsearch"] == YES && [gWorkBench isInitFile: mf] == YES)
                ; //don't do anything
            else
                NSWARNING(ss);//@"There are unterminated coded passages");
                break;
	}
    }
    ENDFORALL;
    SETGLOBAL(@"lastRepeat", 0);
    /*
     NSWARNING(ss);
     //NSWARNING(@"You have unterminated coded passages");
     
     [self handleEnd: NO flush: YES]; */
    
}


-(void)handleEachEOF: (NSNotification *)anote
{ 
    NSString *ss;
    
    if([self global: @"sectionsearch"] && ([gWorkBench isInitFile: [anote object]] == YES))
    {
	[[tce ctRunVault] removeAllObjects];
    }
    
    if([self global: @"eofIsEndFlag"] && ([gWorkBench isInitFile: [anote object]] == NO))
	[self handleEnd: NO flush: NO];
    [self clearComments];
    
    if([anote object])
        ss = [NSString stringWithFormat: @"%@ has unterminated coded passages", [[anote object] name]];
    else ss = [NSString stringWithString: @"There are unterminated coded passages"];
    
    [tce ctDelAllZones];
    if([self global: @"skipinnertopofdoc"] == 0)
        innerRFlag = 1;
    else
        innerRFlag = 0;
    [self clearComments];
    if([self global: @"zapuniversal"]) //([gPrefBoss zapUnivValue])
    {
        int i, n;
        NSArray *who;
        who = [univVault allKeys];
        n = [who count];
        for(i = 0; i < n; i++)
        {
            
            [univVault setObject: @"" forKey: [who objectAtIndex: i]];
        }
    }
    
    FORALL([tce ctRunVault])
    {
	if([temp openRun])
	{
	    [tce ctCloseAllOpenRuns];
            if([self global: @"sectionsearch"] == YES && [gWorkBench isInitFile: [anote object]] == YES)
                ; //don't do anything
            else
                NSWARNING(ss);//@"There are unterminated coded passages");
                break;
	}
    }
    ENDFORALL;
    /*
     NSWARNING(ss);
     //NSWARNING(@"You have unterminated coded passages");
     
     [self handleEnd: NO flush: YES]; */
    
}
-(id) subsetFromArray: (NSArray *) who
{
    NSMutableArray *aa = [[NSMutableArray alloc] init];
    FORALL(who)
    {
        id testValue;
        testValue = [backData objectAtIndex: [temp intValue]];
        [aa addObject: [backData objectAtIndex: [temp intValue]]];
    }ENDFORALL;
    return aa;
}

- (BOOL)loadDataRepresentation:(NSData *)data ofType:(NSString *)type {
    // Implement to load a persistent data representation of your document OR remove this and implement the file-wrapper or file path based load methods.
    NSArray *rootArray;
    if([type isEqualToString: @"TAMS Result"] || [type isEqualToString: @"XML TAMS Result"])
    {
        //rootArray = [NSUnarchiver unarchiveObjectWithData: data];
        
        mySavedData = data;
        [mySavedData retain];
        [savedDataType setString: type];
    }
    return YES;
}

-(void) loadSavedData
{
    {
        NSArray *rootArray;
        NSMutableArray *dataArray;
        NSMutableDictionary *theDict;
        NSArray *theSetNames, *fl;
        int selRow;
        NSDictionary *theSavedNS;
        //        BOOL apm;
        //        NSMutableString *wbPath = [[NSMutableString alloc] init];
        selRow = 0;
#ifdef USESXML
        if([savedDataType isEqualToString: @"XML TAMS Result"]){
            [self loadKeyedData];
            return;
        }
#endif
        if(!gWorkBench)
        {
            NSWARNING(@"Cannot open file directly. Must open through a workbench/project");
            return;
        }
        
        
        rootArray = [NSUnarchiver unarchiveObjectWithData: mySavedData];
        if([[rootArray objectAtIndex: 0] isEqualToString: @"2.0a"] ||[
            [rootArray objectAtIndex: 0] intValue] >= 3)
        {
            
            
            //2. save the globals
            [myGlobals setGlobals: [rootArray objectAtIndex: 1]];
            //need to load the flag values
            //3. save the file list; have to convert to absolute paths
            fl = [rootArray objectAtIndex: 2];
            FORALL(fl)
            {
                if(![gWorkBench fileForName: temp])
                {
                    NSString *msg1 = [NSString  stringWithFormat:@"Cannot continue. Missing source file \"%@\" for this result.", temp];
                    NSWARNING(msg1);
                    return;
                    
                }
                else
                    [fileList addObject: [gWorkBench fileForName: temp]];
            }
            ENDFORALL;
            
            //4. save the data
            dataArray = [rootArray objectAtIndex: 3];
            FORALL(dataArray)
            {
                theDict = [[NSMutableDictionary alloc] initWithDictionary: temp];
                [theDict setObject: [gWorkBench fileForName: 
                    [temp objectForKey: @"_doc"]]
                            forKey:  @"_doc"];
                [backData addObject: theDict];
            }
            ENDFORALL;
            
            //5. save the visible data
            [myData addObjectsFromArray: [self subsetFromArray: [rootArray objectAtIndex: 4]]];	
            
            //6. save the named sets
            //get the dictionary
            theSavedNS = [rootArray objectAtIndex: 5];
            //get the keys
            theSetNames = [theSavedNS allKeys];
            //work through them
            FORALL(theSetNames)
            {
                [namedSelDict setObject: [self subsetFromArray: 
                    [theSavedNS objectForKey: temp]] forKey: temp];
            }
            ENDFORALL;
            //if([theSetNames count]) [self renewNamedSelMenu];
            
            //7. get the limit string
            if(!limitString)
                limitString = [[NSMutableString alloc] init];
            [limitString setString: [rootArray objectAtIndex: 6]];
            //8. get colList
            [colList addObjectsFromArray: [rootArray objectAtIndex: 7]];
            //[myWindow setTitle: [[[self getMWFile] path] lastPathComponent]];
            //9.
            [limitField setStringValue: [rootArray objectAtIndex: 8]];
            //10. get the Coder's list
            if([[rootArray objectAtIndex: 0] intValue] >= 3)
                [codersString setString: [rootArray objectAtIndex: 9]];
            //11. get the automatic sets
            if([[rootArray objectAtIndex: 0] intValue] >= 4)
            {
                [autoSets addEntriesFromDictionary: [rootArray objectAtIndex: 10]];
            }
            [self rebuildAutoSetMenu];
            //12. get the selected row
            if([[rootArray objectAtIndex: 0] intValue] >= 5)
            {
                selRow = [[rootArray objectAtIndex: 11] intValue];
                [self markBackArray: [rootArray objectAtIndex: 12]];
            }
            //13. summary reports
            if([[rootArray objectAtIndex: 0] intValue] >= 6)
            {
                [summReports addEntriesFromDictionary: [rootArray objectAtIndex: 13]];
                [self rebuildSummReportMenu];
            }
            if([[rootArray objectAtIndex: 0] intValue] >= 7)
            {
                [dfString setString: [rootArray objectAtIndex: 14]];
                dfIndex = [[rootArray objectAtIndex: 15] intValue];
            }
            if([[rootArray objectAtIndex: 0] intValue] >= 8)
            {
                [autoHistory addObjectsFromArray: [rootArray objectAtIndex: 16]];
            }
            if([[rootArray objectAtIndex: 0] intValue] >= 9)
            {
                [autoHistoryStart setString: [rootArray objectAtIndex: 17]];
            }
            if([[rootArray objectAtIndex: 0] intValue] >= 10)
            {
                [mediaDict addEntriesFromDictionary: [rootArray objectAtIndex: 18]];
            }
            
            [[NSNotificationCenter defaultCenter] addObserver: self 
                                                     selector: @selector(handleResultsDidChange:)
                                                         name: @"TAMSResultDidChange"
                                                       object: gWorkBench];
            
            FORALL(fileList)
            {
                [[NSNotificationCenter defaultCenter] addObserver: self 
                                                         selector: @selector(handleDirtySourceFlag:)
                                                             name: @"TAMSDocDidChange"
                                                           object: temp];
                
                [[NSNotificationCenter defaultCenter] addObserver: self 
                                                         selector: @selector(addCodeHandler:)
                                                             name: @"TAMSDocAddedCode"
                                                           object: temp];
                
                
                
            }ENDFORALL;
            
            [self setupTables];
            [dirtySourceFlag setState: NSOnState];
            UPDATERECCOUNT;
            [self updateChangeCount: NSChangeCleared];
            [self rebuildSummReportMenu];
            
            [theResults reloadData];
            if(selRow >= 0 && [theResults numberOfRows] > 0)
            {
                [theResults selectRow: selRow byExtendingSelection: NO];
                [theResults scrollRowToVisible: selRow];
            }
            
            
        }
    }
}

-(BOOL) windowShouldClose: (NSNotification *)aNotification
{
#if CLOSEBUG
    [self willClose];
#endif
    return YES;
}

- (void)windowControllerDidLoadNib:(NSWindowController *)windowController
{
    [super windowControllerDidLoadNib: windowController];
    [self zeroSetStack];
    [theResults setDelegate: self];
    [theResults setDoubleAction: @selector(fetchRow:)];
    [self rebuildSummReportMenu];
	//[self clearTable];
	
    ;// [self executeTAMS];
}
-(void) executeTAMS
{
    //get the data
    if(!tce ) return;
    [self rebuildAutoSetMenu]; //only secure place to put it
    [self rebuildSummReportMenu];
    if([tce gCurrentDataSource] != nil)
    {
	dataSource = [tce gCurrentDataSource];
	//[[myWindow windowController] setShouldCloseDocument: YES];
	//[self resetStorage]; //need to zero out the arrays, send inits to all the processes
	//ctInitRV();
	//[tce initLimit];
	[self clearTable];
	[self setGlobal: @"firstwriteflag" to: 1];
	[self setGlobal: @"rawflag" to: [dataSource rawF]];
	[self setGlobal: @"emptyflag" to: [dataSource emptyF]];
	[self setGlobal: @"exactflag" to: [dataSource exactF]];
	[self setGlobal: @"simpleflag" to: [dataSource simpleF]];
	[self setGlobal: @"regexcharflag" to: [dataSource regexCharF]];
	[self setGlobal: @"nonregexcharflag" to: [dataSource nonRegexCharF]];
        [self setGlobal: @"sectionsearch" to: [dataSource sectionF]];
	[self setGlobal: @"raw1stflag" to: [dataSource rawF]];
	[self setGlobal: @"empty1stflag" to: [dataSource emptyF]];
	[self setGlobal: @"exact1stflag" to: [dataSource exactF]];
	[self setGlobal: @"simple1stflag" to: [dataSource simpleF]];
	[self setGlobal: @"section1stflag" to: [dataSource sectionF]];
	[self setGlobal: @"regexchar1stflag" to: [dataSource regexCharF]];
	[self setGlobal: @"nonregexchar1stflag" to: [dataSource nonRegexCharF]];
        
        
	if([gPrefBoss countSectionsValue]) 
	    SETGLOBAL(@"emptysectionflag", 1);
	else
	    SETGLOBAL(@"emptysectionflag",0);
	//[myWindow setReleasedWhenClosed: YES];
	[fileList removeAllObjects];
	[colList removeAllObjects];
        [codersString setString: [dataSource codersList]];
	[self buildCoderList];
	
        //get the search
	if(limitString != nil) [limitString release];
	limitString = [[NSMutableString alloc] init];
	[limitString setString: [dataSource theLimitString]];
	[fileList addObjectsFromArray: [tce hotFileList]];
        [[NSNotificationCenter defaultCenter] addObserver: self 
                                                 selector: @selector(handleResultsDidChange:)
                                                     name: @"TAMSResultDidChange"
                                                   object: gWorkBench];
	FORALL(fileList)
	{
            [[NSNotificationCenter defaultCenter] addObserver: self 
                                                     selector: @selector(handleDirtySourceFlag:)
                                                         name: @"TAMSDocDidChange"
                                                       object: temp];
            
            [[NSNotificationCenter defaultCenter] addObserver: self 
                                                     selector: @selector(addCodeHandler:)
                                                         name: @"TAMSDocAddedCode"
                                                       object: temp];
            
            
            
	}ENDFORALL;
	
	[[NSNotificationCenter defaultCenter] addObserver: self 
                                                 selector: @selector(handleEachEOF:)
                                                     name: @"TAMSFileHasEnded"
                                                   object: nil];
        [self setOriginalStateString];
        
	if([limitString length])
	{
            /*
             if([self global: @"sectionsearch"] == 1)
             {
                 [limitField setStringValue: [NSString stringWithFormat: @"Section: %@", limitString]];
             }
             else
             [limitField setStringValue: limitString];
             */
	    [self setGlobal: @"limitflag" to: 1];
	    [tce handlelimit: limitString];
	    [self doTamsSearch: limitString];
	    [tce ctCloseAllOpenRuns];
	    if([[tce ctRunVault] count])
		[self handleEnd: NO flush: NO];
	}
	else
	{
            /*            if([self global: @"sectionsearch"] == 1)
        {
                
                [limitField setStringValue: [NSString stringWithFormat: @"Section: unlimited", limitString]];
        }
            else
            [limitField setStringValue: @"Unlimited"];
            */
	    [self setGlobal: @"limitflag" to: 0];
	    [self doTamsSearch: nil];
	    [tce ctCloseAllOpenRuns];
	    if([[tce ctRunVault] count])
		[self handleEnd: NO flush: NO];
	}
	[tce setGCurrentTAMS: nil];
        //do the search
	//do the tables
	//reload
	[self setupTables];
	[myWindow makeKeyAndOrderFront: self];
	[backData removeAllObjects];
	[backData addObjectsFromArray: myData];
        
        [self updateChangeCount: NSChangeDone];
        
	UPDATERECCOUNT;
	[theResults reloadData];
	[[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name: @"TAMSFileHasEnded" object: nil];
    }
    
    [tce release];
    
}
#ifdef SECTIONSEARCH
-(NSMutableDictionary *) token2Dictionary: (ctQChar *) qq
{
    NSALLOC(NSMutableDictionary, myD);
    
    [myD setObject: [[[qq buff] copy] autorelease] forKey: @"code"];
    [myD setObject: [[[qq coder] copy] autorelease] forKey: @"coder"];
    [myD setObject: @"Open" forKey: @"state"];
    return [myD autorelease];
    
}

-(void) removeCloseTags: (NSMutableArray *) aa
{
    int i, n;
    NSMutableDictionary *tt;
    
    n = [aa count];
    for(i = n - 1; i >= 0; i--)
    {
        tt = [aa objectAtIndex: i];
        if([[tt objectForKey: @"state"] isEqualToString: @"Closed"])
            [aa removeObject: tt];
    }
}

-(void) addTokenForChar: (ctQChar *) qq forSection: (coderec *) ms
{
    NSMutableArray *aa = [ms sectionCodes];
    FORALL(aa)
    {
        if([[temp objectForKey: @"code"] isEqualToString: [qq buff]] && 
           [[temp objectForKey: @"coder"] isEqualToString: [qq coder]])
        {
            if([[temp objectForKey: @"state"] isEqualTo: @"Closed"])
            {
                [temp setObject: @"Open" forKey: @"state"];
                return;
            }
        }
        
    }
    ENDFORALL;
    [aa addObject: [self token2Dictionary: qq]];
}

-(void) closeTokenForChar: (ctQChar *) qq forSection: (coderec *) ms
{
    NSMutableArray *aa = [ms sectionCodes];
    FORALL(aa)
    {
        if([[temp objectForKey: @"code"] isEqualToString: [qq buff]] && 
           [[temp objectForKey: @"coder"] isEqualToString: [qq coder]])
        {
            [temp setObject: @"Close" forKey: @"Closed"];
        }
    }
    ENDFORALL;
}
#endif

-(void) setCurrMWFile: (MWFile *) who
{
    currMWFile = who;
}
-(MWFile *) currMWFile
{
    return currMWFile;
}

- (void) doTamsSearch: (NSString *) aLimString
{
    int nn;
    ctQChar *qq;
#ifdef REGEXSEARCH
    AGRegex *regex;
    AGRegexMatch *match;
    NSArray *fl;
    int rsi, rsj, rsk, rsnn3, rsnn, rsnn2;
    int charZoom;
    int chtype;
    unsigned opt;
    long rsln;
    NSRange rsr, rsr2, rsr3;
#endif
#ifdef SECTIONSEARCH
    coderec *mySect;
    
    mySect = nil;
#endif
#ifdef REGEXSEARCH
#endif
    qq = nil;
    qq = [[ctQChar alloc] init];
    nn = [self global: @"simpleflag"];
    //setup();
    [tce setGCurrentTAMS: self];
#ifdef REGEXSEARCH
    charZoom = [gPrefBoss zoomFactorValue];
    if([self global: @"nonregexcharflag"])
    {
        fl = [tce hotFileList];
        [colList addObject: @"_code"];
        [colList addObject: @"_data"];
        [colList addObject: @"_begin_loc"];
        [colList addObject: @"_doc"];
        opt = 0;
        if([self global: @"exactflag"] == 0)
            opt = NSCaseInsensitiveSearch;
        rsnn = [fl count];
        for(rsi = 0 ; rsi < rsnn; rsi++)
        {
            MWFile *rsFile;
            NSString *rsString;
            fl = [tce hotFileList];
            rsFile = [fl objectAtIndex: rsi];
            rsString = [rsFile string];
            rsln = [rsString length];
            rsnn2 = 1;
            rsr3 = NSMakeRange(0, rsln - 1);
            while(rsnn2)
            {
                rsr = [rsString rangeOfString: limitString
                                      options: opt
                                        range: rsr3];
                if(rsr.location != NSNotFound)
                {
                    NSALLOC(NSMutableDictionary,theRec);
                    rsr2 = rsr;
                    if(charZoom > rsr2.location)
                    {
                        rsr2.length += charZoom;
                        rsr2.location = 0;
                    }
                    else
                    {
                        rsr2.length += charZoom;
                        rsr2.location -= charZoom;
                    }
                    rsr2.length += charZoom;
                    if(rsr2.location + rsr2.length >= rsln)
                        rsr2.length = rsln - rsr2.location;
                    [theRec setObject: rsFile forKey: @"_doc"];
                    [theRec setObject: [[limitString copy] autorelease] forKey: @"_code"];
                    [theRec setObject: [rsString substringWithRange: rsr2]
                               forKey: @"_data"];
                    /*[theRec setObject: [[[match groupAtIndex: rsk] copy] autorelease]
forKey: @"_data"];*/
                    [theRec setObject: [[NSNumber numberWithLong: 
                        rsr.location] stringValue]
                               forKey: @"_begin_loc"];
                    [theRec setObject: [[NSNumber numberWithLong: 
                        rsr.location + 
                        rsr.length] stringValue]
                               forKey: @"_end_loc"];
                    rsr3.location = rsr.location + rsr.length;
                    rsr3.length = rsln - rsr3.location;
                    [myData addObject: theRec];
                }
                else
                    rsnn2 = 0;
            }
            
        }
        if(!qq) [qq release];
        return;
    }
    
#define NEWREGEXSEARCHCODE
    if([self global: @"regexcharflag"])
    {   
        NSRange tr;
        
        opt = 0;
        if([self global: @"exactflag"] == 0) opt = AGRegexCaseInsensitive;
        if([self global: @"emptyflag"] == 1) opt |= AGRegexMultiline;
        //regex = [[AGRegex alloc] initWithPattern: limitString options: opt];
        
        fl = [tce hotFileList];
        [colList addObject: @"_code"];
        [colList addObject: @"_data"];
        [colList addObject: @"_begin_loc"];
        [colList addObject: @"_doc"];
        rsnn = [fl count];
        for(rsi = 0 ; rsi < rsnn; rsi++)
        {
            MWFile *rsFile;
            NSString *rsString;
            NSMutableDictionary *theRec;
            NSAutoreleasePool *myPool;
            int sbstr;
            if([codersString isEqualToString: @""] == YES)
                sbstr = 0;
            else
                sbstr = [codersString intValue];
            //NSLog(@"str: %@; int:%d\n", codersString, sbstr);
            fl = [tce hotFileList];
            rsFile = [fl objectAtIndex: rsi];
            rsString = [rsFile string];
            rsln = [rsString length];
            tr = NSMakeRange(0,0);
            for(;;)
            {
                //fl = [regex findAllInString: rsString];
                theRec = [[NSMutableDictionary alloc] init];
                myPool = [[NSAutoreleasePool alloc] init];
                rsr = rsr2 = [rsString findString: limitString selectedRange: tr options:opt wrap:NO regex: YES multiline: YES substring: sbstr];
                [myPool release];
                if(rsr.location == NSNotFound) break;
                
                {
                    if(charZoom > rsr2.location)
                    {
                        rsr2.length += charZoom;
                        rsr2.location = 0;
                    }
                    else
                    {
                        rsr2.length += charZoom;
                        rsr2.location -= charZoom;
                    }
                    rsr2.length += charZoom;
                    if(rsr2.location + rsr2.length >= rsln)
                        rsr2.length = rsln - rsr2.location;
                    [theRec setObject: [rsString substringWithRange: rsr2]                                 forKey: @"_data"];
                    
                    [theRec setObject: rsFile forKey: @"_doc"];
                    [theRec setObject: [[limitString copy] autorelease] forKey: @"_code"];
                    /*[theRec setObject: [[[match groupAtIndex: rsk] copy] autorelease]
forKey: @"_data"];*/
                    [theRec setObject: [[NSNumber numberWithLong: 
                        rsr.location] stringValue]
                               forKey: @"_begin_loc"];
                    [theRec setObject: [[NSNumber numberWithLong: 
                        rsr.location + 
                        rsr.length] stringValue]
                               forKey: @"_end_loc"];
                    [myData addObject: [theRec autorelease]];
                }
                tr.location = rsr.location + rsr.length;
                tr.length = 0;
                
            }//for(;;)
            
        }
        //[regex release];
        return;
    }
    
#endif
    
#ifdef SCANCODE
    while((chtype = [tce scanNext: qq]) != ENDOFALLFILES)
#else
        while([tce readnext: qq] != EOF)
#endif
        {     
            if(chtype != ENDOFFILE) 
            {
                [self setCurrMWFile: [qq source]];
            }
#ifdef SECTIONSEARCH
            if([self global: @"sectionsearch"])
            {
                //we need to add the open dictionary
                if([tce hasSectionRun] == NO) 
                {
                    [tce ctOpenSectionRun];
                }
#ifdef SCANCODE
                switch(chtype)
#else
                    switch([qq tokentype])
#endif
                    {
                        case TOKEN:
                            //handle inner repeat
                            if([self isRepeat: [qq buff]] && [self isInnerRepeat: [qq buff]] 
                               && innerRFlag)
                            {
                                [self handleEnd: YES flush: NO];
                            }
                            else
                                
                            {
                                innerRFlag = 1;
                            }
                            
                            //handle last repeat
                            if([self isRepeat: [qq buff]] && [self global: @"lastRepeat"])
                            {
                                [self handleEnd: YES flush: NO];
                                
                                SETGLOBAL(@"lastRepeat", 0);//[self setGlobal: @"lastRepeat" 0];
                            }
                            if([self isLastRepeat: [qq buff]] == YES) {SETGLOBAL(@"lastRepeat", 1);}
                            if([tce hasSectionRun] == NO) 
                            {
                                [tce ctOpenSectionRun];
                            }
                            if([self isRepeat: [qq buff]] == YES)
                                [tce ctOpenRun: qq];
                            [tce ctAddSectionTag: [self token2Dictionary:qq]];
                            
                            [tce ctAddOpenChar: qq]; break;
                            break;
                        case ENDTOKEN:
                            if([tce hasSectionRun] == NO) 
                            {
                                [tce ctOpenSectionRun];
                                
                            }
                            if([extraComment length])[qq addExtra: [self getComment]];
                            [tce ctAddOpenChar: qq]; 
                            [tce ctCloseSectionTagForCode: [qq buff] Coder: [qq coder]];
                            [tce ctCloseRun: qq];
                            break;
                        case CHAR:
                            if([tce hasSectionRun] == NO) 
                            {
                                [tce ctOpenSectionRun];
                                
                            }
                            [tce ctAddOpenChar: qq]; break;
                            
                        case META:
                            [self handlemeta: qq]; break;
                            if([tce hasSectionRun] == NO) 
                            {
                                mySect = [tce ctOpenSectionRun];
                                
                            }
                                break;
                            
                        case ENDOFFILE:
                            [self handleAnEOF: [qq source]];
                            break;
                    };
                
                continue;
            }
            
            
            
#endif		
            // regular simple and non-simple searches
            if(/*![self global: @"limitflag"] || */[self global: @"simpleflag"])
            {
#ifdef SCANCODE
                switch(chtype)
#else
		    switch([qq tokentype])
#endif
		    {
			case TOKEN:
                            if([self isRepeat: [qq buff]] && [self isInnerRepeat: [qq buff]]
                               && innerRFlag)
                                [self handleEnd: YES flush: NO];
                            else 
                            {
                                innerRFlag = 1;
                            }
                                if([self isRepeat: [qq buff]] && [self global: @"lastRepeat"])
                                {
                                    [self handleEnd: YES flush: NO];
                                    
                                    SETGLOBAL(@"lastRepeat", 0);//[self setGlobal: @"lastRepeat" 0];
                                }
                                
                                if([self isLastRepeat: [qq buff]] == YES)
                                {
                                    SETGLOBAL(@"lastRepeat", 1);
                                }
                                
                                if([self global: @"simpleflag"] && aLimString)
                                {
                                    //aCode = [[ctLimitCrit alloc] initWithString: aLimString];
                                    //if(isStringTrue(aCode, [qq buff]) || [self isRepeat: [qq buff]])
                                    if([tce isTagTrue: qq] || [self isRepeat: [qq buff]])
                                    {
                                        [tce ctOpenRun: qq];
                                    }
                                    
                                }
                                else 
                                    [tce ctOpenRun: qq]; 
			    [tce ctAddZone: qq]; 
			    if([self global: @"rawflag"]) [tce ctAddOpenChar: qq];
                                break;
                            
			case ENDTOKEN:
                            if([extraComment length])[qq addExtra: [self getComment]];
			    [tce ctCloseRun: qq]; 
			    [tce ctDelZone: qq ]; 
			    if([self global: @"rawflag"]) [tce ctAddOpenChar: qq];
                                if([self global: @"basicflag"]) 
                                    [self handleEnd: YES flush: NO];
                                    break;
			    
			case CHAR:
			    [tce ctAddOpenChar: qq]; break;
			    
			case META:
			    [self handlemeta: qq]; break;
                            
                        case ENDOFFILE:
                            [self handleAnEOF: [qq source]];
                            break;
		    };
            }
	    //here is the limit logic
            else if(/*[self global: @"limitflag"] && */ ![self global: @"simpleflag"])
            {
                int zoneFlag;
                if(chtype == ENDTOKEN) if([extraComment length])[qq addExtra: [self getComment]];                    
                if(chtype == ENDOFFILE) 
                {
                    [self handleAnEOF: [qq source]]; 
                    continue;
                }
                if(chtype == TOKEN)
                {
                    if([self isRepeat: [qq buff]] && [self isInnerRepeat: [qq buff]]
                       && innerRFlag)
                        [self handleEnd: YES flush: NO];
                    else
                        innerRFlag = 1;
                    if([self isRepeat: [qq buff]] && [self global: @"lastRepeat"])
                    {
                        [self handleEnd: YES flush: NO];
                        
                        SETGLOBAL(@"lastRepeat", 0);//[self setGlobal: @"lastRepeat" 0];
                    }
                    
                    if([self isLastRepeat: [qq buff]] == YES)
                    {
                        SETGLOBAL(@"lastRepeat", 1);
                    }
                    
                }
                zoneFlag = [tce handleLimChar: qq];
                if(zoneFlag == STARTLIM) 
                {
                    //if([self isRepeat: [qq buff]]) continue;
                    [tce ctOpenLimRun: qq];
                }
                else if (zoneFlag == ENDLIM) 
                {
                    [tce ctCloseLimRun: qq];
                    if([self global:@"basicflag"])
                        [self handleEnd: YES flush: NO];
                }
                else if (zoneFlag == INLIM) [tce ctAddLimChar:qq];
            }
        }
            /*
             if([self global: @"eofIsEndFlag"]) //if([gPrefBoss EOFIsEndValue]) 
             [self handleEnd: NO flush: NO];
             */
	    [tce checkZones];
}

- (void)savePanelDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void  *)contextInfo
{
    if(returnCode == NSCancelButton) return;
    if(returnCode == NSOKButton)
    {
	[self writeToFile:[[NSSavePanel savePanel] filename] 
                   ofType: @"DocumentType"];
    }
}

-(NSMutableArray *) convertString: (NSString *)  theString onChar: (unichar) breakChar
{
    int i, len;
    unichar c;
    NSMutableString *ss = [[NSMutableString alloc] init];
    NSMutableArray *ans = [[NSMutableArray alloc] init];
    len = [theString length];
    [ss setString: @""];
    
    for(i = 0; i < len; i++)
    {
	c = [theString characterAtIndex: i];
	if(c == ' ')
	{
	    ;
	}
	else if (c == breakChar)
	{
	    if([ss length] > 0)
	    {
		[ans addObject: [ss copy]];
		[ss setString: @""];
	    }
	}
	else
	{
	    [ss ADDCHAR(c)];
	}
    }
    if([ss length])
    {
	[ans addObject: [ss copy]];
    }
    return ans;
}

-(void) addToList: (NSMutableArray *) aList usingString: (NSString *) aString
{
    NSMutableArray *ans;
    int i,n;
    if(aString == nil) return;
    if([aString isEqualToString: @""]) return;
    ans = [self convertString: aString onChar: ','];
    //ans = convertStringToArray(aString, ',');
    //[ans retain];
    n = [ans count];
    for(i = 0; i < n; i++)
    {
        if(arrayContainsString(aList , [ans objectAtIndex: i]) == NO)
            [aList addObject: [ans objectAtIndex: i]];
    }
    //[aList addObjectsFromArray: ans];
}

-(BOOL)isHotCoder: (NSMutableDictionary *) rec
{
    if([codersList count] == 0) return YES;
    FORALL(codersList)
    {
	if([temp isEqualToString: @"*"] == YES)
	{
	    if([[rec objectForKey: @"_coder"] isEqualToString: @""] == YES) return YES;
	}
	else
	    if([temp isEqualToString: [rec objectForKey: @"_coder"]] == YES) return YES;
    }
    ENDFORALL;
    return NO;
}

-(void) doContWithDict: (NSMutableDictionary *) theVault
{
    int iii, nnn, ii, nn;
    NSMutableDictionary *contList, *contValue;
    NSArray *myKeyArray, *myContArray;
    
    myKeyArray = [theVault allKeys];
    nnn = [myKeyArray count];
    for(iii = 0; iii < nnn; iii++)
    {
        
        //work through
        //look up the repeat variabl
        if((contList = [repCont objectForKey: [myKeyArray objectAtIndex: iii]]) != nil)
        {
            //get the contingency
            contValue = [contList objectForKey: [theVault objectForKey: [myKeyArray objectAtIndex: iii]]];
            if(contValue != nil)
            {
                myContArray = [contValue allKeys];
                
                //set for each
                nn = [myContArray count];
                
                for(ii = 0; ii < nn; ii++)
                {
                    //if it's a repeat
                    if([self isRepeat: [myContArray objectAtIndex: ii]] 
                       || [self isUniversal: [myContArray objectAtIndex: ii]] )
                    {
                        [theVault setObject: 
                            [contValue objectForKey: 
                                [myContArray objectAtIndex: ii]]
                                     forKey: [myContArray objectAtIndex: ii]];
                    }
                    
                }
            }
            else //zap the contingent variables
            {
                
            }
            
        }
    }
    
}

-(void) assignRepeat: (NSString *) rname withValue: (NSString *) rvalue
{
    NSMutableString *ss, *tt;
    if([fieldMap count] > 0)
    {
        ss = [fieldMap objectForKey: rname];
        if(ss == nil)
            [repVault setObject: rvalue forKey: rname];
        else
            [repVault setObject: rvalue forKey: ss];
    }
    else
        [repVault setObject: rvalue forKey: rname];
}
int sectionTotCnt = 0;
-(void) handleEnd: (BOOL) section flush: (BOOL) flushFlag
{
    NSEnumerator *myenums ;
    coderec  *mykey;
    NSString *ss, *st;
    NSMutableArray *doneList;
    int n;
    int realcnt;
    int fflag;
    fflag = 1; //first time through the emptys
    realcnt = 0;
    
    n= 0;
    if([self global: @"emptyflag"])
	n = 1;
    if(section == YES && MYGLOBAL(@"emptysectionflag") == NO && [self global: @"sectionsearch"])
        return; //we're not done
    if([self global: @"sectionsearch"])
    {
        /* being here means that the section has ended, since this is called for !end*/
        
        [tce ctCloseSectionRun];
        
        /* filter results */
        [tce filterSectionRuns];
    }
    //|| (section == YES && [self global: @"emptysectionflag"])
    //first handle all of the repeats
    //need to make this conditional on emptyflag
    /*
     if([self global: @"emptyflag"])
     [repVault removeAllObjects];
     */
    //set the repeats
    FORALL([tce ctRunVault])
    {
        st = [temp theName]; //for debugging
                             //if([self isRepeat: [temp theName]])
        if([temp runType] == REPEATRUN)
	{
	    if(ss = [temp record])
            {
                [self assignRepeat: [temp theName] withValue: [ss copy]];
		//[repVault setObject: [ss copy] forKey: ];
                
            }
	    else
                [self assignRepeat: [temp theName] withValue: @""];
            //[repVault setObject: @"" forKey: [temp theName]];
            
	}
    }
    ENDFORALL;
    
    [self doContWithDict: repVault];
    
    if([self global: @"firstwriteflag"])
    {
	//[colList addObject: @"#"];
	FORALL(univList)
    {
	    [colList addObject:  temp];
    }
	ENDFORALL;
	FORALL(repList)
	{
	    [colList addObject:  temp];
	}
	ENDFORALL;
	[colList addObject: @"_code"];
	[colList addObject: @"_data"];
	[colList addObject: @"_comment"];
	[colList addObject: @"_coder"];
        [colList addObject: @"_doc"];
        if([tce hasLineNumbers] && [gPrefBoss TAScanForLN])
            [colList addObject: @"_line_number"];
	[colList addObject: @"_begin_loc"];
 	[self setGlobal: @"firstwriteflag" to: 0];
	sectionTotCnt = 0;
    }
    
    
    myenums = [[tce ctRunVault] objectEnumerator];
    
    while(mykey = [myenums nextObject])
    {
	NSMutableDictionary *myrec;
	
	//if([mykey openRun] == YES) continue;
	if([self isRepeat: [mykey theName]] == YES) 
	    continue;
	//if it isn't in our approved coder list nix it
	//if([self isValidCoder: [mykey theCoder]] == NO)
	//    continue;
	//we're not a repeat so this one counts
	//make a dictionary of 
	myrec = [[NSMutableDictionary alloc] init];
	// the univerals
        FORALL(univList)
        {
            [myrec setObject: [univVault objectForKey: temp] forKey: temp];
        }
        ENDFORALL;
	//the repeats
        FORALL(repList)
        {
            NSString *tt;
            
            if(tt = [repVault objectForKey: temp])
                [myrec setObject: tt forKey: temp];
            else
                [myrec setObject: @"" forKey: temp];
            
        }
        ENDFORALL;
	//This is where we need to add handling for cross code stuff
        if([mykey hasInfo] == YES && [mykey openRun] ==NO)
        {
            if([mykey runType] != SECTIONRUN)
                [myrec setDictionary: [mykey affiliatedInfo]];
        }
	//ask if it has cross code
	//use that instead
	//if it is open and doesn't have one give it one
	//otherwise
	//the code
        [myrec setObject: [[mykey theName] copy] forKey: @"_code"];
	//the comment
        [myrec setObject: [[mykey comment] copy] forKey: @"_comment"];
	//the comment
        [myrec setObject: [[mykey theCoder] copy] forKey: @"_coder"];
	//the document
        [myrec setObject: [mykey doc] forKey: @"_doc"];
	//the index
	
        [myrec setObject: [[NSNumber numberWithLong: [mykey beginLoc]] stringValue]
                  forKey: @"_begin_loc"];
        
        [myrec setObject: [[NSNumber numberWithLong: [mykey endLoc]] stringValue]
                  forKey: @"_end_loc"];
        if([tce hasLineNumbers] && [gPrefBoss TAScanForLN])
	    [myrec setObject: [[NSNumber numberWithInt: [mykey lineStart]] stringValue]
                      forKey: @"_line_number"];
        
 	//the data
        [myrec setObject: [[mykey record] copy] forKey: @"_data"];
	if( [mykey hasInfo] == NO && [mykey openRun] == YES 
            && ![self global: @"backloadrepeatflag"])
	{
            if([mykey runType] != SECTIONRUN)
                [mykey setAffiliatedInfo: myrec];
	    if([self isHotCoder: myrec] == YES) realcnt++;
	}
	else if([mykey openRun] == NO)
	{
	    if([self isHotCoder: myrec] == YES)
	    {
		[myData addObject: myrec];
		realcnt++;
	    }
	}
    }
    sectionTotCnt += realcnt;
    // empty flag case
    if(((section == NO) || (section == YES && MYGLOBAL(@"emptysectionflag")))
       && n && sectionTotCnt == 0)
    {
        
	NSMutableDictionary *myrec;
	myrec = [[NSMutableDictionary alloc] init];
	// the univerals
        FORALL(univList)
        {
            [myrec setObject: [univVault objectForKey: temp] forKey: temp];
        }
        ENDFORALL;
	//the repeats
        FORALL(repList)
        {
            NSString *tt;
            if(tt = [repVault objectForKey: temp])
            {
                [myrec setObject: tt forKey: temp];
            }
            else
                [myrec setObject: @"" forKey: temp];
            
        }
        ENDFORALL;
	
	//the code
        [myrec setObject: @"*EMPTY*" forKey: @"_code"];
	//the data
        [myrec setObject: @"" forKey: @"_data"];
	//the comment
        [myrec setObject: @"" forKey: @"_comment"];
	//the document
        
	//the index
	
	if([[tce ctRunVault] count])
	{
	    mykey = [[tce ctRunVault] objectAtIndex: 0];
	    [myrec setObject: [[NSNumber numberWithLong: [mykey beginLoc]] 
                stringValue]
                      forKey: @"_begin_loc"];
            
	    [myrec setObject: [[NSNumber numberWithLong: [mykey endLoc]]
                stringValue]
                      forKey: @"_end_loc"];
            
	    [myrec setObject: [mykey doc] forKey: @"_doc"];
	}
	else
	{
            int tl;
            MWFile *www;
	    [myrec setObject:(  [NSNumber numberWithLong: tl = [tce getCharLocation]])
                      forKey: @"_begin_loc"];
            
	    [myrec setObject:([NSNumber numberWithLong: tl = [tce getCharLocation]])
                      forKey: @"_end_loc"];
            
	    /*if([tce hotSearchDocument] != nil)*/ 
            [myrec setObject: (www=[self currMWFile]) forKey: @"_doc"];
            // else [myrec setObject: [ stringWithString: @"NO DOC"] forKey: @"_doc"];
            tl = 0;
#ifdef rightCode
            int tl;
            MWFile *www;
	    [myrec setObject:( tl = [NSNumber numberWithLong: [tce getCharLocation]])
                      forKey: @"_begin_loc"];
            
	    [myrec setObject:( tl = [NSNumber numberWithLong: [tce getCharLocation]])
                      forKey: @"_end_loc"];
            
	    [myrec setObject: (www=[self currMWFile]) forKey: @"_doc"];
            tl = 0;
#endif
            
	}
        
        [myData addObject: myrec];
    }
    
    
    // empty the data source
    //[ctRunVault removeAllObjects];
    doneList = [[NSMutableArray alloc] init];
    FORALL([tce ctRunVault])
    {
	if([temp openRun] == NO) [doneList addObject: temp];
	else if([self global: @"rawflag"] && [self global: @"basicflag"] == 0)
	    [temp addString: @"{!end}"];
    }
    ENDFORALL;
    FORALL(doneList)
    {
	[[tce ctRunVault] removeObject: temp];
    }
    ENDFORALL;
    [doneList removeAllObjects];
    [doneList release];
    //if clean remove the repeats
    if(MYGLOBAL(@"cleanflag") && (section == NO))
    {
	[repVault removeAllObjects];
    }
    if(section == NO || MYGLOBAL(@"emptysectionflag") == 1) sectionTotCnt = 0;
}

/*
 This creates basically a tree structure using nsdictionaries. the first is a dictionary of repeat values and it returns a dictionary of possible values which returns a dictionary of contingent variables which returns a dictionary of their values
 */

#define IFVER2
-(void) handleIf: (NSString *) cList
{
    AGRegex *myExpr, *myExpr2;
    AGRegexMatch *myMatch;
    NSArray *myMatch2;
    NSMutableDictionary *theBase, *tb2;
    
    //first look for the regex
#ifdef IFVER1
    myExpr = [[AGRegex alloc] initWithPattern: @"([a-zA-Z0-9\\_]+)[\\t\\ \\n\\r]*=[\\t\\ \\n\\r]*\\\"(.*)\\\"[\\t\\ \\n\\r]*=>[\\t\\ \\n\\r]*([a-zA-Z0-9\\_]+)[\\t\\ \\n\\r]*=[\\t\\ \\n\\r]*\\\"(.*)\\\""];
#endif
#ifdef IFVER2
    myExpr = [[AGRegex alloc] initWithPattern: @"^[\\t\\ \\n\\r]*([a-zA-Z0-9\\_]+)[\\t\\ \\n\\r]*=[\\t\\ \\n\\r]*\\\"([^\\\"]*)\\\"[\\t\\ \\n\\r]*=>"];
    myExpr2 = [[AGRegex alloc] initWithPattern: @"=>[\\t\\ \\n\\r]*([a-zA-Z0-9\\_]+)[\\t\\ \\n\\r]*=[\\t\\ \\n\\r]*\\\"([^\\\"]*)\\\""];
#endif
    myMatch = [myExpr findInString: cList];
    if( [myMatch count])
    {
        theBase = [repCont objectForKey: [myMatch groupAtIndex: 1]];
#ifdef IFVER2
        myMatch2 = [myExpr2 findAllInString: cList];
#endif
        if(theBase != nil)
        {
            if((tb2 = [theBase objectForKey: [myMatch groupAtIndex: 2]]) != nil)
            {
#ifdef IFVER2
                int n2, i2;
                
                n2 = [myMatch2 count];
                for(i2 = 0; i2 < n2; i2++)
                {
                    [tb2 setObject: [[myMatch2 objectAtIndex: i2] groupAtIndex: 2] 
                            forKey: [[myMatch2 objectAtIndex: i2] groupAtIndex: 1]];
                }
#endif
#ifdef IFVER1
                [tb2 setObject: [myMatch groupAtIndex: 4] forKey: [myMatch groupAtIndex: 3]];
#endif
                
            }
            else
            {
                int n2, i2;
                //tb2 = [[NSMutableDictionary alloc] init];
                tb2 = [NSMutableDictionary dictionary];
#ifdef IFVER2
                
                n2 = [myMatch2 count];
                for(i2 = 0; i2 < n2; i2++)
                {
                    [tb2 setObject: [[myMatch2 objectAtIndex: i2] groupAtIndex: 2] 
                            forKey: [[myMatch2 objectAtIndex: i2] groupAtIndex: 1]];
                }
#endif
#ifdef IFVER1
                [tb2 setObject: [myMatch groupAtIndex: 4] forKey: [myMatch groupAtIndex: 3]];
#endif
                [theBase setObject: tb2 forKey: [myMatch groupAtIndex: 2]];
            }
        }
        else
        {
            theBase = [NSMutableDictionary dictionary];//[[NSMutableDictionary alloc] init];
            tb2 = [NSMutableDictionary dictionary];// [[NSMutableDictionary alloc] init];
#ifdef IFVER1
                [tb2 setObject: [myMatch groupAtIndex: 4] forKey: [myMatch groupAtIndex: 3]];
#endif
#ifdef IFVER2
                {
                    int n2, i2;
                    
                    n2 = [myMatch2 count];
                    for(i2 = 0; i2 < n2; i2++)
                    {
                        [tb2 setObject: [[myMatch2 objectAtIndex: i2] groupAtIndex: 2] 
                                forKey: [[myMatch2 objectAtIndex: i2] groupAtIndex: 1]];
                    }
                }
#endif
                [theBase setObject: tb2 forKey: [myMatch groupAtIndex: 2]];
                [repCont setObject: theBase forKey: [myMatch groupAtIndex: 1]];
        }
    }
    
    //apply changes to any universals
    [self doContWithDict: univVault];
    
}
#ifdef FIELDMAP
-(void) handleMap: (NSString *) namelist
{
    NSArray *aa, *bb;
    NSMutableString *ss, *tt;
    ss = [NSMutableString string];
    tt = [NSMutableString string];
    aa = [namelist componentsSeparatedByString:  @","];
    //break up the commas
    
    //for each
    FORALL(aa)
    {
        bb = [temp componentsSeparatedByString: @"->"];
        //separate out the parts for each
        //copy to a nsmutalbestring
        if([bb count] != 2) continue;
        [ss setString: [bb objectAtIndex: 0]];
        trimNSS(ss);
        
        [tt setString: [bb objectAtIndex: 1]];
        trimNSS(tt);
        
        [fieldMap setObject: tt forKey: ss];
    }ENDFORALL;
    
    //strip them
    //add to dictionary
}
#endif
-(void) handleSetRepeat: (NSString *) namelist
{
    NSMutableArray *myUList;
    int n;
    NSMutableString *s1, *s2, *s3;
    NSMutableArray *oneUVar;
    NSEnumerator *myen;
    
    s1 = [[NSMutableString alloc] init];
    s2 = [[NSMutableString alloc] init];
    
    myUList = convertStringToArray(namelist, ',');
    myen = [myUList objectEnumerator];
    n = [myUList count];
    [s1 setString: @""];
    [s2 setString: @""];
    while(s3 = [myen nextObject])
    {
	oneUVar = convertStringToArray(s3, '=');
	if([oneUVar count] == 2)
	{
	    [s1 setString: [oneUVar objectAtIndex: 0]];
	    trimNSS(s1);
	    [s2 setString: [oneUVar objectAtIndex: 1]];
	    trimNSS(s2);
	    
	    //add to both the list and the dictionary
	    trimNSS(s2);
	    trimCharNSS(s2,'\"');
            if(arrayContainsString(repList, s1) == NO)
                [repList addObject: [s1 copy]];
            if([self isRepeat: s1] && [self isInnerRepeat: s1])
                [self handleEnd: YES flush: NO];
            [self assignRepeat: [[s1 copy] autorelease] withValue:  [[s2 copy] autorelease]];
	    //[repVault setObject: [[s2 copy] autorelease] forKey:[[s1 copy] autorelease] ];
            
	    [s1 setString: @""];
	    [s2 setString: @""];
	}
    }
    //apply contingencies
    [self doContWithDict: repVault];
}

-(void) handleUniversal: (NSString *) namelist
{
    NSMutableArray *myUList;
    int n;
    NSMutableString *s1, *s2, *s3;
    NSMutableArray *oneUVar;
    NSEnumerator *myen;
    
    s1 = [[NSMutableString alloc] init];
    s2 = [[NSMutableString alloc] init];
    
    myUList = convertStringToArray(namelist, ',');
    myen = [myUList objectEnumerator];
    n = [myUList count];
    [s1 setString: @""];
    [s2 setString: @""];
    while(s3 = [myen nextObject])
    {
	oneUVar = convertStringToArray(s3, '=');
	if([oneUVar count] == 2)
	{
	    [s1 setString: [oneUVar objectAtIndex: 0]];
	    trimNSS(s1);
	    [s2 setString: [oneUVar objectAtIndex: 1]];
	    trimNSS(s2);
	    
	    //add to both the list and the dictionary
	    trimNSS(s2);
	    trimCharNSS(s2,'\"');
            if(arrayContainsString(univList, s1) == NO)
                [univList addObject: [s1 copy]];
	    [univVault setObject: [[s2 copy] autorelease] forKey: [[s1 copy] autorelease]];
	    [s1 setString: @""];
	    [s2 setString: @""];
	}
    }
    //apply contingencies
    [self doContWithDict: univVault];
}

/* switchboard for the meta commands */
-(void) handlemeta: (ctQChar *) myc
{
    int i;
    NSMutableString *buff;
    buff = [[NSMutableString alloc] init];
    /* trim the data */
    
    if([[myc extra] length])
    {
        i = 0;
        while([[myc extra] characterAtIndex: i] == ' ') 
        {
            i++;
            if(i >= [[myc extra] length]) break;
        }
        [buff setString: [[myc extra] substringFromIndex: i]];
    }
    else [buff setString: @""];
    ON(@"end")
    {
        SETGLOBAL(@"basicflag",0);
        [self handleEnd: NO flush: NO];
        if([self global: @"skipinneratend"] == 1)
            innerRFlag = 0;
    }
    else ON(@"backloadrepeat")
        SETGLOBAL(@"backloadrepeatflag", 1);
    else ON(@"frontloadrepeat") SETGLOBAL(@"backloadrepeatflag", 0);
    else ON(@"endsection"){
        SETGLOBAL(@"basicflag", 0);
        [self handleEnd: YES flush: NO]; 
        if([self global: @"skipinneratend"] == 1)
            innerRFlag = 0;
    }
    //media
    else ON(@"mediafile") {
        [mediaDict setObject: [[[myc extra] copy] autorelease] forKey:[[[[myc source] path] copy] autorelease] ];
    }
    //repeat and ailiases
    else ON(@"repeat")
        [self addToList: repList usingString: buff];
    else ON(@"context")
        [self addToList: repList usingString: buff];
    else ON(@"contextcode")
        [self addToList: repList usingString: buff];
    //inner and aliases
    else ON(@"first") {[lastRepList removeAllObjects]; [innerRepList removeAllObjects];[self addToList: innerRepList usingString: buff]; SETGLOBAL(@"basicflag",0);}
    else ON(@"inner") {[lastRepList removeAllObjects]; [innerRepList removeAllObjects];[self addToList: innerRepList usingString: buff]; SETGLOBAL(@"basicflag",0);}
    else ON(@"innerrepeat") {[lastRepList removeAllObjects]; [innerRepList removeAllObjects];[self addToList: innerRepList usingString: buff]; SETGLOBAL(@"basicflag",0);}
    else ON(@"firstrepeat") {[lastRepList removeAllObjects]; [innerRepList removeAllObjects];[self addToList: innerRepList usingString: buff]; SETGLOBAL(@"basicflag",0);}
    else ON(@"skipinnertopofdoc") 
    {
        SETGLOBAL(@"skipinnertopofdoc",1);
        innerRFlag = 0;
    }
    else ON(@"noskipinnertopofdoc") 
    {
        SETGLOBAL(@"skipinnertopofdoc",0);
        innerRFlag = 1;
    }
    else ON(@"skipinneratend") SETGLOBAL(@"skipinneratend",1);
    else ON(@"noskipinneratend") SETGLOBAL(@"skipinneratend",0);
    //last repeat and aliases
    else ON(@"lastrepeat")
    {SETGLOBAL(@"basicflag",0); [innerRepList removeAllObjects]; [lastRepList removeAllObjects]; [self addToList: lastRepList usingString: buff];SETGLOBAL(@"lastRepeat",0);}
    else ON(@"last")
    {[innerRepList removeAllObjects]; [lastRepList removeAllObjects]; [self addToList: lastRepList usingString: buff];SETGLOBAL(@"lastRepeat",0);}
#ifdef FIELDMAP
    else ON(@"zapmap")
        [fieldMap removeAllObjects];
#endif
    //struct and unstruct and aliases
    else ON(@"basic")
        SETGLOBAL(@"basicflag", 1);
    else ON(@"unstruct")
        SETGLOBAL(@"basicflag", 1);
    else ON(@"unstructured")
        SETGLOBAL(@"basicflag", 1);
    else ON(@"structured")
        SETGLOBAL(@"basicflag",0);
    else ON(@"struct")
        SETGLOBAL(@"basicflag",0);
    
    else ON(@"block")
        [self addToList: blockList usingString: buff];
    else ON(@"universal")
        [self handleUniversal: buff];
    else ON(@"setrepeat")
        [self handleSetRepeat: buff];
    else ON(@"name")
    {
        if([self isUniversal: @"FileName"] == NO)
            [univList addObject: @"FileName"];
        [univVault setObject: trimCharNSS(trimNSS(buff), '\"') forKey: @"FileName"];
        
    }
    else ON(@"setcomment") [self setComment: buff];
    else ON(@"appendcomment") [self appendComment: buff];
    else ON(@"endcomment") [self endComment: buff];
    else ON(@"endlastcomment") [self endLastComment];
    else ON(@"clearcomments") [self clearComments];
    else ON(@"zapuniversal") SETGLOBAL(@"zapuniversal", 1);
    else ON(@"sectionsearch") SETGLOBAL(@"sectionsearch", 1);
    else ON(@"nozapuniversal") SETGLOBAL(@"zapuniversal", 0);
    else ON(@"nopar") SETGLOBAL(@"noparflag ", 0);
    else ON(@"par") SETGLOBAL(@"noparflag", 0);
    else ON(@"empty") SETGLOBAL(@"emptyflag", 0);
    else ON(@"noempty") SETGLOBAL(@"emptyflag", 0);
    else ON(@"emptysection") SETGLOBAL(@"emptysectionflag",1);
    else ON(@"noemptysection") SETGLOBAL(@"emptysectionflag",0);
    else ON(@"if") {[self handleIf: buff];}
#ifdef FIELDMAP
    else ON(@"map") {[self handleMap: buff];}
#endif
    else ON(@"escapeon") SETGLOBAL(@"escapeflag", 1);
    else ON(@"escapeoff") SETGLOBAL(@"escapeflag", 0);
    else ON(@"start")
        SETGLOBAL(@"startflag", 1);
    else ON(@"stop")
        SETGLOBAL(@"startflag", 0);
    //else ON(@"zap")
    //	handlezap();
    else ON(@"clean")
    {
        SETGLOBAL(@"cleanflag", 1);
        [repVault removeAllObjects];
    }
    else ON(@"dirty")
        SETGLOBAL(@"cleanflag", 0);
    else ON(@"tab")
        SETGLOBAL(@"tabflag", 1);
    else ON(@"notab")
        SETGLOBAL(@"tabflag", 0);
    else ON(@"eofisend") SETGLOBAL(@"eofIsEndFlag", 1);
    else ON(@"eofisnotend") SETGLOBAL(@"eofIsEndFlag", 0);
    else ON(@"limit")
    {
        SETGLOBAL(@"limitflag", 0);
        if(limitString == nil)
        {
            limitString = [[NSMutableString alloc] init];
        }
        [limitString setString: buff];
    }
    //else ON(@"zero")
    //	handlezero();
    //else ON(@"zerozero")
    //	zeromark = 0L;
    else ON(@"header") {SETGLOBAL(@"headerflag", 1); SETGLOBAL(@"firstwriteflag", 0);}
    else ON(@"noheader") {SETGLOBAL(@"headerflag", 0);
        SETGLOBAL(@"firstwriteflag", 0);}
    else ON(@"quote") SETGLOBAL(@"quoteflag", 1);
    else ON(@"noquote") SETGLOBAL(@"quoteflag", 0);
    else ON(@"exact") SETGLOBAL(@"exactflag", 1);
    else ON(@"notexact") SETGLOBAL(@"exactflag", 0);
    else ON(@"raw") SETGLOBAL(@"rawflag", 1);
    else ON(@"notraw") SETGLOBAL(@"rawflag", 0);
    else ON(@"append") [fmode setString: @"a"];
    else ON(@"notappend") [fmode setString: @"w"];
    //else ON(@"conname") handlecon(buff.val());
    //else ON(@"datname") handledat(buff.val());
    //else ON(@"macnl") setnewline(MACNL);
    //else ON(@"unixnl") setnewline(UNIXNL);
    else ON(@"noblank") SETGLOBAL(@"blankflag", 0);
    else ON(@"blank") SETGLOBAL(@"blankflag", 1);
    else ON(@"paranum") SETGLOBAL(@"lineflag", 0);
    else ON(@"noparanum") SETGLOBAL(@"lineflag", 0);
    else ON(@"recnum") SETGLOBAL(@"lnumflag", 1);
    else ON(@"norecnum") SETGLOBAL(@"lnumflag", 0);
    else ON(@"dummy") ;
    else ON(@"comment");
    else ;
    
}
-(NSMutableString *) limString
{
    if(limitString)
        return limitString;
    else
        return @"";
}

-(IBAction) toggleCaseSensitive: (id) sender
{
    int state;
    if(caseSortFlag == NO)
    {
	NSLog(@"about to turn on case\n");
        [[[NSApp delegate] caseMenuItem] setState: NSOffState];
        caseSortFlag = YES;
	NSLog(@"turned on case\n");
    }
    else
    {
	NSLog(@"about to turn off case\n");
        [[[NSApp delegate] caseMenuItem] setState: NSOnState];
	NSLog(@"turned off case\n");
        caseSortFlag = NO;
    }
}
-(void) resetCaseSensitive
{
    if(caseSortFlag == YES)
    {
        [[[NSApp delegate] caseMenuItem] setState: NSOnState];
    }
    else
    {
        [[[NSApp delegate] caseMenuItem] setState: NSOffState];
    }
}
-(BOOL) getCaseSensitive {return caseSortFlag;}

-(IBAction) sortUpAZ: (id) sender
{
    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
    [fakeMI setTag: 2];
    [fakeMI autorelease];
    [self sortUp: fakeMI];
}
-(IBAction) sortUpDate: (id) sender
{
    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
    [fakeMI setTag: 1];
    [fakeMI autorelease];
    [self sortUp: fakeMI];
}
-(IBAction) sortUpCodeWithin: (id) sender
{
    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
    [fakeMI setTag: 15];
    [fakeMI autorelease];
    [self sortUp: fakeMI];
}

-(IBAction) sortUpCode: (id) sender
{
    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
    [fakeMI setTag: 5];
    [fakeMI autorelease];
    [self sortUp: fakeMI];
}

-(IBAction) sortUpFloat: (id) sender
{
    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
    [fakeMI setTag: 3];
    [fakeMI autorelease];
    [self sortUp: fakeMI];
}

-(IBAction) sortUpInt: (id) sender
{
    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
    [fakeMI setTag: 4];
    [fakeMI autorelease];
    [self sortUp: fakeMI];
}
-(IBAction) sortUpIntWithin: (id) sender
{
    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
    [fakeMI setTag: 14];
    [fakeMI autorelease];
    [self sortUp: fakeMI];
}
-(IBAction) sortUpAZWithin: (id) sender
{
    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
    [fakeMI setTag: 12];
    [fakeMI autorelease];
    [self sortUp: fakeMI];
}

-(IBAction) sortUp: (id) Sender
{
    //get the column
    int n;
    int tt;
    NSMutableDictionary *ssi;
    int myType;
    id key;
    
    n = [theResults selectedColumn];
    if(n > 0)
    {
	key = [[[theResults tableColumns] objectAtIndex: n] identifier];
	tt = [Sender tag];
	if(tt < 10) //not within
	{
	    [sortStack removeAllObjects];
	    myType = tt;
	}
	else
	    myType = tt - 10;
	
        //	ssi = [[MWSortStackItem alloc] initWithID: key direction: YES type: myType dateFormat: dfString codeLevel: aCodeLevel];
        ssi = [NSMutableDictionary dictionary];
        [ssi setObject: [[key copy] autorelease] forKey: @"col"];
        [ssi setObject: [[dfString copy] autorelease] forKey: @"dateFormat"];
        [ssi setObject: [NSNumber numberWithBool: YES] forKey: @"up"];
        [ssi setObject: [NSNumber numberWithInt: myType] forKey: @"type"];
        [ssi setObject: [NSNumber numberWithInt: aCodeLevel] forKey: @"codeLevel"];
        if([self getCaseSensitive] == YES) [ssi setObject: @"C" forKey: @"case"];
        
        //	[ssi autorelease];
	[sortStack addObject: ssi];
	[myData sortUsingFunction: stackComp context: sortStack];
        [theResults reloadData];
        MAKEDIRTY;
        
    }
    else
	NSWARNING(@"No data column selected");
    
}
-(void) sortData: (NSMutableArray *) who withStack: (NSArray *) stack
{
    NSMutableArray *a = [[NSMutableArray alloc] init];
    FORALL(stack)
    {
        [a addObject: temp];
        [who sortUsingFunction: stackComp context: a];
    }
    ENDFORALL;
    [a release];
}
-(NSMutableArray *) sortStackCopy
{
    return [[sortStack copy] autorelease];
}

-(IBAction) sortDown: (id) Sender
{
    //get the column
    int n;
    int tt;
    NSMutableDictionary *ssi;
    int myType;
    id key;
    n = [theResults selectedColumn];
    if(n > 0)
    {
	key = [[[theResults tableColumns] objectAtIndex: n] identifier];
	tt = [Sender tag];
	if(tt < 10) //not within
	{
	    [sortStack removeAllObjects];
	    myType = tt;
	}
	else
	    myType = tt - 10;
	
	//ssi = [[MWSortStackItem alloc] initWithID: key direction: NO type: myType dateFormat: dfString codeLevel: aCodeLevel];
	//[ssi autorelease];
        ssi = [NSMutableDictionary dictionary];
        [ssi setObject: [[key copy] autorelease] forKey: @"col"];
        [ssi setObject: [[dfString copy] autorelease] forKey: @"dateFormat"];
        [ssi setObject: [NSNumber numberWithBool: NO] forKey: @"up"];
        [ssi setObject: [NSNumber numberWithInt: myType] forKey: @"type"];
        [ssi setObject: [NSNumber numberWithInt: aCodeLevel] forKey: @"codeLevel"];
        if([self getCaseSensitive] == YES) [ssi setObject: @"C" forKey: @"case"];
        [sortStack addObject: ssi];
	[myData sortUsingFunction: stackComp context: sortStack];
	[theResults reloadData];    
        MAKEDIRTY;
    }
    else
	NSWARNING (@"No data column selected");
    
    
    
}
-(IBAction) sortColumn: (id) Sender
{
    //get the column
    int n;
    id key;
    n = [theResults selectedColumn];
    if(n > 0)
    {
	key = [[[theResults tableColumns] objectAtIndex: n] identifier];    
        //sort
	if([key isEqualToString: @"_begin_loc"] == YES)
	    [myData sortUsingFunction: longFwdComp context: key];
	else
	    [myData sortUsingFunction: stringComp context: key];
    }
    UPDATERECCOUNT;
    [theResults reloadData];
    
}
-(IBAction) smartSort: (id) Sender
{
    //get the column
    int n;
    id key;
    n = [theResults selectedColumn];
    if(n > 0)
    {
	key = [[[theResults tableColumns] objectAtIndex: n] identifier];    
        //sort
	if([key isEqualToString: @"_begin_loc"] == YES ||[key isEqualToString: @"_line_number"] )
	    [self sortUpInt: nil];
	else if ([key isEqualToString: @"_code"] == YES)
	    [self sortUpCode: nil];
        else 
            [self sortUpAZ: nil];
    }
    UPDATERECCOUNT;
    [theResults reloadData];
    
}
-(void) dateFmtDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    if(returnCode == 1)
    {
        int dtag = [[dateFormatMenu selectedItem] tag];
        dfIndex = dtag;
	if(dtag == 99)
	{
	    [dfString setString: [dateFormatOther stringValue]];
	}
	else
	{
	    [dfString setString: dateFmt[dtag]];
	}
        MAKEDIRTY;
    }
}
-(IBAction) okSetDateFmt: (id) Sender
{
    [dateFormatSheet orderOut: Sender];
    [NSApp endSheet: dateFormatSheet returnCode: 1];
    
}
-(IBAction) cancelSetDateFmt: (id) Sender
{
    [dateFormatSheet orderOut: Sender];
    [NSApp endSheet: dateFormatSheet returnCode: 0];
    
}
-(IBAction) doSetDateFmt: (id) Sender
{
    NSWindow *who;
    
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    if(dfIndex < 0) [dateFormatMenu selectItemAtIndex: 0];
    else if( dfIndex < 99)
    {
        [dateFormatMenu selectItemWithTag: dfIndex];
        [dateFormatOther setStringValue: @""];
    }
    else
    {
        [dateFormatMenu selectItemWithTag: dfIndex];
        [dateFormatOther setStringValue: dfString];
    }
    
    
    [NSApp beginSheet: dateFormatSheet
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(dateFmtDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}

/*---------------------  Selected Records ----------------*/

-(NSMutableArray*) handleStep: (NSMutableDictionary *) who onArray: (NSMutableArray *) ss
{
    NSMutableArray *ans = [NSMutableArray array];
    id cstype;
    int csIntType;
    id extype;
    BOOL exBoolType;
    
    if([[who objectForKey: @"stepType"] isEqualToString: @"sel"] == YES)
    {
        switch( [[who objectForKey: @"mode"] intValue])
        {
            case SELECTREVERSE:
            case SELECTADDITIONAL:
                [ans setArray: ss];
                [self handleSelect: [[who objectForKey: @"mode"] intValue]
                        selectType: [[who objectForKey: @"type"] intValue]
                        withString: [who objectForKey: @"searchValue"]
                           withCol: [who objectForKey: @"col"]
                            floatV: [[who objectForKey: @"float"] intValue]
                            regexV: [[who objectForKey: @"regex"] intValue]
                        startArray: backData
                          endArray: ans];
                break;
            case SELECTCODESET:
                cstype = [who objectForKey: @"type"];
                if (cstype == nil)
                    csIntType = SELECT;
                else
                    csIntType = [cstype intValue];
                extype = [who objectForKey: @"exact"];
                if(extype == nil) exBoolType = YES;
                else exBoolType = [extype boolValue];
                
                [self selectDataFrom: ss to: ans forCodeSet: [who objectForKey: @"name"] type: csIntType exact: exBoolType];
                break;
                
            default:
                [self handleSelect: [[who objectForKey: @"mode"] intValue]
                        selectType: [[who objectForKey: @"type"] intValue]
                        withString: [who objectForKey: @"searchValue"]
                           withCol: [who objectForKey: @"col"]
                            floatV: [[who objectForKey: @"float"] intValue]
                            regexV: [[who objectForKey: @"regex"] intValue]
                        startArray: ss
                          endArray: ans];
                break;
        };
        
    }
    //put runing an autoset here
    else if([[who objectForKey: @"stepType"] isEqualToString: @"autoset"] == YES)
    {
        [ans setArray: [self applyAutoSetWithName:
            
              [who objectForKey: @"name"] toArray: ss]];
        
    }
    
    else
    {
        [self handleSet:
            [[who objectForKey: @"op"] intValue]
            
                withSet: [self getAutoSetWithName: [who objectForKey: @"obj"]]
             startArray: ss endArray: ans];        
    }
    
    return ans; 
}

-(NSMutableArray*) getSetWithName: (NSString*) who
{
    NSMutableArray  *aa;
    
    aa = [namedSelDict objectForKey: who];
    if(aa == nil)
        return [self getAutoSetWithName: who];
    else
        return [NSMutableArray arrayWithArray: aa];
    
}
-(NSMutableDictionary *) autoHistoryAsProgram
{
    NSMutableDictionary *myMac = [NSMutableDictionary dictionary];
    [myMac setObject: [self autoHistory] forKey: @"program"];
    [myMac setObject: @"All" forKey: @"start"];
    return myMac;
}
-(NSMutableArray*) applyAutoSetWithName: (NSString *) who toArray: (NSMutableArray *) showing
{
    NSMutableArray *ans = [NSMutableArray array];
    NSMutableDictionary *myMac;
    NSMutableArray *myProg;
    NSMutableArray *sData, *s2, *s1;
    NSArray *ss;
    if([self isAutoSet: who] == NO) return showing;
    sData = [[NSMutableArray alloc] init];
    myMac = [self autoSetForName: who];
    
    myProg = [myMac objectForKey: @"program"];
    ss = [myMac objectForKey: @"sort"];
    
    if([[myMac objectForKey: @"start"] isEqualToString: @"All"] == YES)
        [sData addObjectsFromArray: backData];
    else if([[myMac objectForKey: @"start"] isEqualToString: @"Visible"] == YES)
        [sData addObjectsFromArray: showing];
    else
        [sData addObjectsFromArray: [self getAutoSetWithName: [myMac objectForKey: @"start"]]];
    s2 = sData;
    if(ss != nil)
        [self sortData: sData withStack: ss];
    if(myProg)
    {
        FORALL(myProg)
    {
            s1 = [self handleStep: temp onArray: s2];
            s2 = s1; //keep sending it back in        
    }
        ENDFORALL;
    }
    [ans addObjectsFromArray: s2];
    [sData release];
    return ans;
}

-(NSMutableArray*) getAutoSetWithName: (NSString *) who
{
    NSMutableArray *ans = [NSMutableArray array];
    NSMutableDictionary *myMac;
    NSMutableArray *myProg;
    NSMutableArray *sData, *s2, *s1;
    NSArray *ss;
    
    sData = [[NSMutableArray alloc] init];
    if(who == nil)
    {
        myMac = [self autoHistoryAsProgram];
    }
    else
        myMac = [self autoSetForName: who];
    
    myProg = [myMac objectForKey: @"program"];
    ss = [myMac objectForKey: @"sort"];
    
    if([[myMac objectForKey: @"start"] isEqualToString: @"All"] == YES)
        [sData addObjectsFromArray: backData];
    else if([[myMac objectForKey: @"start"] isEqualToString: @"Visible"] == YES)
        [sData addObjectsFromArray: myData];
    else
        [sData addObjectsFromArray: [self getAutoSetWithName: [myMac objectForKey: @"start"]]];
    s2 = sData;
    if(ss != nil)
        [self sortData: sData withStack: ss];
    if(myProg)
    {
        FORALL(myProg)
    {
            s1 = [self handleStep: temp onArray: s2];
            s2 = s1; //keep sending it back in        
    }
        ENDFORALL;
    }
    [ans addObjectsFromArray: s2];
    [sData release];
    return ans;
}
-(void) handleSet: (int) opType withSet: (NSArray *) mm startArray: (NSMutableArray*) a1 endArray: (NSMutableArray*) a2
{
    int i,n;
    NSMutableArray *final = [[NSMutableArray alloc] init];
    
    {
        //get subset
        //mm = [namedSelDict objectForKey: [[setMathSetMenu selectedItem] title]];
        //opType = [[setMathOpMenu selectedItem] tag];
        switch (opType)
        {
            case 1: //intersect with
                FORALL(mm)
            {
                    if([a1 indexOfObject: temp] == NSNotFound)
                    {
                    }
                    else
                        [final addObject: temp];
            }
                ENDFORALL;
                [a2 addObjectsFromArray: final];
                break;
                
            case 2: //union
                FORALL(mm)
            {
                    if([a1 indexOfObject: temp] == NSNotFound)
                    {
                        [final addObject: temp];
                    }
            }
                ENDFORALL;
                [a2 addObjectsFromArray: final];
                break;
                
            case 3: //Don't intersect with
                n = [mm count];
                for(i = 0; i < n; i++)
                {
                    [a1 removeObject: [mm objectAtIndex: i]];
                }
                    break;
                
            case 4: //not in union with
                n = [backData count];
                for(i = 0; i < n; i++)
                {
                    if([a1 containsObject: [backData objectAtIndex: i]] == YES ||
                       [mm containsObject: [backData objectAtIndex: i]] == YES)
                    {
                    }
                    else
                    {
                        [a1 addObject: [backData objectAtIndex: i]];
                    }
                }
                    [a2 addObjectsFromArray: final];
                break;
                
            case 5: // XOR
                n = [mm count];
                for(i = 0; i < n ; i++)
                {
                    [a2 addObjectsFromArray: a1];
                    if([a2 containsObject: [mm objectAtIndex: i]] == YES)
                    {
                        [a2 removeObject: [mm objectAtIndex: i]];
                    }
                    else
                    {
                        [a2 addObject: [mm objectAtIndex: i]];
                    }
                }
                    break;
                
        };
        [final release];
    }
    
}

-(void) handleSelect: (int) selectMode selectType: (int) st withString: (NSString *)  compValue  withCol: (NSString *) colName floatV: (int) fp regexV: (int) rf startArray: (NSMutableArray*) a1 endArray: (NSMutableArray*) a2
{
    NSMutableArray *findList, *findFromList;
    NSRange a;
    AGRegex *myRegex;
    AGRegexMatch *myRegexMatch;
    NSString *fString;
    
    int n, i, cres, frflag;
    
    findList = [[NSMutableArray alloc] init];
    findFromList = [[NSMutableArray alloc] init];
    if(selectMode == SELECTREVERSE)
    {
        [findList setArray: a1];
        [findList removeObjectsInArray: a2];
        [a2 setArray: findList];
        [findList release];
        [findFromList release];
        return;
    }
    
    [findFromList addObjectsFromArray: a1];
    
    n = [findFromList count];
    for(i =0; i < n; i++)
    {
        if([@"_doc" isEqualToString: colName ] == YES)
        {
            fString =  [(MWFile *)[[findFromList objectAtIndex: i] objectForKey:
                colName] name];
        }
        else
            fString = [[findFromList objectAtIndex: i] objectForKey:
                colName];
	switch(st)
	{
	    case SELALPHA:
                if(rf)
                {
                    myRegex = [[AGRegex alloc] initWithPattern: compValue
                                                       options: AGRegexCaseInsensitive];
                    myRegexMatch = [myRegex findInString: fString];
                    if([myRegexMatch count])
                    {
                        [findList addObject: [findFromList objectAtIndex: i]];
                    }
                    [myRegex release];
                    //[myRegexMatch release];
                }
                else
                {
                    a = [fString rangeOfString: compValue options: NSCaseInsensitiveSearch];
                    if(a.location != NSNotFound)
                    {
                        [findList addObject: [findFromList objectAtIndex: i]];
                    }
                }
		break;
                
	    case SELALPHACASE:
                if(rf)
                {
                    myRegex = [[AGRegex alloc] initWithPattern: compValue];
                    myRegexMatch = [myRegex findInString: fString];
                    if([myRegexMatch count])
                    {
                        [findList addObject: [findFromList objectAtIndex: i]];
                    }
                    [myRegex release];
                    [myRegexMatch release];
                }
                else
                {
                    a = [fString  rangeOfString: compValue ];
                    if(a.location != NSNotFound)
                    {
                        [findList addObject: [findFromList objectAtIndex: i]];
                    }
                }
		break;
                
            case SELEXACT: //no regex for this one
            {
                int ans;
                ans = [fString 
                        isEqualToString: compValue ];
                if(ans == YES)
                {
                    [findList addObject: [findFromList objectAtIndex: i]];
                }
            }
		break;
                
	    case SELEQUAL:
		if(fp)
		{
		    if([fString doubleValue]
                       == [compValue doubleValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		}
		else
		    if([fString intValue]
                       == [compValue intValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		
		break;
                
	    case SELGT:
		if(fp)
		{
		    if([fString doubleValue]
                       > [compValue doubleValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		}
		else
		    if([fString intValue]
                       > [compValue intValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		
		break;
                
	    case SELGTE:
		if(fp)
		{
		    if([fString doubleValue]
                       >= [compValue doubleValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		}
		else
		    if([fString intValue]
                       >= [compValue intValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		
		break;
                
	    case SELLT:
		if(fp)
		{
		    if([fString doubleValue]
                       < [compValue doubleValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		}
		else
		    if([fString intValue]
                       < [compValue intValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		
		break;
	    case SELLTE:
		if(fp)
		{
		    if([fString doubleValue]
                       <= [compValue doubleValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		}
		else
		    if([fString intValue]
                       <= [compValue intValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		
		break;
	    case SELDATE:
                cres = [(NSDate *) [NSCalendarDate dateWithString: 
                    fString
                                                   calendarFormat: dfString] compare:
                    [NSCalendarDate dateWithString: compValue
                                    calendarFormat: dfString]];
                if(cres == NSOrderedSame)
                    [findList addObject: [findFromList objectAtIndex: i]];
		    break;
                
	    case SELBEFOREDATE:
                cres = [(NSDate *) [NSCalendarDate dateWithString: 
                    fString
                                                   calendarFormat: dfString] compare:
                    [NSCalendarDate dateWithString: compValue
                                    calendarFormat: dfString]];
                if(cres == NSOrderedAscending)
                    [findList addObject: [findFromList objectAtIndex: i]];
		    break;
                
	    case SELAFTERDATE:
                cres = [(NSDate *) [NSCalendarDate dateWithString: 
                    fString
                                                   calendarFormat: dfString] compare:
                    [NSCalendarDate dateWithString: compValue
                                    calendarFormat: dfString]];
                if(cres == NSOrderedDescending)
                    [findList addObject: [findFromList objectAtIndex: i]];
		    break;
		
	    case SELBEFOREEQDATE:
                cres = [(NSDate *) [NSCalendarDate dateWithString: 
                    fString
                                                   calendarFormat: dfString] compare:
                    [NSCalendarDate dateWithString: compValue
                                    calendarFormat: dfString]];
                if(cres == NSOrderedAscending || cres == NSOrderedSame)
                    [findList addObject: [findFromList objectAtIndex: i]];
		    break;
		
	    case SELAFTEREQDATE:
                cres = [(NSDate *) [NSCalendarDate dateWithString: 
                    fString
                                                   calendarFormat: dfString] compare:
                    [NSCalendarDate dateWithString: compValue
                                    calendarFormat: dfString]];
                if(cres == NSOrderedDescending || cres == NSOrderedSame)
                    [findList addObject: [findFromList objectAtIndex: i]];
		    break;
		
		
		
	    default: ;
	}
    }
    if(selectMode == SELECTADDITIONAL)
    {
	n = [findList count];
	if(n == 0) 
        {
            NSWARNING(@"No records found"); 
            frflag=0;
        }
	else
	{
            frflag = 1;
	    for(i = 0; i<n; i++)
	    {
		if([a2 indexOfObject: [findList objectAtIndex: i]]
                   == NSNotFound)
		{
		    [a2 addObject: [findList objectAtIndex: i]];
		}
	    }
	}
    }
    else if(selectMode == SELECTFEWER)
    {
	n = [findList count];
	if(n == 0) 
        {
            NSWARNING(@"No records found"); 
            frflag=0;
        }
	else
	{
            [a2 setArray: a1];
            [a2 removeObjectsInArray: findList];
            
        }
        
    }
    else if (selectMode == SELECT)
    {
	if([findList count] == 0) 
        {
            NSWARNING(@"No records found"); 
            frflag = 0;
        }
	else
	{
	    [a2 removeAllObjects];
	    [a2 addObjectsFromArray: findList];
            frflag = 1;
	}
    }
    //Clean up
    [findList release];
    [findFromList release];
    
}

-(void) selectDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    NSMutableArray *findList, *findFromList;
    NSMutableString *compValue;
    NSRange a;
    AGRegex *myRegex;
    AGRegexMatch *myRegexMatch;
    NSString *fString;
    
    int rr, n, st, fp, rf, i, cres, frflag;
    if(returnCode == 0) return;
    rr = [theResults selectedRow];
    findList = [[NSMutableArray alloc] init];
    findFromList = [[NSMutableArray alloc] init];
    compValue = [[NSMutableString alloc] init];
    [compValue setString: [selectField stringValue]];
    st = [[selectMenu selectedItem] tag];
    fp = [selectFloat intValue];
    rf = [selectRegexFlag intValue];
    frflag = 0;
    //this block is for autohistory
    {
        NSMutableDictionary *ahd = [NSMutableDictionary dictionary];
        [ahd setObject: @"sel" forKey: @"stepType"];
        [ahd setObject: [NSNumber numberWithInt: selectMode] forKey: @"mode"];
        [ahd setObject: [NSNumber numberWithInt: st] forKey: @"type"];
        [ahd setObject: [[compValue copy] autorelease] forKey: @"searchValue"];
        [ahd setObject: [[SELECTEDCOLUMNID(theResults) copy] autorelease] forKey: @"col"];
        [ahd setObject: [NSNumber numberWithInt: fp] forKey: @"float"];
        [ahd setObject: [NSNumber numberWithInt: rf] forKey: @"regex"];
        [autoHistory addObject: ahd];
    }
    if(selectMode == SELECTADDITIONAL)
    {
	[findFromList addObjectsFromArray: backData];
    }
    else
    {
	[findFromList addObjectsFromArray: myData];
    }
    n = [findFromList count];
    for(i =0; i < n; i++)
    {
        if([@"_doc" isEqualToString: SELECTEDCOLUMNID(theResults) ] == YES)
        {
            fString =  [(MWFile *)[[findFromList objectAtIndex: i] objectForKey:
                SELECTEDCOLUMNID(theResults)] name];
        }
        else
            fString = [[findFromList objectAtIndex: i] objectForKey:
                SELECTEDCOLUMNID(theResults)];
	switch(st)
	{
	    case SELALPHA:
                if(rf)
                {
                    myRegex = [[AGRegex alloc] initWithPattern: compValue
                                                       options: AGRegexCaseInsensitive];
                    myRegexMatch = [myRegex findInString: fString];
                    if([myRegexMatch count])
                    {
                        [findList addObject: [findFromList objectAtIndex: i]];
                    }
                    [myRegex release];
                    //[myRegexMatch release];
                }
                else
                {
                    a = [fString rangeOfString: compValue options: NSCaseInsensitiveSearch];
                    if(a.location != NSNotFound)
                    {
                        [findList addObject: [findFromList objectAtIndex: i]];
                    }
                }
		break;
                
	    case SELALPHACASE:
                if(rf)
                {
                    myRegex = [[AGRegex alloc] initWithPattern: compValue];
                    myRegexMatch = [myRegex findInString: fString];
                    if([myRegexMatch count])
                    {
                        [findList addObject: [findFromList objectAtIndex: i]];
                    }
                    [myRegex release];
                    [myRegexMatch release];
                }
                else
                {
                    a = [fString  rangeOfString: compValue ];
                    if(a.location != NSNotFound)
                    {
                        [findList addObject: [findFromList objectAtIndex: i]];
                    }
                }
		break;
                
            case SELEXACT: //no regex for this one
            {
                int ans;
                ans = [fString 
                        isEqualToString: compValue ];
                if(ans == YES)
                {
                    [findList addObject: [findFromList objectAtIndex: i]];
                }
            }
		break;
                
	    case SELEQUAL:
		if(fp)
		{
		    if([fString doubleValue]
                       == [compValue doubleValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		}
		else
		    if([fString intValue]
                       == [compValue intValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		
		break;
                
	    case SELGT:
		if(fp)
		{
		    if([fString doubleValue]
                       > [compValue doubleValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		}
		else
		    if([fString intValue]
                       > [compValue intValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		
		break;
                
	    case SELGTE:
		if(fp)
		{
		    if([fString doubleValue]
                       >= [compValue doubleValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		}
		else
		    if([fString intValue]
                       >= [compValue intValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		
		break;
                
	    case SELLT:
		if(fp)
		{
		    if([fString doubleValue]
                       < [compValue doubleValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		}
		else
		    if([fString intValue]
                       < [compValue intValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		
		break;
	    case SELLTE:
		if(fp)
		{
		    if([fString doubleValue]
                       <= [compValue doubleValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		}
		else
		    if([fString intValue]
                       <= [compValue intValue])
		    {
			[findList addObject: [findFromList objectAtIndex: i]];
		    }
		
		break;
	    case SELDATE:
                cres = [(NSDate *) [NSCalendarDate dateWithString: 
                    fString
                                                   calendarFormat: dfString] compare:
                    [NSCalendarDate dateWithString: compValue
                                    calendarFormat: dfString]];
                if(cres == NSOrderedSame)
                    [findList addObject: [findFromList objectAtIndex: i]];
		    break;
                
	    case SELBEFOREDATE:
                cres = [(NSDate *) [NSCalendarDate dateWithString: 
                    fString
                                                   calendarFormat: dfString] compare:
                    [NSCalendarDate dateWithString: compValue
                                    calendarFormat: dfString]];
                if(cres == NSOrderedAscending)
                    [findList addObject: [findFromList objectAtIndex: i]];
		    break;
                
	    case SELAFTERDATE:
                cres = [(NSDate *) [NSCalendarDate dateWithString: 
                    fString
                                                   calendarFormat: dfString] compare:
                    [NSCalendarDate dateWithString: compValue
                                    calendarFormat: dfString]];
                if(cres == NSOrderedDescending)
                    [findList addObject: [findFromList objectAtIndex: i]];
		    break;
		
	    case SELBEFOREEQDATE:
                cres = [(NSDate *) [NSCalendarDate dateWithString: 
                    fString
                                                   calendarFormat: dfString] compare:
                    [NSCalendarDate dateWithString: compValue
                                    calendarFormat: dfString]];
                if(cres == NSOrderedAscending || cres == NSOrderedSame)
                    [findList addObject: [findFromList objectAtIndex: i]];
		    break;
		
	    case SELAFTEREQDATE:
                cres = [(NSDate *) [NSCalendarDate dateWithString: 
                    fString
                                                   calendarFormat: dfString] compare:
                    [NSCalendarDate dateWithString: compValue
                                    calendarFormat: dfString]];
                if(cres == NSOrderedDescending || cres == NSOrderedSame)
                    [findList addObject: [findFromList objectAtIndex: i]];
		    break;
		
		
		
	    default: ;
	}
    }
    if(selectMode == SELECTADDITIONAL)
    {
	n = [findList count];
	if(n == 0) 
        {
            NSWARNING(@"No records found"); 
            frflag=0;
        }
	else
	{
            frflag = 1;
	    for(i = 0; i<n; i++)
	    {
		if([myData indexOfObject: [findList objectAtIndex: i]]
                   == NSNotFound)
		{
		    [myData addObject: [findList objectAtIndex: i]];
		}
	    }
	}
    }
    else if(selectMode == SELECTFEWER)
    {
	n = [findList count];
	if(n == 0) 
        {
            NSWARNING(@"No records found"); 
            frflag=0;
        }
	else
	{
            [myData removeObjectsInArray: findList];
            frflag = 1;
        }
        
    }
    else if (selectMode == SELECT)
    {
	if([findList count] == 0) 
        {
            NSWARNING(@"No records found"); 
            frflag = 0;
        }
	else
	{
	    [myData removeAllObjects];
	    [myData addObjectsFromArray: findList];
            frflag = 1;
	}
    }
    if(frflag)
        if(selectMode ==SELECTADDITIONAL)
            [self addStateString: [NSString stringWithFormat: @"+%@: %@", compValue, 
                SELECTEDCOLUMNID(theResults)]];
        else if(selectMode ==SELECTFEWER)
            [self addStateString: [NSString stringWithFormat: @"-%@: %@", compValue, 
                SELECTEDCOLUMNID(theResults)]];
        else
            [self addStateString: [NSString stringWithFormat: @"%@: %@", compValue, 
                SELECTEDCOLUMNID(theResults)]];
    [self updateRecCountVertical];
    [theResults reloadData];
    //Clean up
    [findList release];
    [findFromList release];
    [compValue release];
    
}

-(IBAction) doSelect: (id) Sender
{
    [self pushSetStack];
    [selectSheet orderOut: Sender];
    [NSApp endSheet: selectSheet returnCode: 1];
    
}
-(IBAction) cancelSelect: (id) Sender
{
    [selectSheet orderOut: Sender];
    [NSApp endSheet: selectSheet returnCode: 0];
    
}
-(NSMutableArray *) allData {return backData;}

-(IBAction) selectAllRecs: (id) Sender
{
    [self pushSetStack];
    [myData removeAllObjects];
    [autoHistory removeAllObjects];
    [autoHistoryStart setString: @""];
    [myData addObjectsFromArray: backData];
    [theResults reloadData];
    [self updateRecCountVertical];
    [self setOriginalStateString];
}
-(IBAction) selectAdditionalRecs: (id) Sender
{
    int n;
    NSWindow *who;
    
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    //check if col is selected
    n = [theResults selectedColumn];
    if(n <= 0)
    {
	NSWARNING(@"You must pick a column to select data within.");
	return;
    }
    
    //if yes put up the sheet
    //save the type of search
    selectMode = SELECTADDITIONAL;
    //first fill in the blank!
    [selectField setStringValue: @""];
    [selectMenu selectItemAtIndex: 0];
    [selectRegexFlag setIntValue: 0];
    [selectFloat setIntValue: 0];
    [NSApp beginSheet: selectSheet
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(selectDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}
-(IBAction) selectFewerRecs: (id) Sender
{
    int n;
    NSWindow *who;
    
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    //check if col is selected
    n = [theResults selectedColumn];
    if(n <= 0)
    {
	NSWARNING(@"You must pick a column to select data within.");
	return;
    }
    
    //if yes put up the sheet
    //save the type of search
    selectMode = SELECTFEWER;
    //first fill in the blank!
    [selectField setStringValue: @""];
    [selectMenu selectItemAtIndex: 0];
    [selectRegexFlag setIntValue: 0];
    [selectFloat setIntValue: 0];
    [NSApp beginSheet: selectSheet
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(selectDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}

-(IBAction) selectRecs: (id) Sender
{
    int n;
    NSWindow *who;
    //check if col is selected
    n = [theResults selectedColumn];
    if(n <= 0)
    {
	NSWARNING(@"You must pick a column to select data within.");
	return;
    }
    
    //if yes put up the sheet
    //save the type of search
    selectMode = SELECT;
    //first fill in the blank!
    [selectField setStringValue: @""];
    [selectMenu selectItemAtIndex: 0];
    [selectRegexFlag setIntValue: 0];
    [selectFloat setIntValue: 0];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    [NSApp beginSheet: selectSheet
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(selectDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}
-(IBAction) selectReverseRecs: (id) Sender
{
    int i,n;
    NSMutableArray *findData;
    
    findData = [[NSMutableArray alloc] init];
    
    n = [backData count];
    for(i = 0; i < n; i++)
    {
        if([myData indexOfObject: [backData objectAtIndex: i]] == NSNotFound)
        {
            [findData addObject: [backData objectAtIndex: i]];
        }
    }
    if([findData count] <= 0)
    {
	NSWARNING(@"No data found.");
	return;
    }
    //this block is for autohistory
    {
        NSMutableDictionary *ahd = [NSMutableDictionary dictionary];
        [ahd setObject: @"sel" forKey: @"stepType"];
        [ahd setObject: [NSNumber numberWithInt: SELECTREVERSE] forKey: @"mode"];
        [autoHistory addObject: ahd];
    }
    [self pushSetStack];
    [myData removeAllObjects];
    [myData addObjectsFromArray: findData];
    [findData release];
    UPDATERECCOUNT;
    [theResults reloadData];
    [self addStateString: @"reversed"];
}

-(IBAction) removeSelected: (id) Sender
{
    if(NSYESNOQUESTION(@"Really remove the selected from the dataset?") == NO) return;
    [backData removeObjectsInArray: myData];
    [myData removeAllObjects];
    [myData addObjectsFromArray: backData];
    [self clearNamedSelMenu: nil];
    [self zeroSetStack];
    UPDATERECCOUNT;
    [theResults reloadData];
    [self setOriginalStateString];
    [self addStateString: @"-selected"];
}

-(IBAction) removeUnselected: (id) Sender
{
    if(NSYESNOQUESTION(@"Really remove the unselected from the dataset?") == NO) return;
    [backData removeAllObjects];
    [backData addObjectsFromArray: myData];
    [self clearNamedSelMenu: nil];
    [self zeroSetStack];
    UPDATERECCOUNT;
    [theResults reloadData];
    [self setOriginalStateString];
    [self addStateString: @"-unselected"];
}

-(IBAction) selectMarked: (id) Sender
{
    int i, n;
    NSMutableArray *fd = [[NSMutableArray alloc] init];
    n = [backData count];
    for(i = 0; i < n; i++)
    {
        if([self isMarkedRecord: [backData objectAtIndex: i]] == YES)
            [fd addObject: [backData objectAtIndex: i]];
    }
    if([fd count])
    {
        [self pushSetStack];
        [myData removeAllObjects];
        [myData addObjectsFromArray: fd];
        UPDATERECCOUNT;
        [theResults reloadData];
    }
    else
    {
        NSWARNING(@"No marked records");
    }
    [fd release];
    [self setStateString: @"marked"];
    
}

-(IBAction) addMarkedToSelected: (id) Sender;
{
    [self pushSetStack];
    FORALL(backData)
    {
        if([self isMarkedRecord: temp] == YES)
        {
            if([myData indexOfObject: temp] == NSNotFound)
            {
                [myData addObject: temp];
            }
        }
    }ENDFORALL;
    UPDATERECCOUNT;
    [theResults reloadData];
    [self addStateString: @"+marked"];
}

-(IBAction) addUnmarkedToSelected: (id) Sender;
{
    [self pushSetStack];
    FORALL(backData)
    {
        if([self isMarkedRecord: temp] == NO)
        {
            if([myData indexOfObject: temp] == NSNotFound)
            {
                [myData addObject: temp];
            }
        }
    }ENDFORALL;
    UPDATERECCOUNT;
    [theResults reloadData];
    [self addStateString: @"+unmarked"];
    
}

-(IBAction) removeUnmarkedFromSelected: (id) Sender;
{
    NSMutableArray *found = [[NSMutableArray alloc] init];
    FORALL(myData)
    {
        if([self isMarkedRecord: temp] == YES)
        {
            [found addObject: temp];
        }
    }ENDFORALL;
    if([found count])
    {
        [self pushSetStack];
        [myData removeAllObjects];
        [myData addObjectsFromArray: found];
        UPDATERECCOUNT;
        [theResults reloadData];
    }
    [found release];
    [self setStateString: @"-unmarked"];
    
}
-(IBAction) removeMarkedFromSelected: (id) Sender;
{
    NSMutableArray *found = [[NSMutableArray alloc] init];
    FORALL(myData)
    {
        if([self isMarkedRecord: temp] == NO)
        {
            [found addObject: temp];
        }
    }ENDFORALL;
    if([found count])
    {
        [self pushSetStack];
        [myData removeAllObjects];
        [myData addObjectsFromArray: found];
        UPDATERECCOUNT;
        [theResults reloadData];
    }
    [found release];
    [self addStateString: @"-marked"];
    
}


-(IBAction) selectUnmarked: (id) Sender
{
    int i, n;
    NSMutableArray *fd = [[NSMutableArray alloc] init];
    
    n = [backData count];
    for(i = 0; i < n; i++)
    {
        if([self isMarkedRecord: [backData objectAtIndex: i]] == NO)
            [fd addObject: [backData objectAtIndex: i]];
    }
    if([fd count])
    {
        [self pushSetStack];
        [myData removeAllObjects];
        [myData addObjectsFromArray: fd];
        UPDATERECCOUNT;
        [theResults reloadData];
        [self setStateString: @"unmarked"];
    }
    else
    {
        NSWARNING(@"No unarked records");
    }
    [fd release];
    
}
/*-----------         Named Selections ---------------*/

-(IBAction) loadNamedSelection: (id) Sender
{
    NSString *selectedSelection;
    
    selectedSelection = [Sender title];
    if([[namedSelDict objectForKey: selectedSelection] count])
    {
        [self pushSetStack];
        [myData removeAllObjects];
        [myData addObjectsFromArray: [namedSelDict objectForKey: selectedSelection]];
        UPDATERECCOUNT;
        [theResults reloadData];
        [self setStateString: selectedSelection];
    }
    
}


-(void) backupNamedSel
{
    NSArray *nl;
    NSArray *nd;
    
    nl = [namedSelDict allKeys];
    FORALL(nl)
    {
        
        nd = [self arrayFromSubset: [namedSelDict objectForKey: temp]];
        [namedSelDict setObject: nd forKey: temp];
        
    }
    ENDFORALL;
}
-(void) restoreNamedSel
{
    NSArray *nl;
    NSArray *nd;
    
    nl = [namedSelDict allKeys];
    FORALL(nl)
    {
        
        nd = [self subsetFromArray: [namedSelDict objectForKey: temp]];
        [namedSelDict setObject: nd forKey: temp];
        
    }
    ENDFORALL;
}


-(IBAction) clearNamedSelMenu: (id) Sender
{
    
    //delete the menu options
    if([namedSelDict count] == 0) return;
    if(Sender == nil)
    {
        if(NSYESNOQUESTION(@"The operation you have picked will probably create unreliable named sets. Delete all named sets? (I recommend clicking \"YES\")") == NO)
        {
            [self backupNamedSel];
            savedNamedSel = YES;
            return;
        }
    }
    else
        if(NSYESNOQUESTION(@"Delete all of this file's named sets?") ==NO) return;
    savedNamedSel = NO;
    [namedSelDict removeAllObjects];
    [self rebuildAutoSetMenu];
    UPDATERECCOUNT;
}



-(void) renewNamedSelMenu
{
    int i,nm;
    NSMenu *namedSelMenu;
    NSMutableArray *theKeys;
    //delete the menu options
    // myMen = [[NSApp mainMenu] itemWithTag: NAMEDSELMENU] ;
    namedSelMenu = [[[NSApp delegate] namedSelectionMenu] submenu];
    nm = [namedSelMenu numberOfItems];
    for(i = nm-1; i >= NAMEDSELBASE; i--)
    {
	[namedSelMenu removeItemAtIndex: i];
    }
    theKeys = [NSMutableArray arrayWithArray: [namedSelDict allKeys]];
    [theKeys sortUsingFunction: nsStringComp context: nil];
    FORALL(theKeys)
    {
	NSMenuItem *mm;
	
	mm = [[NSMenuItem alloc] init];
	[mm setTitle: temp];
	[mm setAction: @selector(loadNamedSelection:)];
	[namedSelMenu addItem: mm];
    }ENDFORALL;
    
}

-(void) namedSelDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    NSMutableArray *mm;
    
    if(returnCode)
    {
        if([namedSelDict objectForKey: [namedSelField stringValue]] != nil)
        {
            NSWARNING(@"Name already exists; use unique name");
            return;
        }
        mm = [[NSMutableArray alloc] init];
        [mm addObjectsFromArray: myData];
        [namedSelDict setObject: mm forKey: [namedSelField stringValue]];
        [mm release];
        [self rebuildAutoSetMenu];
        //[self renewNamedSelMenu];
        [self setStateString: [namedSelField stringValue]];
        [self updateOnlyRecCount];
        MAKEDIRTY;
    }
    
}

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

-(IBAction) okNamedSelection: (id) Sender
{
    if([self validSetName: [namedSelField stringValue]] == NO)
    {
        NSWARNING(@"You must use a unique set name");
        return;
    }
    [namedSelSheet orderOut: Sender];
    [NSApp endSheet: namedSelSheet returnCode: 1];
    
}
-(IBAction) addNamedSelection: (id) Sender
{
    NSWindow *who;
    [namedSelField setStringValue: @""];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    [NSApp beginSheet: namedSelSheet
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(namedSelDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}

- (void) windowDidBecomeKey:(NSNotification *)aNotification
{
    //[self renewNamedSelMenu];
    [self rebuildAutoSetMenu];
    [self rebuildSummReportMenu];
    [self resetCaseSensitive];
    /*
     if(exactCodeSetFlag)
     {
         [[[NSApp delegate] exactRsltCodeSetMenuItem] setState: NSOnState];
     }
     else
     {
         [[[NSApp delegate] exactRsltCodeSetMenuItem] setState: NSOffState];
     }
     */
    if(gWorkBench != nil) 
    {
        if([gWorkBench reanalysisMode] == YES)
        {
            [[[NSApp delegate] reanalysisMenu] setState: NSOnState];
        }
        else
        {
            [[[NSApp delegate] reanalysisMenu] setState: NSOffState];
        }
    }
    [self displaySelData];
    
    
}

/* ---------- Set Math with Named Sets ----------- */
-(void) setMathDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    NSArray *mm;
    NSString *sn;
    int opType, i,n;
    NSMutableArray *final = [[NSMutableArray alloc] init];
    
    if(returnCode)
    {
        //get subset
        sn = [[setMathSetMenu selectedItem] title];
        mm = [self getSetWithName: sn];
        opType = [[setMathOpMenu selectedItem] tag];
        
        //this block is for autohistory
        if([self isAutoSet: sn])
        {
            NSMutableDictionary *ahd = [NSMutableDictionary dictionary];
            [ahd setObject: @"set" forKey: @"stepType"];
            [ahd setObject: [NSNumber numberWithInt: opType]
                    forKey: @"op"];
            [ahd setObject: [[sn copy] autorelease]
                    forKey: @"obj"];
            [autoHistory addObject: ahd];
        }
        
        
        switch (opType)
        {
            case 1: //intersect with
                FORALL(mm)
            {
                    if([myData indexOfObject: temp] == NSNotFound)
                    {
                    }
                    else
                        [final addObject: temp];
            }
                ENDFORALL;
                [myData removeAllObjects];
                [myData addObjectsFromArray: final];
                break;
                
            case 2: //union
                FORALL(mm)
            {
                    if([myData indexOfObject: temp] == NSNotFound)
                    {
                        [final addObject: temp];
                    }
            }
                ENDFORALL;
                [myData addObjectsFromArray: final];
                break;
                
            case 3: //Don't intersect with
                n = [mm count];
                for(i = 0; i < n; i++)
                {
                    [myData removeObject: [mm objectAtIndex: i]];
                }
                    break;
                
            case 4: //not in union with
                n = [backData count];
                for(i = 0; i < n; i++)
                {
                    if([myData containsObject: [backData objectAtIndex: i]] == YES ||
                       [mm containsObject: [backData objectAtIndex: i]] == YES)
                    {
                    }
                    else
                    {
                        [final addObject: [backData objectAtIndex: i]];
                    }
                }
                    [myData removeAllObjects];
                [myData addObjectsFromArray: final];
                break;
                
            case 5: // XOR
                n = [mm count];
                for(i = 0; i < n ; i++)
                {
                    if([myData containsObject: [mm objectAtIndex: i]] == YES)
                    {
                        [myData removeObject: [mm objectAtIndex: i]];
                    }
                    else
                    {
                        [myData addObject: [mm objectAtIndex: i]];
                    }
                }
                    break;
                
        };
        [final release];
        UPDATERECCOUNT;
        [theResults reloadData];
        [self addStateString: [NSString stringWithFormat: @"%@ w/ %@", 
            [[setMathOpMenu selectedItem] title],
            [[setMathSetMenu selectedItem] title]]];
    }
    
}

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

-(IBAction) okSetMath: (id) Sender
{
    [self pushSetStack];
    [setMathSheet orderOut: Sender];
    [NSApp endSheet: setMathSheet returnCode: 1];
    
}
-(IBAction) doSetMath: (id) Sender
{
    //Need to rebuild the named selections menu
    //are there any?
    NSMutableArray *namedSels;
    NSWindow *who;
    
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    
    if([[self allSetNames] count] == 0) 
    {
        NSWARNING(@"No named selections");
        return;
    }
    [setMathOpMenu selectItemAtIndex: 0];
    [setMathSetMenu removeAllItems];
    namedSels = [NSMutableArray arrayWithArray: [self allSetNames]];
    [namedSels sortUsingFunction: nsStringComp context: nil];
    FORALL(namedSels)
    {
        [setMathSetMenu addItemWithTitle: temp];
    }
    ENDFORALL;
    
    [namedSelField setStringValue: @""];
    [NSApp beginSheet: setMathSheet
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(setMathDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}

/* find the record in the original file */
-(IBAction) fetchRow: (id) Sender
{
    int row, b, e;
    NSMutableDictionary *aRec;
    MWFile *who;
    
    if(!gWorkBench)
    {
        NSWARNING(@"Project file has closed, cannot locate source files");
        return;
    }
    
    //get the key numbers
    row = [theResults selectedRow];
    //make a range
    aRec = [myData objectAtIndex: row];
    b = [[aRec objectForKey: @"_begin_loc"] intValue];
    e = [[aRec objectForKey: @"_end_loc"] intValue];
    who = [aRec objectForKey: @"_doc"];
    //call the window
    if([gWorkBench mwFileExists: who] == NO) 
    {
        NSWARNING(@"Cannot find the source file.");
    }
    else
    {
        [who closeFakeFile];
        [gWorkBench openMWFile: who type: SOURCETYPE];
        [[who filePointer] selectAndScrollRange: NSMakeRange(b, e-b) andMoveForward: YES];
    }
    
}

-(IBAction) refreshResults: (id) Sender
{
    int selRow;
    int tsim;
    NSMutableString *ols = [[NSMutableString alloc] init];
    //get the data
    FORALL(fileList)
    {
	if(FILEOPEN(temp) == NO)
	{
	    NSWARNING(@"Cannot find one of the original source files.");
	    return;
	}
    }
    ENDFORALL;
    
    //if(dataSource)
    {
        int nnn;
        
        [ols setString: [limitField stringValue]];
        [self clearNamedSelMenu: nil];
	tce = [[TAMSCharEngine alloc] initWithArrayAndStart: fileList];
	selRow = [theResults selectedRow];
	[self clearTable]; //do before the data goes away
                           //clean my own lists
        
	[self initVariables];
        [self zeroSetStack];
	//[myData removeAllObjects];
        [myData autorelease];
        myData = [[NSMutableArray alloc] init];
        //	[backData removeAllObjects];
        [backData autorelease];
        backData = [[NSMutableArray alloc] init];
	[univList removeAllObjects];
	[repList removeAllObjects];
        [lastRepList removeAllObjects];
        [innerRepList removeAllObjects];
	[blockList removeAllObjects];
	[colList removeAllObjects];
	[markedList removeAllObjects];
	[univVault removeAllObjects];
	[repVault removeAllObjects];
	[normVault removeAllObjects];
	[sortStack removeAllObjects];
        [repCont removeAllObjects];
        [fieldMap removeAllObjects];
        [mediaDict removeAllObjects];
        [self clearComments];
	[self buildCoderList];
	if([gPrefBoss countSectionsValue]) 
	    SETGLOBAL(@"emptysectionflag", 1);
	else
	    SETGLOBAL(@"emptysectionflag",0);
        tsim = [self global: @"simpleflag"];
        
        SETGLOBAL(@"rawflag", [self global: @"raw1stflag"]);
        SETGLOBAL(@"simpleflag", [self global: @"simple1stflag"]);
        tsim = [self global: @"simpleflag"];
        
        SETGLOBAL(@"exactflag", [self global: @"exact1stflag"]);
        SETGLOBAL(@"emptyflag", [self global: @"empty1stflag"]);
        SETGLOBAL(@"sectionsearch", [self global: @"section1stflag"]);
        
	[[NSNotificationCenter defaultCenter] addObserver: self 
                                                 selector: @selector(handleEachEOF:)
                                                     name: @"TAMSFileHasEnded"
                                                   object: nil];
        tsim = [self global: @"simpleflag"];
        //get the search
        /* all of this is now handlied when the object is init'd*/
	//[limitString setString: [dataSource theLimitString]];
	//clearSearchList();
	//addArrayToSearchList(fileList);
	//startSearch();
        
	if([limitString length])
	{
	    [self setGlobal: @"limitflag" to: 1];
	    [tce handlelimit: limitString];
            tsim = [self global: @"simpleflag"];
	    [self doTamsSearch: limitString];
	    [tce ctCloseAllOpenRuns];
	    if([[tce ctRunVault] count])
		[self handleEnd: NO flush: NO];
	}
	else
	{
	    [self setGlobal: @"limitflag" to: 0];
            tsim = [self global: @"simpleflag"];
	    [self doTamsSearch: nil];
	    [tce ctCloseAllOpenRuns];
	    if([[tce ctRunVault] count])
		[self handleEnd: NO flush: NO];
	}
	//gCurrentTAMS = nil;
        
        //do the search
	//do the tables
	//reload 
	[self setupTables];
	[myWindow makeKeyAndOrderFront: self];
	[backData removeAllObjects];
	[backData addObjectsFromArray: myData];
        [self setOriginalStateString];
        nnn = [[self autoHistory] count];
        if(nnn > 0)
        {
            [self doAutoSet: nil];
            [limitField setStringValue: ols];
        }
	UPDATERECCOUNT;
        
	[theResults reloadData];
        [ols release];
	[[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name: @"TAMSFileHasEnded" object: nil];
        
	if([myData count] > 0) 
	{
	    [myWindow setDocumentEdited: YES];
	    [self updateChangeCount: NSChangeDone];
	}
	if([theResults numberOfRows] > selRow && [theResults numberOfRows] > 0)
	    [theResults selectRow: selRow byExtendingSelection: NO];
	[dirtySourceFlag setState: NSOffState];
        if(savedNamedSel) [self restoreNamedSel];
        [tce release];
        
    }
    
}

-(void) clearTable
{
    NSArray *tc = [theResults tableColumns];
    NSTableColumn *t;
    NSEnumerator *ten;
    
    ten = [tc objectEnumerator];
    while(t = [ten nextObject])
	[theResults removeTableColumn: t];
}

-(void) setupTables
{
    NSTableColumn *t;
    NSEnumerator *men;
    NSString *ss;
    
    //delete the existing columns
    //create the right number of columns with the right headers
    //send a refresh
    
    /*
     FORALL(tc)
     {
         [theResults removeTableColumn: temp];
     }
     ENDFORALL;
     */
    //create new ones
    if([myData count] == 0) return;
    //make the count stuff here
    t = [[NSTableColumn alloc] initWithIdentifier: @"#"];
    [t setWidth: COLWIDTH/2.0];
    [theResults addTableColumn: t];
    [[t headerCell] setStringValue: @"#"];
    //    md = [myData objectAtIndex: 0];
    men = [colList objectEnumerator];
    while(ss = [men nextObject])
    {
	//make column
        if([self isBlocked: ss]) continue;
        t = [[NSTableColumn alloc] initWithIdentifier: ss];
	[t setWidth: COLWIDTH];
        [theResults addTableColumn: t];
        [[t headerCell] setStringValue: ss];
	
    }
    //    [theResults setTarget: self];
    
    //    [theResults setAction: @selector(displaySelData)];
    [theResults setAllowsColumnReordering: YES];
//    [theResults setAutosizesAllColumnsToFit: YES];
    builtTable = YES;
	[theResults reloadData];
//	[theResults setAutosizesAllColumnsToFit: NO];
    
}


- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
	if(myData == nil || builtTable == NO){
		NSLog(@"pop\'ng table before init\nb");
		return 0;
		}
    return [myData count];
}
- (id)tableView:(NSTableView *)aTableView
    objectValueForTableColumn:(NSTableColumn *)aTableColumn
            row:(int)rowIndex
{
    NSMutableString *numStr;
    NSString *ss = [aTableColumn identifier];
    NSDictionary *dd;
    if([ss isEqualToString: @"#"] == YES)
    {
	numStr = [[NSMutableString alloc] init];
	[numStr setString: [[NSNumber numberWithInt: rowIndex + 1] stringValue]];
	if([self isMarked: rowIndex] == YES)
	    [numStr appendString: @"+"];
	[numStr autorelease];
	return numStr;
    }
    else if([ss isEqualToString: @"_doc"] == YES)
    {
 	dd =[myData objectAtIndex: rowIndex];
	return [(MWFile *)[dd objectForKey: @"_doc"] name];
        
    }
    else
    {
        dd = [myData objectAtIndex: rowIndex];
        return [dd objectForKey: ss];
    }
}

-(void) setDataSource: (NSString *) theData{}

-(BOOL)tableView: (NSTableView *) aTable shouldEditTableColumn: (NSTableColumn *) aCol row: (unsigned) arow
{
    return NO;
}
- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
{
    [self displaySelData];
}
- (void)tableView:(NSTableView*)tableView didClickTableColumn:(NSTableColumn *)tableColumn
{
    [self displaySelData];
}

-(void) browseFieldDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    
    if(returnCode)
    {
        [browseField setString: [browseFieldMenu titleOfSelectedItem]];
        [self displaySelData];
    }
    
}

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

-(IBAction) okBrowseField: (id) Sender
{
    [browseFieldSheet orderOut: Sender];
    [NSApp endSheet: browseFieldSheet returnCode: 1];
    
}
-(IBAction) doBrowseField: (id) Sender
{
    NSWindow *who;
    
    NSMutableArray *cols=[NSMutableArray array];
    NSArray *currCols;
    
    currCols = [self tableColumns];
    FORALL(currCols)
    {
        [cols addObject: [temp identifier]];
    }
    ENDFORALL;
    [browseFieldMenu removeAllItems];
    [browseFieldMenu addItemsWithTitles: cols];
    [browseFieldMenu selectItemWithTitle: browseField];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    
    [NSApp beginSheet: browseFieldSheet
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(browseFieldDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}

-(void) displaySelData
{
    [self displaySelData: [theResults selectedRow]];
}

-(void) displaySelData: (int) row
{
    NSString *ss;
    NSMutableString *s2, *s3;
    //get the selected row
    //get the appropriate data
    if([myData count] == 0)
    {
        [thisCell setString: @""];
        
        return;
    }
    
    if([myData count] - 1 < row) row = [myData count] - 1;
    if(row >= 0)
    {
        if([browseField isEqualToString: @"_doc"])
            ss = [[[myData objectAtIndex: row] objectForKey: browseField] name];
        else
            ss = [[myData objectAtIndex: row] objectForKey: browseField];
        
        //set it to the textview
        s2 = [[NSMutableString alloc] init];
        s3 = [[NSMutableString alloc] init];
        [s2 setString: ss];
        [s2 replaceOccurrencesOfString: @"\\n" withString: @"\n"
                               options: NSLiteralSearch range: NSMakeRange(0, [s2 length])];
        [s2 replaceOccurrencesOfString: @"\\t" withString: @"\t"
                               options: NSLiteralSearch range: NSMakeRange(0, [s2 length])];
        [s2 replaceOccurrencesOfString: @"\\r" withString: @"\r"
                               options: NSLiteralSearch range: NSMakeRange(0, [s2 length])];
        if(stripTags)
        {
            MWFakeFile *mf;
            TAMSCharEngine *tx;
            ctQChar *qq;
            qq = [[ctQChar alloc] init];
            
            
            mf = [[MWFakeFile alloc] initWithString: s2];
            tx = [[TAMSCharEngine alloc] initWithFile: mf];
            [tx setAllowTab: 1];
            [tx setNoPar: 0];
            [tx startSearch];
            while([tx scanNext: qq withWarnings: NO] != ENDOFFILE)
                //while([tx readnext: qq] != EOF)
            {
                if([qq tokentype] == CHAR)
                {
                    [s3 appendString: [qq buff]];
                }
            }
            [tx release];
            [qq release];
            [mf release];
            
        }
        else
            [s3 setString: s2];
        [s3 replaceOccurrencesOfString: @"\\n" withString: @"\n"
                               options: NSLiteralSearch range: NSMakeRange(0, [s3 length])];
        [s3 replaceOccurrencesOfString: @"\\t" withString: @"\t"
                               options: NSLiteralSearch range: NSMakeRange(0, [s3 length])];
        [s3 replaceOccurrencesOfString: @"\\r" withString: @"\r"
                               options: NSLiteralSearch range: NSMakeRange(0, [s3 length])];
        
        if([gPrefBoss TAScanForLN] && [[[myData objectAtIndex: row] objectForKey: @"_line_number"] intValue]
           && [browseField isEqualToString: @"_data"])
        {
            [thisCell setString: [NSString stringWithFormat: @"%d\t%@", 
                [[[myData objectAtIndex: row] objectForKey: @"_line_number"] intValue],
                s3]];
        }
        else
        {
            [thisCell setString: s3];
        }
        [s2 release];
        [s3 release];
        /*put colorize stuff here */
        //if([self global: @"nonregexcharflag"] || [self global: @"regexcharflag"]) return;
        if([gPrefBoss autoColorValue])
            [self doColorize: nil];
        
    }
}

-(IBAction) copyWithoutTags: (id) sender
{
    ctQChar *q;
    NSString *oText;
    NSMutableString *nText;
    NSRange r;
    MWFakeFile *ff;
    int ch;
    BOOL a;
    
    r = [thisCell selectedRange];
    if(r.length == 0) return;
    oText = [[thisCell 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) doColorize: (id) sender
{
    NSTextStorage *ts = [thisCell textStorage];
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    ctQChar *q;
    MWFile *mf;
    
    if(!gWorkBench) return;
    mf = [[MWFakeFile alloc] initWithString: [thisCell string]];
    [tc addFileToSearchList: mf];
    [tc startSearch];
    
    q = [[ctQChar alloc] init];
    
    [thisCell setTextColor: [NSColor blackColor]];
    [ts beginEditing];
    while([tc scanNext: q withWarnings: NO] != ENDOFFILE)
    {
        if([q tokentype] == TOKEN || [q tokentype] == ENDTOKEN)
        {
            /*
             [ts addAttribute:
                 NSForegroundColorAttributeName 
                        value:  [gWorkBench colorForCode: [q buff]]
                        range: [q range]];
             */
            [thisCell 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]];
             */
            [thisCell setTextColor: [gPrefBoss metaColor] range: [q range]];
        }
    }
    [ts endEditing];
    
    [tc release];
    [mf release];
    [q release];
}

- (BOOL)validateMenuItem:(NSMenuItem *)anItem
{
    BOOL ans = [super validateMenuItem: anItem];
    
    if([[anItem title] isEqualToString: @"Save"] == YES)
    {
	return YES;
    }
    if([[anItem title] isEqualToString: @"Save As..."] == YES)
    {
	return YES;
    }
    
    return ans;
    
}
- (void) moveForward
{
    [myWindow makeKeyAndOrderFront: self];
}

-(IBAction) moveWorkBenchForward: (id) sender
{
    [gWorkBench front];
    
}
-(IBAction) showCodeBrowser: (id) Sender
{
    [gWorkBench showCodeBrowser: self];
}
-(NSString *)getTitle
{
    return [myWindow title];
}
-(void) setMWFile: (MWFile *) who{ myMWFID = who;}
-(MWFile *) getMWFile {return myMWFID;}
-(id) getGWorkBench: (id) who {return gWorkBench;}
-(void) setGWorkBench: (id) who {gWorkBench = who;}
- (void)document:(NSDocument *)doc didSave:(BOOL)didSave contextInfo:(void *)contextInfo
{
    MWFile *mw;
    mw = [self getMWFile];
    if(didSave == YES)
    {
	[myWindow setDocumentEdited: NO];
	[self updateChangeCount: NSChangeCleared];
        [mw setOpenFile: self]; //reset the path
        [mw setHasFile: YES];
        if(gWorkBench != nil) [gWorkBench setDirty];
    }
    
}
-(IBAction) saveDocument: (id) Sender
{
    
    
    MWFile *mw;
    NSString *path;
    NSLog(@"in saveDocument--%@\n", [self fileName]);
    //[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
{
    
    MWFile *mw;
    [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];
     }
     */
}

-(void) setStateString: (NSString *) what
{
    [limitField setStringValue: what];
}

-(void) addStateString: (NSString *) what
{
    NSString *old;
    old = [limitField stringValue];
    [limitField setStringValue: [NSString stringWithFormat: @"%@; %@", old, what]];
}
-(void) setOriginalStateString
{
    if([self global: @"regexcharflag"] || [self global: @"nonregexcharflag"])
    {
        [limitField setStringValue: [NSString stringWithFormat: @"Find: %@",limitString]];
        return;
        
    } 
    
    if([self global: @"sectionsearch"])
    {
        if([limitString length]) 
        {
            [limitField setStringValue: [NSString stringWithFormat: @"Section: %@",limitString]];
        }
        else
            [limitField setStringValue: @"Section: unlimited"];
        
        return;
        
    } 
    else if(limitString)
    {
        if([limitString length]) 
        {
            [limitField setStringValue: limitString];
            return;
        }
    }
    
    [limitField setStringValue: @"Unlimited"];
}

-(IBAction) doSetStripTags: (id) sender
{
    NSMenuItem *tagMenu;
    tagMenu = [[NSApp delegate] toggleShowTagsMenuItem];
    if([self global: @"rawflag"] == NO) return;
    if(stripTags)
    {
        stripTags = NO;
        [tagMenu setState: NSOffState];
    }
    else
    {
        stripTags = YES;
        [tagMenu setState: NSOnState];
    }
    [self displaySelData];
}

-(IBAction) doCollapseDown:(id) Sender
{
    //loop through
    NSString * compareValue;
    NSString *recKey;
    id compareRec;
    NSALLOC(NSMutableArray, tempStorage); 
    int fflag;
    if([theResults selectedColumn] < 0) 
    {
        NSWARNING(@"Need to select a column");
        [tempStorage release];
        return;
    }
    
    recKey = SELECTEDCOLUMNID(theResults);
    if(recKey == nil) return;
    fflag = 1;
    FORALL(myData)
    {
        if(fflag == 1)
        {
            compareValue = [temp objectForKey: recKey];
            compareRec = temp;
            fflag = 2;
        }
        else if(fflag == 2)
        {
            if([[temp objectForKey: recKey] isEqualToString: compareValue] == YES)
            {
                compareRec = temp;
            }
            else
            {
                [tempStorage addObject: compareRec];
                compareRec = temp;
                compareValue = [temp objectForKey: recKey];
            }
        }
    }ENDFORALL;
    [self pushSetStack];
    
    [tempStorage addObject: compareRec];
    [myData removeAllObjects];
    [myData addObjectsFromArray: tempStorage];
    [tempStorage release];
    {
        NSString *sss = [NSString stringWithFormat: @"cllpse dwn: %@", recKey];
        
        [self addStateString: sss];
    }
    
    UPDATERECCOUNT;
    [theResults reloadData];
    
    
    //get the compare value if 1st time or compare with value if it's the second+
    // is it different, save the new value
    
    
}
-(IBAction) doCollapseUp:(id) Sender
{
    //loop through
    NSString * compareValue;
    NSString *recKey;
    id compareRec;
    NSALLOC(NSMutableArray, tempStorage); 
    int fflag;
    
    if([theResults selectedColumn] < 0) 
    {
        NSWARNING(@"Need to select a column");
        [tempStorage release];
        return;
    }
    
    
    recKey = SELECTEDCOLUMNID(theResults);
    fflag = 1;
    FORALL(myData)
    {
        if(fflag == 1)
        {
            compareValue = [temp objectForKey: recKey];
            compareRec = temp;
            fflag = 2;
        }
        else if(fflag == 2)
        {
            if([[temp objectForKey: recKey] isEqualToString: compareValue] == YES)
            {
                ; //do nothing since we want the topmost one to represent everyone
            }
            else
            {
                [tempStorage addObject: compareRec];
                compareRec = temp;
                compareValue = [temp objectForKey: recKey];
            }
        }
    }ENDFORALL;
    [self pushSetStack];
    
    [tempStorage addObject: compareRec];
    [myData removeAllObjects];
    [myData addObjectsFromArray: tempStorage];
    [tempStorage release];
    {
        NSString *sss = [NSString stringWithFormat: @"cllpse up: %@", recKey];
        
        [self addStateString: sss];
    }
    UPDATERECCOUNT;
    [theResults reloadData];
    
    
    //get the compare value if 1st time or compare with value if it's the second+
    // is it different, save the new value
    
    
}

/* auto sets routines */

-(IBAction) createAutoSet: (id) sender
{
    [autoSetWatcher runMacroEditor];
}
-(NSMutableDictionary *) autoSets
{
    return autoSets;
}
-(NSWindow *) myWindow
{
    return myWindow;
}
-(BOOL) isInfiniteLoop: (NSDictionary*)who  usingStack: (NSMutableArray *)mystack
{
    NSArray *pgm;
    int i, n;
    pgm = [who objectForKey: @"program"];
    n = [pgm count];
    for(i = 0; i< n; i++)
    {
        NSDictionary *w;
        w = [pgm objectAtIndex: i];
        if([[w objectForKey: @"stepType"] isEqualToString: @"autoset"] == YES)
        {
            if(addUniqueToArray(mystack, [w objectForKey: @"name"]) == NO) return YES;
            if([self isInfiniteLoop: [self autoSetForName:[w objectForKey: @"name"]] usingStack: mystack] == YES)
                return YES;
        }
        if([[w objectForKey: @"stepType"] isEqualToString: @"set"] == YES)
        {
            NSString *setName;
            setName = [w objectForKey: @"obj"];
            if(setName == nil) continue;
            if(addUniqueToArray(mystack, setName) == NO) return YES;
            if([self isInfiniteLoop: [self autoSetForName:setName] usingStack: mystack] == YES)
                return YES;
        }
        
    }
    return NO;
}


-(IBAction) doAutoSet: (id) sender
{
    NSMutableDictionary *who;
    NSMutableArray *ans;
    NSString *title;
    NSMutableArray *oldHist;
    BOOL allFlag;
    allFlag = YES;
    if(sender != nil)
    {
        ans = [self getAutoSetWithName: [sender title]];
        who = [self autoSetForName: [sender title]];
        title = [sender title];
    }
    else
    {
        ans = [self getAutoSetWithName: nil];
        who = [self autoHistoryAsProgram];
        title = [self autoHistoryStart];
        oldHist = [[NSMutableArray alloc] initWithArray: autoHistory];
        [autoHistory removeAllObjects];
    }
    
#ifdef NOSHOWZEROCOUNT
    if([ans count])
#endif
    {
        NSMutableArray *aa = [NSMutableArray array];
        [aa addObject: title];
        if([self isInfiniteLoop: who usingStack: aa])
        {
            if(NSYESNOQUESTION(@"Autoset has a potential infinite loop, continue?") == NO)
                return;
        }
        [self pushSetStack];
        [myData setArray: ans];
        [theResults reloadData];
        if([[who objectForKey: @"start"] isEqualToString: @"Visible"])
        {
            allFlag = NO;
            [self addStateString: [NSString stringWithFormat: @"->%@",title]];
        }
        else
        {
            [self setStateString: title];
        }
        [autoHistoryStart setString: title];
        if(sender != nil && allFlag == YES)
            [autoHistory removeAllObjects];
        else if(sender == nil)
        {
            [autoHistory setArray: oldHist];
            [oldHist release];
        }
        
        UPDATERECCOUNT;
    }
    if([ans count] == 0) NSWARNING(@"No records found");
#ifdef NOSHOWZEROCOUNT
    else
    {        
        NSWARNING(@"No records found");
    }
#endif
}

-(IBAction) removeAllAutoSets: (id) sender
{
    if(NSYESNOQUESTION(@"Delete all of this file's autosets?") ==NO) return;
    [[self autoSets] removeAllObjects];
    [self rebuildAutoSetMenu];
    UPDATERECCOUNT;
}

-(IBAction) doRunSet: (id) sender
{
    [self pushSetStack];
    if([namedSelDict objectForKey: [sender title]] == nil)
    {
        //put the autohistory block here
        //this block is for autohistory
        [self doAutoSet: sender];
        if([self isAutoSet: [sender title]])
        {
            NSMutableDictionary *ahd = [NSMutableDictionary dictionary];
            [ahd setObject: @"autoset" forKey: @"stepType"];
            [ahd setObject: [[[sender title] copy] autorelease] forKey: @"name"];
            [autoHistory addObject: ahd];
        }
        
    }
    else
        [self loadNamedSelection: sender];
}

-(void) rebuildAutoSetMenu
{
    int i, n, m;
    NSMenu *asmn;
    NSMutableArray *w1, *w2;
    
    asmn = [[[NSApp delegate] autoSetMenu] submenu];
    m = [asmn numberOfItems];
    
    if(m > AUTOSETBASE)
        for(i = AUTOSETBASE; i < m; i++)
        {
            [asmn removeItemAtIndex: AUTOSETBASE];
        }
            /*
             if(gWorkBench != nil)
             {
                 who = [gWorkBench allAutoSetNames];
                 if(m = [who count])
                     for(i = 0; i<m; i++)
                     {
                         NSMenuItem *mm;
                         
                         mm = [[NSMenuItem alloc] init];
                         [mm setTitle: [who objectAtIndex: i]];
                         [mm setAction: @selector(doAutoSet:)];
                         [asmn addItem: mm];
                         
                     }
             }
             
             who = [[self autoSets] allKeys];
             */
            w1 = [NSMutableArray arrayWithArray: [namedSelDict allKeys]];
    w2 = [NSMutableArray arrayWithArray: [self allAutoSetNames]];
    
    [w1 sortUsingFunction: nsStringComp  context: nil];
    [w2 sortUsingFunction: nsStringComp  context: nil];
    
    //who = [self allSetNames];
    if((m = [w1 count]) > 0)
    {
        for(i=0; i< m; i++)
        {
            [asmn addItemWithTitle: [w1 objectAtIndex: i]
                            action: @selector(doRunSet:)
                     keyEquivalent: @""];
        }
    }
    n = [w2 count];
    if(m > 0 && n > 0)
        [asmn addItem: [NSMenuItem separatorItem]];
    
    if(n > 0)
    {
        for(i=0; i< n; i++)
        {
            [asmn addItemWithTitle: [w2 objectAtIndex: i]
                            action: @selector(doRunSet:)
                     keyEquivalent: @""];
        }
    }
    
}



-(NSArray *) allSetNames
{
    NSMutableArray *aa;
    
    aa = [NSMutableArray array];
    [aa addObjectsFromArray: [self allAutoSetNames]];
    [aa addObjectsFromArray: [namedSelDict allKeys]];
    return aa;
    
}

-(NSArray *) allAutoSetNames
{
    NSMutableArray *aa;
    
    aa = [NSMutableArray array];
    if(gWorkBench != nil)
    {
        [aa addObjectsFromArray: [gWorkBench allAutoSetNames]];
    }
    [aa addObjectsFromArray: [autoSets allKeys]];
    return aa;
}

-(BOOL) validSetName: (NSString *) who
{
    if(who == nil) return NO;
    if([who isEqualToString: @""] == YES) return NO;
    if([self validAutoSetName: who] && [namedSelDict objectForKey: who] == nil)
        return YES;
    else
        return NO;
}
-(NSMutableArray *) autoHistory{return autoHistory;}

-(NSMutableString *) autoHistoryStart {return autoHistoryStart;}

-(BOOL) isAutoSet: (NSString *) who
{
    if([self autoSetForName: who] != nil) return YES;
    if(gWorkBench != nil)
        if([gWorkBench autoSetForName: who] != nil) return YES;
    return NO;
}
-(BOOL) validAutoSetName: (NSString *) who
{
    if(who == nil) return NO;
    if([who isEqualToString: @""] == YES) return NO;
    
    if([self autoSetForName: who] == nil && [gWorkBench autoSetForName: who] == nil &&
       [who isEqualToString: @"All"] == NO && [who isEqualToString: @"Visible"] == NO)
        return YES;
    else
        return NO;
}
-(void) addAutoSet: (NSMutableDictionary *) what withName: (NSString *) who
{
    if([[what objectForKey: @"global"] intValue] == 0)
    {
        [autoSets setObject: what forKey: who];
        UPDATERECCOUNT;
    }
    else if (gWorkBench != nil)
    {[gWorkBench addAutoSet: what withName: who];}
    else NSWARNING(@"Cannot save macro: not connected to a project");
}
-(NSMutableDictionary *) myAutoSetForName: (NSString *) who
{
    return [autoSets objectForKey: who];
}

-(NSMutableDictionary *) autoSetForName: (NSString *) who
{
    NSMutableDictionary *ans;
    if(gWorkBench != nil) 
        ans = [gWorkBench autoSetForName: who];
    else
        ans = nil;
    if(ans == nil)
        return [autoSets objectForKey: who];
    else
        return ans;
}
-(void) removeAutoSetForName: (NSString *) who
{
    if([self myAutoSetForName: who] != nil)
    {
        [autoSets removeObjectForKey: who];
        UPDATERECCOUNT;
    }
    else
        if(gWorkBench != nil) [gWorkBench removeAutoSetForName: who];
}

-(NSArray *) columns
{
    return colList;
}

-(IBAction) doToggleReanalysisMode: (id) sender
{
    if(gWorkBench)
    {
        [gWorkBench doToggleReanalysisMode: sender];
    }
}
/*-----------------------------------------------*/
/* summary data routines */
-(NSMutableArray *) hotData
{return myData;}

-(IBAction) runSummaryReport: (id) sender
{
    [summWatcher doSummary];
}

-(void) codeLevelDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    
    if(returnCode)
    {
        aCodeLevel = [codeLevelField intValue];
    }
    
}

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

-(IBAction) okCodeLevel: (id) Sender
{
    [codeLevelPane orderOut: Sender];
    [NSApp endSheet: codeLevelPane returnCode: 1];
    
}
-(IBAction) doCodeLevel: (id) Sender
{
    NSWindow *who;
    [codeLevelField setIntValue: aCodeLevel];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    [NSApp beginSheet: codeLevelPane
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(codeLevelDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}
-(BOOL) isMySummReport: (NSString *) who
{
    NSArray *a;
    a = [self mySummReports];
    FORALL(a)
    {
        if([temp isEqualToString: who]) return YES;
    }
    ENDFORALL;
    return NO;
}

-(int) reportScope: (NSString *) who
{
    if([self isMySummReport: who]) return 1;
    if([self isSummReport: who]) return 2;
    return 0;
}

-(NSMutableString *) dateFormat{return dfString;}
-(BOOL) isSummReport: (NSString *) who
{
    NSArray *a;
    a = [self allSummReports];
    FORALL(a)
    {
        if([temp isEqualToString: who]) return YES;
    }
    ENDFORALL;
    return NO;
}
-(void) addSummReport:(NSString *) who report: (NSDictionary *) r global: (BOOL) g
{
    if(g ==NO)
    {
        [summReports setObject:r forKey: who];
        [self rebuildSummReportMenu];
        MAKEDIRTY;
    }
    else
    {
        [gWorkBench addSummReport: who report: r global: g];
        [self rebuildSummReportMenu];
    }
}
-(void) delSummReport:(NSString *) who
{
    if([self isMySummReport: who])
    {
        [summReports removeObjectForKey: who];
        [self rebuildSummReportMenu];
        MAKEDIRTY;
    }
    else
    {
        [gWorkBench delSummReport: who];
    }
}

-(NSArray *) mySummReports
{
    return [summReports allKeys];
}
-(NSArray *) allSummReports
{
    NSMutableArray *ar = [NSMutableArray array];
    
    [ar addObjectsFromArray: [self mySummReports]];
    [ar addObjectsFromArray: [gWorkBench mySummReports]];
    return ar;
}

-(NSDictionary *) summReport: (NSString *) who
{
    NSDictionary *ans;
    ans = [summReports objectForKey: who];
    if(ans == nil) return [gWorkBench summReport: who];
    else return ans;
}
-(void) doRunSummRep: (id) sender
{
    NSDictionary *r;
    r = [self summReport: [sender title]];
    if(r != nil)
        [summWatcher runSummReport: r];
}
-(void) rebuildSummReportMenu
{
    int i, n, m;
    NSMenu *asmn;
    NSMutableArray *w1, *w2;
    
    asmn = [[[NSApp delegate] summReportMenu] submenu];
    m = [asmn numberOfItems];
    
    if(m > SUMMREPORTBASE)
        for(i = SUMMREPORTBASE; i < m; i++)
        {
            [asmn removeItemAtIndex: SUMMREPORTBASE];
        }
            
            w1 = [NSMutableArray arrayWithArray: [self mySummReports]];
    w2 = [NSMutableArray arrayWithArray: [gWorkBench mySummReports]];
    
    [w1 sortUsingFunction: nsStringComp  context: nil];
    [w2 sortUsingFunction: nsStringComp  context: nil];
    
    //who = [self allSetNames];
    [asmn addItem: [NSMenuItem separatorItem]];
    if((m = [w1 count]) > 0)
    {
        for(i=0; i< m; i++)
        {
            [asmn addItemWithTitle: [w1 objectAtIndex: i]
                            action: @selector(doRunSummRep:)
                     keyEquivalent: @""];
        }
    }
    n = [w2 count];
    if(m > 0 && n > 0)
        [asmn addItem: [NSMenuItem separatorItem]];
    
    if(n > 0)
    {
        for(i=0; i< n; i++)
        {
            [asmn addItemWithTitle: [w2 objectAtIndex: i]
                            action: @selector(doRunSummRep:)
                     keyEquivalent: @""];
        }
    }
    
}
/******** dotGraph rountines ********/
-(NSArray *) tableColumns
{
    return [theResults tableColumns];
}

-(int) fieldType: (NSString *) name
{
    if([self isUniversal: name] == YES) return 1;
    if([self isRepeat: name] == YES) return 2;
    else return 0;
}

-(int) codeLevel
{
    return aCodeLevel;
}
-(IBAction) doDotGraph: (id) sender
{
    [dotGraphWatcher doDotGraph];
}
/******** stack routines ********/
-(NSMutableDictionary *) getStackElem
{
    NSMutableDictionary *stackElem;
    NSString *ss;
    NSMutableArray *myHistory = [[NSMutableArray alloc] init];
    stackElem = [NSMutableDictionary dictionary];
    ss = [limitField stringValue];
    [stackElem setObject: [NSArray arrayWithArray: myData] forKey: @"data"];
    [stackElem setObject: [[ss copy] autorelease] forKey: @"limit"];
    [myHistory addObjectsFromArray: [self autoHistory]];
    [myHistory autorelease];
    [stackElem setObject: myHistory forKey: @"history"];
    return stackElem;
}

-(void) pushSetStack
{
    NSMutableDictionary *stackElem;
    if([gPrefBoss enableBack] == 0)
    {
        [self zeroSetStack];
        return;
    }
    stackElem = [self getStackElem];
    [setStack addObject: stackElem];
    [fwdSetStack removeAllObjects];
    [fwdButton setEnabled: NO];
    [backButton setEnabled: YES];
    
}
-(IBAction) popSetStack: (id) sender
{
    int nnn;
    if([gPrefBoss enableBack] == 0)
    {
        [self zeroSetStack];
        return;
    }
    nnn = [setStack count];
    if(nnn >0)
    {
        NSDictionary *dd;
        NSString *ss;
        NSArray *ah;
        //first save what we have
        [fwdSetStack addObject: [self getStackElem]];
        [fwdButton setEnabled: YES];
        
        
        //Now pop what we have
        dd = [setStack objectAtIndex: nnn - 1];
        [myData setArray: [dd objectForKey: @"data"]];
        ss = [dd objectForKey: @"limit"];
        [limitField setStringValue: ss];
        ah = [dd objectForKey: @"history"];
        if(ah != nil)
            [autoHistory setArray: ah];
        else
            [autoHistory removeAllObjects];
        [setStack removeLastObject];
        UPDATERECCOUNT;
        [theResults reloadData];
        if([setStack count] == 0) [backButton setEnabled: NO];
    }
    else
        [self zeroSetStack];
}
-(IBAction) popFwdSetStack: (id) sender
{
    if([gPrefBoss enableBack] == 0)
    {
        [self zeroSetStack];
        return;
    }
    if([fwdSetStack count] >0)
    {
        NSDictionary *dd;
        NSString *ss;
        NSArray *ah;
        //first save what we have
        [setStack addObject: [self getStackElem]];
        [backButton setEnabled: YES];
        
        
        //Now pop what we have
        dd = [fwdSetStack lastObject];
        [myData setArray: [dd objectForKey: @"data"]];
        ss = [dd objectForKey: @"limit"];
        [limitField setStringValue: ss];
        ah = [dd objectForKey: @"history"];
        if(ah != nil)
            [autoHistory setArray: ah];
        else
            [autoHistory removeAllObjects];
        [fwdSetStack removeLastObject];
        UPDATERECCOUNT;
        [theResults reloadData];
        if([fwdSetStack count] == 0) [fwdButton setEnabled: NO];
    }
    else
        [self zeroSetStack];
}
-(IBAction) zeroSetStack: (id) sender
{
    [self zeroSetStack];
}
-(void) zeroSetStack
{
    [fwdButton setEnabled: NO];
    [backButton setEnabled: NO];
    [setStack removeAllObjects];
    [fwdSetStack removeAllObjects];
}
-(IBAction) exportData: (id) sender
{
    [exportWatcher doExport];
}
-(IBAction) toggleExactCodeSet: (id) sender
{
    if(exactCodeSetFlag)
    {
        exactCodeSetFlag = NO;
        [sender setState: NSOffState];
    }
    else
    {
        exactCodeSetFlag = YES;
        [sender setState: NSOnState];
    }
}    

-(BOOL) selectDataFrom: (NSArray *) fromArray to: (NSMutableArray *) toArray forCodeSet: (NSString *) who type: (int) tp exact: (BOOL) ex
{
    
    int i,n;
    BOOL test;
    NSArray *codes;
    NSMutableArray *removeList;
    
    codes = [gWorkBench codesInCodeSet: who];
    if(codes == nil) return NO;
    switch(tp) 
    {
        case SELECT:
            n = [fromArray count];
            for(i = 0; i < n; i++)
            {
                NSString *mycode;
                test = NO;
                mycode = [[fromArray objectAtIndex: i] objectForKey: @"_code"];
                if(ex)
                {
                    FORALL(codes)
                {
                        if([mycode isEqualToString: temp])
                        {
                            test = YES;
                            break;
                        }
                } ENDFORALL;
                }
                else
                {
                    FORALL(codes)
                {
                        if(isParentOf(temp, mycode))
                        {
                            test = YES;
                            break;
                        }
                } ENDFORALL;
                }
                if(test)[toArray addObject: [myData objectAtIndex: i]];
            }
                if([toArray count] <= 0)
                {
                    return NO;
                }
                return YES;
            break;
        case SELECTFEWER:
            n = [fromArray count];
            removeList = [NSMutableArray array];
            for(i = 0; i < n; i++)
            {
                NSString *mycode;
                test = NO;
                mycode = [[fromArray objectAtIndex: i] objectForKey: @"_code"];
                if(ex)
                {
                    FORALL(codes)
                {
                        if([mycode isEqualToString: temp])
                        {
                            test = YES;
                            break;
                        }
                } ENDFORALL;
                }
                else
                {
                    FORALL(codes)
                {
                        if(isParentOf(temp, mycode))
                        {
                            test = YES;
                            break;
                        }
                } ENDFORALL;
                }
                if(test)[removeList addObject: [myData objectAtIndex: i]];
            }
                if([removeList count] <= 0)
                {
                    return NO;
                }
                [toArray setArray: fromArray];
            [toArray removeObjectsInArray: removeList];
            
            return YES;
            break;
        case SELECTADDITIONAL:
            n = [backData count];
            removeList = [NSMutableArray array];
            for(i = 0; i < n; i++)
            {
                NSString *mycode;
                test = NO;
                mycode = [[backData objectAtIndex: i] objectForKey: @"_code"];
                if(ex)
                {
                    FORALL(codes)
                {
                        if([mycode isEqualToString: temp])
                        {
                            test = YES;
                            break;
                        }
                } ENDFORALL;
                }
                else
                {
                    FORALL(codes)
                {
                        if(isParentOf(temp, mycode))
                        {
                            test = YES;
                            break;
                        }
                } ENDFORALL;
                }
                if(test)
                {
                    if([fromArray indexOfObject: [backData objectAtIndex: i]] == NSNotFound)
                        [removeList addObject: [backData objectAtIndex: i]];
                }
            }
                if([removeList count] <= 0)
                {
                    return NO;
                }
                [toArray setArray: fromArray];
            [toArray addObjectsFromArray: removeList];
            
            return YES;
            break;
    };
}

-(BOOL) selectCodeSetWithName:(NSString *) who withWarnings: (BOOL) w pushStack: (BOOL) ps exact: (BOOL) ex
{
    return [self selectCodeSetWithName: who withWarnings: w pushStack: ps type: SELECT exact: ex];
}

-(BOOL) selectCodeSetWithName:(NSString *) who withWarnings: (BOOL) w pushStack: (BOOL) ps type: (int) tp exact: (BOOL) ex
{
    BOOL test;
    NSMutableArray *findData;
    
    if([self global: @"simpleflag"] == 0) return NO;
    
    
    findData = [[NSMutableArray alloc] init];
    test = [self selectDataFrom: myData to: findData forCodeSet: who type: tp exact: ex];
    if(test == NO)
    {
	if(w) {NSWARNING(@"No data found.");}
	return NO;
    }
    //this block is for autohistory
    if(ps) [self pushSetStack];
    
    [myData removeAllObjects];
    [myData addObjectsFromArray: findData];
    [findData release];
    return YES;
    
}
-(IBAction) selectCodeSet: (id) sender
{
    NSMutableDictionary *ahd = [NSMutableDictionary dictionary];
    if([self global: @"simpleflag"] == 0)
    {
    {NSWARNING(@"Selecting code sets requires a simple style search");}
        return;
    }
    if([self selectCodeSetWithName: [sender title] withWarnings: YES pushStack: YES exact: exactCodeSetFlag])
    {
        [ahd setObject: @"sel" forKey: @"stepType"];
        [ahd setObject: [NSNumber numberWithInt: SELECTCODESET] forKey: @"mode"];
        [ahd setObject: [[[sender title] copy] autorelease] forKey: @"name"];
        [ahd setObject: [NSNumber numberWithBool: exactCodeSetFlag] forKey: @"exact"];
        [autoHistory addObject: ahd];
        UPDATERECCOUNT;
        [theResults reloadData];
        [self addStateString: [NSString stringWithFormat: @"code set: %@", [sender title]]];
    }
}

-(void) sel2CodeSetDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    
    if(returnCode)
    {
        NSMutableArray *myCodeList;
        NSString *codeName;
        codeName = [sel2CodeSetName stringValue];
        if([gWorkBench codeSetExists: codeName])
        {
            if(NSYESNOQUESTION(@"Code set already exists with that name. Replace it?") == NO)
                return;
        }
        myCodeList = [NSMutableArray array];
        FORALL(myData)
        {
            addUniqueToArray(myCodeList, [[[temp objectForKey: @"_code"] copy] autorelease]);
        }
        ENDFORALL;
        [myCodeList sortUsingFunction: nsStringComp context: nil];
        [gWorkBench registerCodeSet: codeName withCodes:  myCodeList force: YES];
    }
    
}

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

-(IBAction) okSel2CodeSet: (id) Sender
{
    [sel2CodeSetSheet orderOut: Sender];
    [NSApp endSheet: sel2CodeSetSheet returnCode: 1];
    
}

-(IBAction) turnSelectionIntoCodeSet: (id) sender
{
    NSWindow *who;
    if([self global: @"simpleflag"] == 0)
    {
        NSWARNING(@"Must use a simple search to convert selections into code sets.");
        return;
    }
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    
    [sel2CodeSetName setStringValue: @""];
    [NSApp beginSheet: sel2CodeSetSheet
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(sel2CodeSetDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}

-(void) selCSDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    NSString *csName;
    BOOL csExact;
    NSString *stString;
    
    if(returnCode>0)
    {
        csName = [selCSMenu titleOfSelectedItem];
        if([selCSExactSwitch state] == NSOnState) exactCodeSetFlag=csExact = YES;
        else exactCodeSetFlag=csExact = NO;
        NSMutableDictionary *ahd = [NSMutableDictionary dictionary];
        if([self global: @"simpleflag"] == 0)
        {
        {NSWARNING(@"Selecting code sets requires a simple style search");}
            return;
        }
        if([self selectCodeSetWithName: csName withWarnings: YES pushStack: YES type: returnCode exact: csExact])
        {
            [ahd setObject: @"sel" forKey: @"stepType"];
            [ahd setObject: [NSNumber numberWithInt: SELECTCODESET] forKey: @"mode"];
            [ahd setObject: [NSNumber numberWithInt: returnCode] forKey: @"type"];
            [ahd setObject: [[csName copy] autorelease] forKey: @"name"];
            [ahd setObject: [NSNumber numberWithBool: csExact] forKey: @"exact"];
            
            [autoHistory addObject: ahd];
            UPDATERECCOUNT;
            [theResults reloadData];
            switch(returnCode)
            {
                case SELECT:
                    stString = [NSString stringWithFormat: @"code set: %@", csName];
                    break;
                case SELECTFEWER:
                    stString = [NSString stringWithFormat: @"-code set: %@", csName];
                    break;
                case SELECTADDITIONAL:
                    stString = [NSString stringWithFormat: @"+code set: %@", csName];
                    break;
            };
            if(csExact) [self addStateString: [NSString stringWithFormat: @"%@ (x)", stString]];
            else
                [self addStateString: stString];
            
        }
    }
    
}
-(IBAction) selCSCancel: (id) Sender
{
    [selCSSheet orderOut: Sender];
    [NSApp endSheet: selCSSheet returnCode: 0];
    
}
-(IBAction) selCSSelectLess: (id) Sender
{
    [selCSSheet orderOut: Sender];
    [NSApp endSheet: selCSSheet returnCode: SELECTFEWER];
    
}
-(IBAction) selCSSelectMore: (id) Sender
{
    [selCSSheet orderOut: Sender];
    [NSApp endSheet: selCSSheet returnCode: SELECTADDITIONAL];
    
}

-(IBAction) selCSSelect: (id) Sender
{
    [selCSSheet orderOut: Sender];
    [NSApp endSheet: selCSSheet returnCode: SELECT];
    
}
-(IBAction) doSelectCodeSetDialogue: (id) Sender
{
    NSWindow *who;
    if([self global: @"simpleflag"] == 0)
    {
        NSWARNING(@"Must use a simple search to convert selections into code sets.");
        return;
    }
    [selCSMenu removeAllItems];
    [selCSMenu addItemsWithTitles: [gWorkBench allCodeSetNames]];
    if([selCSMenu numberOfItems] >= 1) [selCSMenu selectItemAtIndex: 0];
    if(exactCodeSetFlag)
        [selCSExactSwitch setState: NSOnState];
    else
        [selCSExactSwitch setState: NSOffState];
    
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
    [NSApp beginSheet: selCSSheet
       modalForWindow: who
	modalDelegate: self
       didEndSelector: @selector(selCSDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    
}
-(IBAction) requestCodeDefinition: (id) sender
{
    int who;
    NSString *theCode;
    NSMutableString *theDef;
    //get the string
    if(gWorkBench == nil) return;
    if([self global: @"simpleflag"] == 0)
    {
        NSWARNING(@"Definitions are only available in simple searches");
        return;
    }
    who = [theResults selectedRow];
    if(who >= 0)
    {
        theCode = [[myData objectAtIndex: who] objectForKey: @"_code"];
    }
    else return;
    
    
    //ask for definition
    theDef = [gWorkBench getDefinition: theCode];
    if(!theDef) {
        NSString *warning;
        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) requestCodeDefinitionOfSelection: (id) sender
{
    NSRange who;
    NSString *theCode, *theSel;
    NSMutableString *theDef;
    NSString *warning;
    //get the string
    if(gWorkBench == nil) return;
    
    who = [thisCell selectedRange];
    if(who.length == 0) return;
    
    
    theSel = [[thisCell 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];
}
-(BOOL) isReal {return YES;}
-(void) appendComment: (NSString *) what
{
    NSMutableString *hh;
    if(what == nil)
    {
        return;
    }
    if([what isEqualToString: @""])
    {
        return;
    }
    hh = [NSMutableString stringWithString: what];
    trimCharNSS(hh,'\"');
    [commentArray addObject: hh];
    [extraComment appendString: hh];
}
-(void) endComment: (NSString *) what
{
    NSMutableString *hh;
    
    if(what == nil)
    {
        [self clearComments];
        return;
    }
    if([what isEqualToString: @""])
    {
        [self clearComments];
        return;
    }
    hh = [NSMutableString stringWithString: what];
    trimCharNSS(hh,'\"');
    FORALL(commentArray)
    {
        if([temp isEqualToString: hh])
        {
            [commentArray removeObjectAtIndex: __i];
            break;
        }
    }
    ENDFORALL;
    [extraComment setString: [commentArray componentsJoinedByString: @""]];
    
}

-(void) endLastComment
{
    if([commentArray count] > 0)
        [commentArray removeLastObject];
    if([commentArray count] == 0)
    {
        [self clearComments];
        return;
    }
    else
        [extraComment setString: [commentArray componentsJoinedByString: @""]];
    
}

-(void) clearComments
{
    [commentArray removeAllObjects];
    [extraComment setString: @""];
}
-(NSMutableString *) getComment
{
    return extraComment;
}
-(void) setComment: (NSString *) what;
{
    NSMutableString *hh;
    if(what == nil)
    {
        [self clearComments];
        return;
    }
    if([what isEqualToString: @""])
    {
        [self clearComments];
        return;
    }
    [self clearComments];
    hh = [NSMutableString stringWithString: what];
    trimCharNSS(hh,'\"');
    [extraComment setString: hh];
}
#ifdef MULTIMEDIA
-(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]);
            [mediaFileName 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]);
                    [mediaFileName setStringValue: [newPath lastPathComponent]];
                    [myMovieView setMovie: myMovie];
                    return;
                }
            }
        }
    }
    NSWARNING(@"Unable to find or open media file. Remove !mediafile metatag and relocate the file");
    
}

-(void) mediaPlayerDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    
    [myMovieView stop: nil];
    [myTimer invalidate];
    [myTimer release];
    
    [myMovie release];
    myMovie = nil;
    myTimer = nil;
}
-(IBAction) exitMediaPlayer: (id) Sender
{
    [mediaSheet orderOut: Sender];
    [NSApp endSheet: mediaSheet returnCode: 1];
    
}
-(IBAction) setMovieTime: (NSString *) tt;
{
    long tmValue, scale;
    double tm;
    if(myMovie == nil ) return;
    scale = (long) GetMovieTimeScale( [myMovie QTMovie]);
    if(isHHMMSS(tt))
    {
        tmValue = hhmmss2sec(tt) * scale;
    }
    else
    {
        tm = [tt doubleValue];
        tmValue = tm * scale;
    }
    SetMovieTimeValue([myMovie QTMovie], tmValue);
    /*    
        tm = [tt doubleValue];
    tmValue = tm * scale;
    SetMovieTimeValue([myMovie QTMovie], tmValue);*/
}  

-(IBAction) restartMedia: (id) sender
{
    int r1;
    NSString  *tc;
    
    //if I'm at the end exit
    r1 = [theResults selectedRow];
    {
        //then jump to the new time
        tc = [[myData objectAtIndex: r1] objectForKey: [gPrefBoss getAVCode]];
        if(tc == nil) return;
        if([tc isEqualToString: @""] != YES)
        {
            [mediaTimeCode setStringValue: tc];
            [self setMovieTime: tc];
        }
    }
}

-(void) jumpMediaRow: (int) row 
{
    int r1, r2, n;
    BOOL p;
    NSString *p1, *p2, *tc, *mf;
    
    //if I'm at the end exit
    r1 = mediaRow;
    r2 = row;
    n = [myData count];
    if(r2 >= n || r2 <= 0) return;
    p = [myMovieView isPlaying];
    //what is my file?
    p1 = [[[myData objectAtIndex: r1] objectForKey: @"_doc"] path];
    //What is the next file?
    p2 = [[[myData objectAtIndex: r2] objectForKey: @"_doc"] path];
    //are they the same
    if([p1 isEqualToString: p2])
    {
        //then jump to the new time
        tc = [[myData objectAtIndex: r2] objectForKey: [gPrefBoss getAVCode]];
        if(tc == nil) return;
        if([tc isEqualToString: @""] != YES)
        {
            [mediaTimeCode setStringValue: tc];
            [self setMovieTime: tc];
        }
    }
    else
    {
        [myMovieView stop: nil];
        //get file
        mf = [mediaDict objectForKey: p2];
        if(mf == nil) return;
        tc = [[myData objectAtIndex: r2] objectForKey: [gPrefBoss getAVCode]];
        if(tc == nil) return;
        [myMovie release];
        myMovie = nil;
        [self loadMediaFile: mf];
        {
            if([tc isEqualToString: @""] != YES)
            {
                [mediaTimeCode setStringValue: tc];
                [self setMovieTime: tc];
            }
        }
        
        if(p) [myMovieView start: nil];
    }
	if([theResults numberOfRows] > 0 && [theResults numberOfRows] > r2)
    [theResults selectRow: r2 byExtendingSelection: NO];
    mediaRow = r2;
    
    //else stop
    //load
    //jump to time
}


-(IBAction) jumpMediaBack: (id) sender
{
    int r1, r2, n;
    
    //if I'm at the end exit
    r1 = [theResults selectedRow];
    r2 = r1 - 1;
    n = [myData count];
    if(r1 == 0) return;
    [self jumpMediaRow: r2];
}

-(IBAction) jumpMediaForward: (id) sender
{
    int r1,r2, n;
    
    //if I'm at the end exit
    r1 = [theResults selectedRow];
    r2 = r1 + 1;
    n = [myData count];
    if(r1 >= n-1) return;
    [self jumpMediaRow: r2];
}

-(void) idleTimer:(id)sender
{
    long scale, ct;
    float time;
    if(myMovie == nil) return;
    scale = GetMovieTimeScale( [myMovie QTMovie]);
    ct =  GetMovieTime([myMovie QTMovie], nil);
    time = (float) ct/ (float) scale;
    if([gPrefBoss timeFormatHHMMSS] == 1)
        [mediaTimeCode setStringValue: sec2hhmmss((unsigned) time)];
    else
        [mediaTimeCode setStringValue: [NSString stringWithFormat: @"%.2fs", (float) ct/ (float) scale]];
    if(jagFlag)
        MoviesTask([myMovie QTMovie],0);
}

-(void) XidleTimer:(id)sender
{
    long scale, ct;
    double time;
    if(myMovie == nil) return;
    scale = GetMovieTimeScale( [myMovie QTMovie]);
    ct =  GetMovieTime([myMovie QTMovie], nil);
    time = (double) ct/ (double) scale;
    if([gPrefBoss timeFormatHHMMSS] == 1)
        [mediaTimeCode setStringValue: sec2hhmmss((unsigned) time)];
    else
        [mediaTimeCode setStringValue: [NSString stringWithFormat: @"%.2fs", time]];
    
    //[mediaTimeCode setStringValue: [NSString stringWithFormat: @"%.2fs", time];
    if(jagFlag)
        MoviesTask([myMovie QTMovie],0);
}


-(IBAction) doMediaPlayer: (id) sender
{
    int r;
    NSDictionary *dd;
    NSString *df, *mf;
    NSString *tc;
    r = [theResults selectedRow];
    if([mediaSheet isVisible])
    {
        [self jumpMediaRow: r];
        return;
    }
    //get row
    dd = [myData objectAtIndex: r];
    //get file
    df = [[dd objectForKey: @"_doc"] path];
    mf = [mediaDict objectForKey: df];
    if(mf == nil) return;
    tc = [dd objectForKey: [gPrefBoss getAVCode]];
    if(tc == nil) return;
    //does file have a media file
    //set the name of the media file
    //set the nsmovieview
    //jump to the location in the media file
    //run
    mediaRow = r;
    [NSApp beginSheet: mediaSheet
       modalForWindow: nil
	modalDelegate: self
       didEndSelector: @selector(mediaPlayerDidEnd:returnCode:contextInfo:)
          contextInfo: nil];
    if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_2)
        jagFlag = YES;
    else
        jagFlag = FALSE;
    
    if(myTimer == nil)
        myTimer = [[NSTimer scheduledTimerWithTimeInterval:0.1		// interval, 0.1 seconds
                                                    target:self
                                                  selector:@selector(idleTimer:)		// call this method
                                                  userInfo:nil
                                                   repeats:YES] retain];
    
    [self loadMediaFile: mf];
    {
        if([tc isEqualToString: @""] != YES)
        {
            
            [mediaTimeCode setStringValue: tc];
            
            [self setMovieTime: tc];
        }
    }
    
}
#else
-(void) idleTimer:(id)sender
{
}
#endif
@end
