1//
2//  myResults.m
3//  TAMS Edit
4//
5//  Created by matthew on Sun Apr 21 2002.
6//  Copyright (c) 2001 Matthew Weinstein. All rights reserved.
7//
8
9#import "myResults.h"
10#import "ctReadChar.h"
11#import "tams.h"
12#import "ctLimitCrit.h"
13#import "TAMSCharEngine.h"
14#import "coderec.h"
15#import "NSRecordData.h"
16#import "prefBoss.h"
17#import "myProject.h"
18#import "docDelegate.h"
19#import "appDelegate.h"
20#import "utils.h"
21#import "tamsutils.h"
22#import "MWPath.h"
23#import "MWFakeFile.h"
24#import "MGWPopUpButton.h"
25#import "MWKeyedResult.h"
26
27//#import "AGRegex.h"
28#import <stdio.h>
29#import <stdlib.h>
30#import "MWSortStackItem.h"
31#import "stringCategories.h"
32#import "MWTAMSStringCategories.h"
33//#define SIMON 1
34#define NOTIFICATIONDIRTY 1
35#define CLOSEBUG 1
36#define NAMEDSELMENU 140
37#define COLWIDTH 90.0
38#define XML 1
39#define REGEXSEARCH 1
40#define NAMEDSELBASE 4
41#define FIELDMAP 1
42#define MYGLOBAL(X)	[myGlobals findInt: X]
43#define SETGLOBAL(X,Y)	[myGlobals setKey: X intValue: Y]
44#define ON(X) if([X isEqualToString: [myc buff]] == YES)
45#define SELECTEDCOLUMNID(X) [[[X tableColumns] objectAtIndex: [X selectedColumn]] identifier]
46#define UPDATERECCOUNT	[self updateRecCount];
47
48#define TAMSTART(X) [[X objectForKey: @"_begin_loc"] intValue]
49#define TAMEND(X) [[X objectForKey: @"_end_loc"] intValue]
50#define MAKEDIRTY [self updateChangeCount: NSChangeDone];
51#define DIRTYWARN if([dirtySourceFlag state] == NSOnState) if(NSYESNOQUESTION(@"Results may be out of synch with data files. Proceed?") == NO) return;
52
53NSString *dateFmt[20] =
54{{@"%m/%d/%y"}, //mm/dd/yy
55{@"%m/%d/%Y"}, //mm/dd/yyyy
56{@"%m-%d-%y"}, //mm-dd-yyyy
57{@"%d/%m/%Y"}, //dd/mm/yyyy
58{@"%d/%m/%y"}, //dd/mm/yy
59{@"%B %d, %Y"}, //month dd, yyyy
60{@"%d %B, %Y"}, //dd month, yyyy
61{@"%I:%M"}, //hh:mm
62{@"%I:%M %p"}, //hh:mm AM/PM
63{@"%I:%M:%S"}, //hh:mm:ss
64{@"%I:%M:%S %p"},//hh:mm:ss AM/PM
65    {@"%H:%M"}, //24hh:mm
66{@"%H:%M:%S"}, //24hh:mm:ss
67{@""} //other
68};
69
70BOOL arrayContainsString(NSArray *a, NSString *s)
71{
72    int i;
73    int n;
74
75    n  = [a count];
76    for(i = 0; i < n; i++)
77    {
78        if([[a objectAtIndex: i] isEqualToString: s] == YES)
79            return YES;
80    }
81    return NO;
82}
83//need to change this for version 2
84int locationComp(id first, id second, void *key)
85{
86    //compare the documents
87    if([first objectForKey: @"_doc"] == [second objectForKey: @"_doc"])
88    {
89	if([[first objectForKey: @"_begin_loc"] intValue] >
90           [[first objectForKey: @"_begin_loc"] intValue])
91            return NSOrderedDescending;
92	else if([[first objectForKey: @"_begin_loc"] intValue] <
93		[[first objectForKey: @"_begin_loc"] intValue])
94            return NSOrderedAscending;
95	else return NSOrderedSame;
96    }
97    else
98    {
99        return [(MWFile *)[first objectForKey: @"_doc"] compare: [second objectForKey: @"_doc"]];
100
101
102    }
103}
104int locationFwdComp(id first, id second, void *key)
105{
106    //compare the documents
107    if([[first objectForKey: @"_doc"] isEqual: [second objectForKey: @"_doc"]])
108    {
109	if([[first objectForKey: @"_begin_loc"] intValue] <
110           [[first objectForKey: @"_begin_loc"] intValue])
111            return NSOrderedDescending;
112	else if([[first objectForKey: @"_begin_loc"] intValue] >
113		[[first objectForKey: @"_begin_loc"] intValue])
114            return NSOrderedAscending;
115	else return NSOrderedSame;
116    }
117    else
118    {
119        return ([(MWFile *)[first objectForKey: @"_doc"] compare: [second objectForKey: @"_doc"]]);
120
121
122    }
123}
124
125
126
127int nsStringComp(id first, id second, void *key)
128{
129    return([(NSString *)first compare: second]);
130}
131int nsMWFileComp(id first, id second, void *key)
132{
133    return nsStringComp([first name], [second name], key);
134}
135
136
137int stringComp(id first, id second, NSString *key)
138{
139    return [[first objectForKey: key] compare: [second objectForKey: key]];
140}
141
142int longFwdComp(id first, id second, NSString *key)
143{
144    int a, b;
145    a = [[first objectForKey: key] intValue];
146    b = [[second objectForKey: key] intValue];
147    if(a < b)
148	return NSOrderedAscending;
149    else if(a > b)
150	return NSOrderedDescending;
151    else
152	return NSOrderedSame;
153}
154
155@implementation myResults
156-(void) updateOnlyRecCount
157{
158    [recCount setStringValue:
159        [NSString stringWithFormat: @"%d/%d", [myData count], [backData count]]];
160
161}
162-(void) updateRecCountVertical
163{
164    int n;
165    n = [myData count];
166    [recCount setStringValue:
167        [NSString stringWithFormat: @"%d/%d", n, [backData count]]];
168    [self updateChangeCount: NSChangeDone];
169    if([theResults selectedColumn] < 0 && [theResults numberOfRows] > 0)
170    {
171        [theResults selectRow: 0 byExtendingSelection: NO];
172    }
173    [self displaySelData: 0];
174
175}
176
177-(void) updateRecCount
178{
179    int r, n;
180    n = [myData count];
181    r = [theResults selectedRow];
182    [recCount setStringValue:
183        [NSString stringWithFormat: @"%d/%d", n, [backData count]]];
184    [self updateChangeCount: NSChangeDone];
185	if(n>0 && [theResults numberOfRows] > 0)
186    {
187        [theResults selectRow: 0 byExtendingSelection: NO];
188        [self displaySelData: 0];
189    }
190
191}
192-(void) updateRecCountAtRow
193{
194    int r, n;
195    n = [myData count];
196    r = [theResults selectedRow];
197    [recCount setStringValue:
198        [NSString stringWithFormat: @"%d/%d", n, [backData count]]];
199    [self updateChangeCount: NSChangeDone];
200    if(r < n && r >= 0)
201        [self displaySelData: r];
202    else
203    {
204	if (n > 0 && [theResults numberOfRows] > 0)
205        [theResults selectRow: 0 byExtendingSelection: NO];
206
207        [self displaySelData: 0];
208    }
209
210}
211-(BOOL) isUniversal: (NSString *) name
212{
213    FORALL(univList)
214    {
215	if([temp isEqualToString: name]) return YES;
216
217    }
218    ENDFORALL;
219    return NO;
220}
221
222-(BOOL) isInnerRepeat: (NSString *) name
223{
224    FORALL(innerRepList)
225    {
226	if([temp isEqualToString: name]) return YES;
227
228    }
229    ENDFORALL;
230    return NO;
231}
232-(BOOL) isLastRepeat: (NSString *) name
233{
234    FORALL(lastRepList)
235    {
236	if([temp isEqualToString: name]) return YES;
237
238    }
239    ENDFORALL;
240    return NO;
241}
242
243-(BOOL) isRepeat: (NSString *) name
244{
245    FORALL(repList)
246    {
247	if([temp isEqualToString: name]) return YES;
248
249    }
250    ENDFORALL;
251    return NO;
252}
253-(BOOL) isBlocked: (NSString *) name
254{
255    FORALL(blockList)
256    {
257	if([temp isEqualToString: name]) return YES;
258
259    }
260    ENDFORALL;
261    return NO;
262}
263
264-(int) getDocType {return myDocType;}
265-(void) setCharEngineWithSource: (id) src andFileList: (NSArray *) myList
266{
267
268    tce = [[TAMSCharEngine alloc] init];
269    [tce addArrayToSearchList: myList];
270    [tce setGCurrentDataSource: src];
271    [tce startSearch];
272}
273-(void) setCharEngine: (TAMSCharEngine*) who {tce = who;}
274-(void) setGlobalInt: (id) key value: (int) v
275{
276    [myGlobals setKey: key intValue: v];
277}
278-(int) global: (NSString *)name
279{
280    return [myGlobals findInt: name];
281}
282-(void) setGlobal: (NSString *) name to: (int) val
283{
284    [myGlobals setKey: name intValue: val];
285}
286
287-(void) initVariables
288{
289	builtTable = NO;
290    [myGlobals setKey: @"eofIsEndFlag" intValue: [gPrefBoss EOFIsEndValue]];
291    [myGlobals setKey: @"firstwriteflag" intValue: 1];
292    [myGlobals setKey: @"quoteflag" intValue: 1];
293    [myGlobals setKey: @"tabflag" intValue: 0];
294    [myGlobals setKey: @"headerflag" intValue: 1];
295    [myGlobals setKey: @"lnumflag" intValue: 0];
296    [myGlobals setKey: @"lineflag" intValue: 0];
297    [myGlobals setKey: @"fastflag" intValue: 0];
298    [myGlobals setKey: @"basicflag" intValue: [gPrefBoss defaultUnstruct]];
299    [myGlobals setKey: @"blankflag" intValue: 1];
300    [myGlobals setKey: @"startflag" intValue: 1];
301    [myGlobals setKey: @"nameflag" intValue: 0];
302    [myGlobals setKey: @"noparflag" intValue: 1];
303    [myGlobals setKey: @"cleanflag" intValue: 1];
304    [myGlobals setKey: @"lastRepeat" intValue: 0];
305    [myGlobals setKey: @"skipinnertopofdoc" intValue: 1];
306    [myGlobals setKey: @"skipinneratend" intValue: 1];
307    [myGlobals setKey: @"linecount" unsValue: 1L];
308    [myGlobals setKey: @"escapeflag" unsValue: [gPrefBoss escapeBracesValue]];
309    [myGlobals setKey: @"zeromark" unsValue: 0];
310    SETGLOBAL(@"backloadrepeatflag", [gPrefBoss backendRepeatValue]);
311    SETGLOBAL(@"zapuniversal", [gPrefBoss zapUnivValue]);
312    if([self global: @"skipinnertopofdoc"] == 1)innerRFlag = 0;
313
314
315}
316-(id) init
317{
318    [super init];
319    myDocType = RESULTTYPE;
320    firstUpdateFlag = YES;
321    exactCodeSetFlag = YES;
322    stripTags = NO;
323    //[[NSDocumentController sharedDocumentController] addDocument: self];
324    myGlobals = [[varRegistry alloc] init];
325    closePermission = NO;
326    caseSortFlag = NO;
327    fieldMap = [[NSMutableDictionary alloc] init];
328    univVault = [[NSMutableDictionary alloc] init];
329    normVault = [[NSMutableDictionary alloc] init];
330    repVault = [[NSMutableDictionary alloc] init];
331    univList = [[NSMutableArray alloc] init];
332    fileList = [[NSMutableArray alloc] init];
333    codersList = [[NSMutableArray alloc] init];
334    colList = [[NSMutableArray alloc] init];
335    repList = [[NSMutableArray alloc] init];
336    blockList = [[NSMutableArray alloc] init];
337    myData = [[NSMutableArray alloc] init];
338    backData = [[NSMutableArray alloc] init];
339    setStack = [[NSMutableArray alloc] init];
340    fwdSetStack = [[NSMutableArray alloc] init];
341    fmode = [[NSMutableString alloc] init];
342    innerRepeat = [[NSMutableString alloc] init];
343    markedList = [[NSMutableArray alloc] init];
344    savedDataType = [[NSMutableString alloc] init];
345    lastRepList = [[NSMutableArray alloc] init];
346    innerRepList = [[NSMutableArray alloc] init];
347    lgNewCodeName = [[NSMutableString alloc] init];
348    lgNewCodeDef = [[NSMutableString alloc] init];
349    sortStack = [[NSMutableArray alloc] init];
350    dfString = [[NSMutableString alloc] init];
351    [dfString setString: dateFmt[0]];
352    browseField = [[NSMutableString alloc] initWithString: @"_data"];
353    codersString = [[NSMutableString alloc] init];
354    namedSelSelected = [[NSMutableString alloc] init];
355    namedSelDict = [[NSMutableDictionary alloc] init];
356    repCont = [[NSMutableDictionary alloc] init];
357    autoSets = [[NSMutableDictionary alloc] init];
358    summReports = [[NSMutableDictionary alloc] init];
359    autoHistory = [[NSMutableArray alloc] init];
360    autoHistoryStart = [[NSMutableString alloc] init];
361    extraComment = [[NSMutableString alloc] init];
362    commentArray = [[NSMutableArray alloc] init];
363    mediaDict = [[NSMutableDictionary alloc] init];
364    myMovie = nil;
365    myTimer = nil;
366    dfIndex = -1;
367
368    limitString = nil;
369
370    //These are set by the user and should maintain their value so we don't reset them in initVariable
371    [myGlobals setKey: @"simpleflag" intValue: 0];
372    [myGlobals setKey: @"limitflag" intValue: 0];
373    [myGlobals setKey: @"rawflag" intValue: 1];
374    [myGlobals setKey: @"exactflag" intValue: 0];
375    [myGlobals setKey: @"emptyflag" intValue: 1];
376    [myGlobals setKey: @"regexcharflag" intValue: 1];
377    [myGlobals setKey: @"sectionsearch" intValue: 0];
378    [self initVariables];
379
380    return self;
381}
382
383- (void) reconnect
384{
385    FORALL(fileList)
386    {
387        [[NSNotificationCenter defaultCenter] addObserver: self
388                                                 selector: @selector(handleDirtySourceFlag:)
389                                                     name: @"TAMSDocDidChange"
390                                                   object: temp];
391        /*
392         [[NSNotificationCenter defaultCenter] addObserver: self
393                                                  selector: @selector(addCodeHandler:)
394                                                      name: @"TAMSDocAddedCode"
395                                                    object: temp];*/
396    }
397    ENDFORALL;
398
399
400}
401- (void) disconnect
402{
403    [[NSNotificationCenter defaultCenter]
404	    removeObserver:self];
405    /*
406    FORALL(fileList)
407    {
408	[[NSNotificationCenter defaultCenter]
409	    removeObserver:self
410                      name: @"TAMSDocDidChange"
411                    object: temp
412	    ];
413    }ENDFORALL;
414    */
415}
416
417- (void) close
418{
419    [self disconnect];
420    [super close] ;
421}
422-(void) dealloc {
423    [self disconnect];
424    [autoHistory release];
425    [lastRepList release];
426    [innerRepList release];
427    [autoHistoryStart release];
428    [autoSets release];
429    [univVault release];
430    [normVault release];
431    [repVault release];
432    [univList release];
433    [fieldMap release];
434    [summReports release];
435    [fileList release];
436    [colList release];
437    [savedDataType release];
438    [repList release];
439    [browseField release];
440    [mediaDict release];
441    [extraComment release];
442    [commentArray release];
443    [blockList release];
444    [myData release];
445    [backData release];
446    [fmode release];
447    [markedList release];
448    [lgNewCodeName release];
449    [lgNewCodeDef release];
450    [dfString release];
451    [codersList release];
452    [innerRepeat release];
453    [sortStack release];
454    [namedSelSelected release];
455    [namedSelDict release];
456    [repCont release];
457    [setStack release];
458    [fwdSetStack release];
459
460    [super dealloc];
461}
462
463-(void) addCodeHandler: (NSNotification *) notification
464{
465    NSDictionary *info;
466    MWFile *who;
467
468    who = [notification object];
469    info = [notification userInfo];
470    FORALL(backData)
471    {
472        if([temp objectForKey: @"_doc"] == who)
473        {
474            int b, e, l, loc;
475            loc = [[info objectForKey: @"location"] intValue];
476            l = [[info objectForKey: @"length"] intValue];
477            b = [[temp objectForKey: @"_begin_loc"] intValue];
478            e = [[temp objectForKey: @"_end_loc"] intValue];
479            if(b >= loc)
480                [temp setObject: [NSNumber numberWithLong: (b + l)]
481                         forKey: @"_begin_loc"];
482            if(e >= loc)
483                [temp setObject: [NSNumber numberWithLong:( e + l)]
484                         forKey: @"_end_loc"];
485        }
486
487    }
488    ENDFORALL;
489    [theResults reloadData];
490}
491
492
493#ifdef NOTIFICATIONDIRTY
494-(void) handleDirtySourceFlag: (NSNotification *) notification
495{
496    // if this is one of mine get dirty
497    if([dirtySourceFlag state] == NSOnState) return;
498    FORALL(fileList)
499    {
500	//if([(MWFile *)temp compare: [notification object]] == YES)
501        if(temp == [notification object])
502	{
503	    [dirtySourceFlag setState: NSOnState];
504	    return;
505	}
506    }
507    ENDFORALL;
508}
509#else
510//update method
511- (void)windowDidBecomeKey:(NSNotification *)aNotification
512{
513    //do the docs exist
514    FORALL(fileList)
515    {
516	if([gWorkBench fileExists: temp] == YES)
517	{
518            //if yes are dirty
519	    [dirtySourceFlag setState: NSOnState];
520	    return;
521	}
522    } ENDFORALL;
523    //mark me and return
524    if(gWorkBench != nil)
525    {
526        if([gWorkBench reanalysisMode] == YES)
527        {
528            [[[NSApp delegate] reanalysisMenu] setState: NSOnState];
529        }
530        else
531        {
532            [[[NSApp delegate] reanalysisMenu] setState: NSOffState];
533        }
534        [gWorkBench rebuildCodeSetMenu];
535    }
536
537}
538#endif
539
540-(void) adjustBy: (int) amt startingAt: (int) loc for: (id) who
541{
542    int newLoc;
543    FORALL(myData)
544    {
545	if([[temp objectForKey: @"_doc"] isEqual: who])
546	{
547	    if([[temp objectForKey: @"_begin_loc"] intValue] > loc)
548	    {
549		newLoc = [[temp objectForKey: @"_begin_loc"] intValue] + amt;
550		[temp setObject: [NSNumber numberWithInt: newLoc] forKey: @"_begin_loc"];
551	    }
552	    if([[temp objectForKey: @"_end_loc"] intValue] > loc)
553	    {
554		newLoc = [[temp objectForKey: @"_end_loc"] intValue] + amt;
555		[temp setObject: [NSNumber numberWithInt: newLoc] forKey: @"_end_loc"];
556	    }
557	}
558    } ENDFORALL;
559}
560
561-(IBAction) doMarkAll: (id) sender
562{
563    [markedList setArray: myData];
564    [theResults reloadData];
565    [self updateChangeCount: NSChangeDone];
566
567}
568
569-(IBAction) doUnmarkAll: (id) sender
570{
571    [markedList removeAllObjects];
572    [theResults reloadData];
573    [self updateChangeCount: NSChangeDone];
574
575}
576
577-(void) markRecord: (int) row withReload: (BOOL) doit
578{
579    if([markedList indexOfObject: [myData objectAtIndex: row]] == NSNotFound)
580    {
581	[markedList addObject: [myData objectAtIndex: row]];
582    }
583    if(doit == YES)
584        [theResults reloadData];
585    [self updateChangeCount: NSChangeDone];
586}
587
588//array of nsnumbers
589-(void) markArray: (NSArray *) rows
590{
591    FORALL(rows)
592    {
593        [self markRecord: [temp intValue] withReload: NO];
594    }
595    ENDFORALL;
596    [theResults reloadData];
597    [self updateChangeCount: NSChangeDone];
598
599}
600-(void) markBackArray: (NSArray *) rows
601{
602    FORALL(rows)
603    {
604        if([markedList indexOfObject: [backData objectAtIndex:  [temp intValue]]] == NSNotFound)
605        {
606            [markedList addObject: [backData objectAtIndex: [temp intValue]]];
607        }
608
609    }
610    ENDFORALL;
611    [theResults reloadData];
612    [self updateChangeCount: NSChangeDone];
613
614}
615
616-(IBAction) doMark: (id) sender
617{
618    int row;
619
620    row = [theResults selectedRow];
621    if([markedList indexOfObject: [myData objectAtIndex: row]] == NSNotFound)
622    {
623	[markedList addObject: [myData objectAtIndex: row]];
624    }
625    [theResults reloadData];
626    [self updateChangeCount: NSChangeDone];
627
628}
629-(IBAction) doUnmark: (id) sender
630{
631    int row;
632    int selObj;
633
634    row = [theResults selectedRow];
635    selObj = [markedList indexOfObject: [myData objectAtIndex: row]];
636    if(selObj != NSNotFound)
637    {
638	[markedList removeObject: [myData objectAtIndex: row]];
639    }
640    [theResults reloadData];
641    MAKEDIRTY;
642
643}
644
645-(IBAction) doDeleteMarked: (id) sender
646{
647    if([markedList count])
648    {
649	FORALL(markedList)
650    {
651	    [myData removeObject: temp];
652    }
653	ENDFORALL;
654	[markedList removeAllObjects];
655        [theResults reloadData];
656        UPDATERECCOUNT;
657        MAKEDIRTY;
658    }
659}
660
661-(IBAction) doReverseMarked: (id) sender
662{
663    NSMutableArray *newMarked = [[NSMutableArray alloc] init];
664    //save the total list into an array
665    [newMarked setArray: myData];
666    //remove the marked
667    FORALL(markedList)
668    {
669	[newMarked removeObject: temp];
670    }
671    ENDFORALL;
672    //set the new marked list
673    [markedList setArray: newMarked];
674    [newMarked release];
675    //reload
676    [theResults reloadData];
677    MAKEDIRTY;
678
679
680}
681
682-(IBAction) doShowComment: (id) sender
683{
684    int row;
685    id aRec;
686
687    //get the key numbers
688    row = [theResults selectedRow];
689    //make a range
690    aRec = [myData objectAtIndex: row];
691    NSRunAlertPanel(@"Comment:", [aRec objectForKey: @"_comment"], @"Ok", nil, nil);
692
693}
694
695-(void) newCodeDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
696{
697    if(returnCode == 1)
698    {
699	[lgNewCodeName setString: [newCodeName stringValue]];
700	[lgNewCodeDef setString: [newCodeDef string]];
701	[arBossWindow orderOut: self];
702	[NSApp endSheet: arBossWindow returnCode: 1];
703    }
704
705
706}
707-(IBAction) deleteSourceCodes: (id) Sender
708{
709    NSMutableArray *myLocalRecs;
710    id myRec, ans;
711    NSEnumerator *locList;
712    DIRTYWARN;
713    if([self global: @"sectionsearch"] == YES || [self global: @"regexcharflag"] == YES ||
714       [self global: @"nonregexcharflag"] == YES)
715    {
716        NSWARNING(@"Cannot delete codes this type of search");
717        return;
718    }
719    if([self global: @"limitflag"] && ![self global: @"simpleflag"])
720    {
721	NSWARNING(@"Only simple searches can have records removed");
722	return;
723    }
724    ans = NSYESNOQUESTION(@"This will delete information from your source files. Should I proceed?");
725    if(ans == NO) return;
726    if([markedList count])
727    {
728
729        //is there something there?
730        //refresh?
731        //copy records
732        myLocalRecs = [[NSMutableArray alloc] init];
733        [myLocalRecs setArray: markedList];
734
735        //reverse sort
736        [myLocalRecs sortUsingFunction: locationComp context: nil];
737
738        //go through and call the main docuement
739        locList = [markedList reverseObjectEnumerator];
740        while(myRec = [locList nextObject])
741        {
742            if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
743            {
744                if([gPrefBoss batchOpenFiles])
745                    [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
746                else
747                    [(MWFile *)[myRec objectForKey: @"_doc"] setOpenFakeFileWithWorkBench: gWorkBench];
748
749            }
750
751            [[[myRec objectForKey: @"_doc"] filePointer ] deleteCodeFromResultStartingWith: 			[[myRec objectForKey: @"_begin_loc"] intValue]
752                                                                                endingWith: [[myRec objectForKey:@"_end_loc"] intValue] from: self];
753        }
754        if([gPrefBoss batchOpenFiles] == 0)
755        {
756            locList = [myLocalRecs reverseObjectEnumerator];
757            while(myRec = [locList nextObject])
758            {
759                [(MWFile *)[myRec objectForKey: @"_doc"] closeFakeFile];
760
761            }
762        }
763        //remove the files from here
764        if([markedList count])
765        {
766            FORALL(markedList)
767        {
768                [myData removeObject: temp];
769                [backData removeObject: temp];
770        }
771            ENDFORALL;
772            [markedList removeAllObjects];
773        }
774        [theResults reloadData];
775        UPDATERECCOUNT;
776
777        //have it reload
778        if([gPrefBoss autoReloadValue])
779            [self refreshResults: self];
780
781    }
782    else
783    {
784    }
785}
786-(void) recodeDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
787{
788    NSMutableArray *myLocalRecs;
789    NSMutableString *myNewCodeName;
790    id myRec;
791    NSEnumerator *locList;
792
793    myNewCodeName = [[NSMutableString alloc] init];
794
795
796    if([markedList count])
797    {
798	if(returnCode == 1)
799	{
800	    //is there something there?
801	    if([lgNewCodeName isEqualToString: @""] == YES) return;
802	    //refresh?
803	    //copy records
804	    myLocalRecs = [[NSMutableArray alloc] init];
805	    [myLocalRecs setArray: markedList];
806
807	    //reverse sort
808	    [myLocalRecs sortUsingFunction: locationComp context: nil];
809
810	    //go through and call the main docuement
811	    locList = [markedList reverseObjectEnumerator];
812	    while(myRec = [locList nextObject])
813	    {
814                if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
815                    [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
816		[[[myRec objectForKey: @"_doc"] filePointer] recode: lgNewCodeName
817                                                              first: [[myRec objectForKey:@"_begin_loc"] intValue]
818                                                               last: [[myRec objectForKey:@"_end_loc"] intValue] from: self
819                                                            withDef: lgNewCodeDef];
820	    }
821            if([gPrefBoss cancelAfterRecode] == 1)
822                [self doUnmarkAll: nil];
823
824	    //have it reload
825	    if([gPrefBoss autoReloadValue])
826		[self refreshResults: self];
827	}
828    }
829    else
830    {
831    }
832}
833
834//#define MODALWIND 1
835
836-(void) setInnerRepeat: (NSString *) what
837{
838    [innerRepeat setString: what];
839    trimNSS(innerRepeat);
840
841}
842-(void) buildCoderList
843{
844    NSString *ss;
845    NSMutableArray *tempArray;
846    int n;
847
848    //remove objects
849    [codersList removeAllObjects];
850    //get the list
851    ss = codersString;
852    //split object
853    tempArray = convertStringToArray(ss, ',');
854    [tempArray retain];
855    n = [tempArray count];
856    FORALL(tempArray)
857    {
858	NSMutableString *tt;
859	tt = [[NSMutableString alloc] init];
860	[tt setString: temp];
861	trimNSS(tt);
862	[codersList addObject: tt];
863    }
864    ENDFORALL;
865    n = [codersList count];
866    //trim objects
867    [tempArray release];
868}
869-(IBAction) doAddCodeOK: (id) sender
870{
871    lgNewCodeMode = CODEMODEOLD;
872    [lgNewCodeName setString: [addCodeName titleOfSelectedItem]];
873    [lgNewCodeDef setString: @""];
874    [addCodeWindow orderOut: sender];
875    [NSApp endSheet: addCodeWindow returnCode: 1];
876
877}
878
879-(IBAction) doFillName: (id) sender
880{
881    [newCodeName setStringValue: [addCodeName titleOfSelectedItem]];
882}
883
884-(IBAction) doNewCode: (id) sender
885{
886    lgNewCodeMode = CODEMODENEW;
887    if([inheritedColorSwitch state] == NSOnState)
888        lgNewCodeColor = inheritedColor;
889    else
890        lgNewCodeColor = otherColor;
891    //lgNewCodeColor = [[codeColorMenu selectedItem] tag];
892    lgNewRealColor = [myColorWell color];
893    [lgNewCodeName setString: [newCodeName stringValue]];
894    [lgNewCodeDef setString: [newCodeDef string]];
895    [addCodeWindow orderOut: sender];
896    [NSApp endSheet: addCodeWindow returnCode: 1];
897
898}
899
900
901-(IBAction) doAddCodeCancel: (id) sender
902{  [addCodeWindow orderOut: sender];
903    [NSApp endSheet: addCodeWindow returnCode: 0];
904
905}
906
907-(IBAction) selectColorFromWell:(id)Sender
908{
909    [inheritedColorSwitch setState: NSOffState];
910}
911-(IBAction) selectColorFromSwitch:(id) sender
912{
913    if([inheritedColorSwitch state] == NSOnState)
914        [myColorWell setColor: [gWorkBench colorForCode: [newCodeName stringValue]]];
915}
916-(NSMutableString *) escapeCommentBraces: (NSMutableString *) who
917{
918    NSRange r, r1;
919    int i,n;
920    NSMutableString *ss = [NSMutableString string];
921    r = [who rangeOfString: @"{"];
922    r1 = [who rangeOfString: @"}"];
923    if(r1.location == NSNotFound && r.location == NSNotFound) return who;
924    n = [who length];
925    for(i = 0; i < n; i++)
926    {
927        if([who characterAtIndex: i] == '\\')
928        {
929            if(i < n -1)
930            {
931                [ss ADDCHAR([who characterAtIndex: i])];
932                i++;
933                [ss ADDCHAR([who characterAtIndex: i])];
934                continue;
935            }
936        }
937        if([who characterAtIndex: i] == '{')
938        {
939            [ss ADDCHAR('\\')];
940            [ss ADDCHAR([who characterAtIndex: i])];
941            continue;
942        }
943        if([who characterAtIndex: i] == '}')
944        {
945            [ss ADDCHAR('\\')];
946            [ss ADDCHAR([who characterAtIndex: i])];
947            continue;
948        }
949        [ss ADDCHAR([who characterAtIndex: i])];
950    }
951    [who setString: ss];
952    return who;
953}
954-(void) addCommentDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (NSArray *) hotList
955{
956    NSString *lgNewCodeName;
957    NSMutableString *thisCmnt, *theCmnt;
958    NSMutableArray *myLocalRecs;
959    id myRec;
960    NSEnumerator *locList;
961    if(returnCode)
962    {
963        if([hotList count])
964	{
965            thisCmnt = [[NSMutableString alloc] init];
966            theCmnt = [commentField string];
967            //is there something there?
968            myLocalRecs = [[NSMutableArray alloc] init];
969            [myLocalRecs setArray: hotList];
970
971            //reverse sort
972            [myLocalRecs sortUsingFunction: locationComp context: nil];
973
974            //go through and call the main docuement
975            locList = [myLocalRecs reverseObjectEnumerator];
976            while(myRec = [locList nextObject])
977            {
978                if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
979                {
980                    if([gPrefBoss batchOpenFiles] == 1)
981                        [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
982                    else
983                        [(MWFile *)[myRec objectForKey: @"_doc"] setOpenFakeFileWithWorkBench: gWorkBench];
984                }
985                lgNewCodeName = [myRec objectForKey: @"_code"] ;
986                if(commentMode == 0)
987                {
988                    [thisCmnt setString: theCmnt];
989                }
990                else
991                {
992                    NSString *cmt1;
993                    cmt1 = [myRec objectForKey: @"_comment"];
994                    if(cmt1 != nil)
995                        [thisCmnt setString: cmt1];
996                    [thisCmnt appendString: theCmnt];
997                }
998                [self escapeCommentBraces: thisCmnt];
999                [[[myRec objectForKey: @"_doc"] filePointer] recode: lgNewCodeName
1000                                                            comment: thisCmnt
1001                                                              first: [[myRec objectForKey:@"_begin_loc"] intValue]
1002                                                               last: [[myRec objectForKey:@"_end_loc"] intValue] from: self
1003                                                            withDef: @""];
1004                /*
1005                 This is too crude, but is the start of refreshing the actual data,
1006                 what would need to happen is have tce or some such object translate this*/
1007
1008
1009
1010                [myRec setObject: thisCmnt
1011                          forKey: @"_comment"];
1012
1013            }
1014            if([gPrefBoss batchOpenFiles] == 0)
1015            {
1016                locList = [myLocalRecs reverseObjectEnumerator];
1017                while(myRec = [locList nextObject])
1018                {
1019                    [(MWFile *)[myRec objectForKey: @"_doc"] closeFakeFile];
1020
1021                }
1022            }
1023            //have it reload
1024            [self updateRecCountAtRow];
1025            if([gPrefBoss cancelAfterRecode] == 1)
1026                [self doUnmarkAll: nil];
1027            if([gPrefBoss autoReloadValue])
1028                [self refreshResults: self];
1029            [self displaySelData];
1030            [thisCmnt release];
1031            [myLocalRecs release];
1032
1033	}
1034	else
1035	{
1036	}
1037
1038    }
1039    [hotList autorelease];
1040}
1041
1042
1043-(IBAction) cancelAddComment: (id) Sender
1044{
1045    [commentSheet orderOut: Sender];
1046    [NSApp endSheet: commentSheet returnCode: 0];
1047
1048}
1049
1050-(IBAction) okAddComment: (id) Sender
1051{
1052    [commentSheet orderOut: Sender];
1053    [NSApp endSheet: commentSheet returnCode: 1];
1054
1055}
1056
1057-(IBAction) doAppendCommentToMarked: (id) sender
1058{
1059    int row;
1060    NSMutableArray *hitList;
1061    NSWindow *who;
1062    NSString *cmt;
1063
1064    DIRTYWARN;
1065    hitList = [[NSMutableArray alloc] init];
1066    if([self global: @"simpleflag"] == 0)
1067    {
1068        NSWARNING(@"You can only add comments to simple searches.");
1069        return;
1070    }
1071    row = [theResults selectedRow];
1072    [hitList addObjectsFromArray: markedList];
1073    [commentField setString: @""];
1074    /*
1075     row = [theResults selectedRow];
1076     if([markedList indexOfObject: [myData objectAtIndex: row]] == NSNotFound)
1077     {
1078         [markedList addObject: [myData objectAtIndex: row]];
1079     }
1080     [theResults reloadData];
1081     [self updateChangeCount: NSChangeDone];
1082     */
1083    commentMode=1;
1084
1085    if([gPrefBoss detachedSheetValue])
1086        who = nil;
1087    else
1088        who = myWindow;
1089
1090    [NSApp beginSheet: commentSheet
1091       modalForWindow: who
1092	modalDelegate: self
1093       didEndSelector: @selector(addCommentDidEnd:returnCode:contextInfo:)
1094          contextInfo: hitList];
1095
1096}
1097
1098-(IBAction) doAddComment: (id) sender
1099{
1100    int row;
1101    NSMutableArray *hitList;
1102    NSWindow *who;
1103    NSString *cmt;
1104
1105    DIRTYWARN;
1106    hitList = [[NSMutableArray alloc] init];
1107    if([self global: @"simpleflag"] == 0)
1108    {
1109        NSWARNING(@"You can only add comments to simple searches.");
1110        return;
1111    }
1112    row = [theResults selectedRow];
1113    if(row >=0)
1114        [hitList addObject: [myData objectAtIndex: row]];
1115    cmt = [[myData objectAtIndex: row] objectForKey: @"_comment"];
1116    if(cmt != nil) [commentField setString: cmt];
1117    commentMode = 0;
1118    /*
1119     row = [theResults selectedRow];
1120     if([markedList indexOfObject: [myData objectAtIndex: row]] == NSNotFound)
1121     {
1122         [markedList addObject: [myData objectAtIndex: row]];
1123     }
1124     [theResults reloadData];
1125     [self updateChangeCount: NSChangeDone];
1126     */
1127
1128    if([gPrefBoss detachedSheetValue])
1129        who = nil;
1130    else
1131        who = myWindow;
1132
1133    [NSApp beginSheet: commentSheet
1134       modalForWindow: who
1135	modalDelegate: self
1136       didEndSelector: @selector(addCommentDidEnd:returnCode:contextInfo:)
1137          contextInfo: hitList];
1138
1139}
1140-(IBAction) doRecode: (id) sender
1141{
1142    NSArray *clist;
1143    NSWindow *who;
1144    NSString *hcode;
1145    DIRTYWARN;
1146    if(![markedList count]) return;
1147    hcode = [[markedList objectAtIndex: 0] objectForKey: @"_code"];
1148    if([self global: @"sectionsearch"] == YES || [self global: @"regexcharflag"] == YES ||
1149       [self global: @"nonregexcharflag"] == YES)
1150    {
1151        NSWARNING(@"Cannot recode this type of search");
1152        return;
1153    }
1154    if([self global: @"limitflag"] && ![self global: @"simpleflag"])
1155    {
1156	NSWARNING(@"Only simple searches can be recoded");
1157	return;
1158    }
1159    //delete the menu items
1160    if([addCodeName numberOfItems])
1161        [addCodeName removeAllItems];
1162    //get a fresh list
1163    //add new
1164    //[addCodeName addItemWithTitle: @"New"];
1165    //build up the menu
1166    clist = [gWorkBench getHotCodeList];
1167    [addCodeName addItemsWithTitles: clist];
1168    [addCodeName selectItemAtIndex: 0];
1169    recodeFlag = 1;
1170    if([self global: @"simpleflag"])
1171    {
1172        [newCodeName setStringValue: hcode];
1173        if([addCodeName itemWithTitle: hcode] != nil)
1174            [addCodeName selectItemWithTitle: hcode];
1175        else
1176            [addCodeName selectItemAtIndex: 0];
1177    }
1178    else
1179    {
1180        [addCodeName selectItemAtIndex: 0];
1181        [newCodeName setStringValue: @""];
1182    }
1183
1184    [newCodeDef setString: @""];
1185    [inheritedColorSwitch setState: NSOnState];
1186    //   [codeColorMenu selectItemAtIndex:  [codeColorMenu indexOfItemWithTag: inheritedColor]];
1187    [myColorWell setColor: [gPrefBoss realColor]];
1188
1189    [codePrompt setStringValue: @"Recode to:"];
1190    if([gPrefBoss detachedSheetValue])
1191        who = nil;
1192    else
1193        who = myWindow;
1194
1195    [NSApp beginSheet: addCodeWindow
1196       modalForWindow: who
1197	modalDelegate: self
1198       didEndSelector: @selector(addCodeDidEnd:returnCode:contextInfo:)
1199          contextInfo: nil];
1200
1201}
1202
1203-(BOOL) isOverlapped: (id) r1 and: (id) r2
1204{
1205    int b1, b2, e1, e2;
1206
1207    b1 = TAMSTART(r1);
1208    b2 = TAMSTART(r2);
1209    e1 = TAMEND(r1);
1210    e2 = TAMEND(r2);
1211
1212    if([r1 objectForKey: @"_doc"] != [r2 objectForKey: @"_doc"]) return NO;
1213    //if (r1 == r2) return NO;
1214
1215    if( b1 <= b2 && e1 <= b2) return NO;
1216    if(b1 >= e2 && e1 >= e2) return NO;
1217    return YES;
1218
1219}
1220-(NSString *) processRecodeWithOldCode: (NSString *) oldCode newCode: (NSString *) newCode onRecord: (NSString *) r1 range: (NSRange) rr
1221{
1222    BOOL pmode, q4ct;
1223    int tcnt;
1224    TAMSCharEngine *tx = [[TAMSCharEngine alloc] initWithString: r1];
1225    ctQChar *qq = [[ctQChar alloc] init];
1226    NSMutableString *newData = [NSMutableString string];
1227
1228    [tx setEscFlag: 0];
1229    [tx startSearch];
1230    tcnt = 0;
1231    q4ct = NO;
1232    //[tx setCharLocation: rr.location];
1233    if(([tx getCharLocation] <= rr.location + rr.length)
1234       && [tx getCharLocation] >= rr.location) pmode = YES; else pmode = NO;
1235       while([tx readnext: qq] != EOF)
1236       {
1237           switch([qq tokentype])
1238           {
1239               case TOKEN:
1240               case ENDTOKEN:
1241                   if( [[qq buff] isEqualToString: oldCode] == YES && ((pmode && tcnt < 2) || q4ct ==YES))
1242                   {
1243                       tcnt++;
1244                       if([qq tokentype] == TOKEN) q4ct = YES;
1245                       [qq setBuff: newCode];
1246                       [newData appendString: stringForQChar(qq, NO)];
1247                   }
1248                   else
1249                       [newData appendString: stringForQChar(qq, NO)];
1250                   break;
1251               default: [newData appendString: stringForQChar(qq, NO)];
1252
1253           };
1254           if(([tx getCharLocation] <= rr.location + rr.length)
1255              && [tx getCharLocation] >= rr.location) pmode = YES; else pmode = NO;
1256
1257       }
1258       [tx release];
1259       [qq release];
1260       return newData;
1261
1262}
1263-(NSString *) processAddcodeWithOldCode: (NSString *) oldCode newCode: (NSString *) newCode onRecord: (NSString *) r1 range: (NSRange) rr
1264{
1265    TAMSCharEngine *tx = [[TAMSCharEngine alloc] initWithString: r1];
1266    ctQChar *qq = [[ctQChar alloc] init];
1267    NSMutableString *newData = [NSMutableString string];
1268    int tcnt;
1269    BOOL pmode, q4ct;
1270    q4ct = NO;
1271    [tx setEscFlag: 0];
1272    [tx startSearch];
1273    //[tx setCharLocation: rr.location];
1274    tcnt =0;
1275    if(([tx getCharLocation] <= rr.location + rr.length)
1276       && [tx getCharLocation] >= rr.location) pmode = YES; else pmode = NO;
1277       while([tx readnext: qq] != EOF)
1278       {
1279           switch([qq tokentype])
1280           {
1281               case TOKEN:
1282               case ENDTOKEN:
1283                   if( [[qq buff] isEqualToString: oldCode] == YES && ((pmode && tcnt < 2) || q4ct))
1284                   {
1285                       if([qq tokentype] == TOKEN) q4ct = YES;
1286                       tcnt++;
1287                       [newData appendString: code2tag(newCode, (([qq tokentype] == TOKEN)? YES : NO),
1288                                                       YES, nil)];
1289                       [newData appendString: stringForQChar(qq, NO)];
1290                   }
1291                   else
1292                       [newData appendString: stringForQChar(qq, NO)];
1293                   break;
1294               default: [newData appendString: stringForQChar(qq, NO)];
1295
1296           };
1297
1298           if(([tx getCharLocation] <= rr.location + rr.length)
1299              && [tx getCharLocation] >= rr.location) pmode = YES; else pmode = NO;
1300
1301       }
1302       [tx release];
1303       [qq release];
1304       return newData;
1305
1306}
1307-(void) adjustAllToRecodeWithNewCode: (NSString *) newCode oldCode: (NSString *) oldCode keyRecord: (id) rr keyData: (NSString *) kd
1308{
1309    NSRange rrr;
1310    NSString * rstr;
1311    FORALL(backData)
1312    {
1313        int b1, b2, e1, e2, l1, l2;
1314        b1 = TAMSTART(rr);
1315        b2 = TAMSTART(temp);
1316        e1 = TAMEND(rr);
1317        e2 = TAMEND(temp);
1318        l2 = [[temp objectForKey: @"_data"] length];
1319        l1 = [kd length];
1320        if(TAMSTART(rr) == TAMSTART(temp) && TAMEND(rr) == TAMEND(temp))
1321        {
1322            [temp setObject: [[newCode copy] autorelease] forKey: @"_code"];
1323        }
1324        if([self isOverlapped: temp and: rr])
1325        {
1326            if(b1 <= b2) rrr.location = 0;
1327            else
1328                rrr.location = b1 - b2;
1329            if(e1 >= e2) rrr.length = 1+e2 - (b2 + rrr.location)  + ((l1 - (e2 - b2) > 0) ? l1 - (e2 -b2) : (e2-b2) - l1);
1330
1331            else  rrr.length = 1+e1 - (b2 + rrr.location) +
1332                ((l1 - (e2 - b2) > 0) ? l1 - (e2 -b2) : (e2-b2) - l1);
1333            rstr = [self processRecodeWithOldCode: oldCode
1334                                          newCode: newCode onRecord: [temp objectForKey: @"_data"] range: rrr];
1335            [temp setObject: rstr forKey: @"_data"];
1336        }
1337
1338    }
1339    ENDFORALL;
1340}
1341-(void) adjustAllToAddcodeWithNewCode: (NSString *) newCode oldCode: (NSString *) oldCode keyRecord: (id) rr keyData: (NSString *) kd
1342{
1343    NSRange rrr;
1344    NSString * rstr;
1345    FORALL(backData)
1346    {
1347        int b1, b2, e1, e2, l1, l2;
1348        b1 = TAMSTART(rr);
1349        b2 = TAMSTART(temp);
1350        e1 = TAMEND(rr);
1351        e2 = TAMEND(temp);
1352        l2 = [[temp objectForKey: @"_data"] length];
1353        l1 = [kd length];
1354        if([self isOverlapped: temp and: rr])
1355        {
1356            if(b1 < b2) rrr.location = 0;
1357            else
1358                rrr.location = b2 - b1;
1359            if(e2 >= e1) rrr.length = 1+b2 - (b2 + rrr.location)  + ((l1 - (e2 - b2) > 0) ? l1 - (e2 -b2) : (e2-b2) - l1);
1360            else  rrr.length = 1+e1 - (b2 + rrr.location)  + ((l1 - (e2 - b2) > 0) ? l1 - (e2 -b2) : (e2-b2) - l1);
1361            rstr = [self processAddcodeWithOldCode: oldCode
1362                                           newCode: newCode onRecord: [temp objectForKey: @"_data"] range: rrr];
1363            [temp setObject: rstr forKey: @"_data"];
1364        }
1365
1366    }
1367    ENDFORALL;
1368}
1369-(void)handleResultsDidChange: (NSNotification *) not
1370{
1371    NSDictionary *myDat = [not userInfo];
1372    if([[myDat objectForKey: @"type"] isEqualToString: @"r"] == YES)
1373    {
1374        [self adjustAllToRecodeWithNewCode:
1375            [myDat objectForKey: @"newCode"]
1376                                   oldCode: [myDat objectForKey: @"oldCode"]
1377                                 keyRecord: [myDat objectForKey: @"keyRecord"]
1378                                   keyData: [myDat objectForKey: @"keyData"]];//[[myDat objectForKey: @"keyRecord"] objectForKey: @"_data"]];
1379    }
1380    else
1381    {
1382        [self adjustAllToAddcodeWithNewCode:
1383            [myDat objectForKey: @"newCode"]
1384                                    oldCode: [myDat objectForKey: @"oldCode"]
1385                                  keyRecord: [myDat objectForKey: @"keyRecord"]
1386                                    keyData: [myDat objectForKey: @"keyData"]];
1387    }
1388
1389}
1390
1391-(void) addCodeDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
1392{
1393    NSMutableArray *myLocalRecs;
1394    id myRec;
1395    NSEnumerator *locList;
1396    NSMutableString *oldCode;
1397    NSMutableString *newData;
1398    oldCode = [NSMutableString string];
1399
1400    if(recodeFlag == 0) //this is addcode
1401    {
1402	if([markedList count])
1403	{
1404	    if(returnCode == 1)
1405	    {
1406		//Something there?
1407		if([lgNewCodeName isEqualToString: @""] == YES) return;
1408		//is it a new definition?
1409                if(lgNewCodeMode == CODEMODENEW)
1410                {
1411                    if(lgNewCodeColor == otherColor)
1412                        [gWorkBench newCode: lgNewCodeName definition: lgNewCodeDef
1413                                  realColor: lgNewRealColor];
1414                    else
1415                        [gWorkBench newCode: lgNewCodeName definition: lgNewCodeDef
1416                                      color: lgNewCodeColor];
1417                }
1418		//copy records
1419		myLocalRecs = [[NSMutableArray alloc] init];
1420		[myLocalRecs setArray: markedList];
1421
1422		//reverse sort
1423		[myLocalRecs sortUsingFunction: locationFwdComp context: nil];
1424
1425		//go through and call the main docuement
1426		locList = [myLocalRecs reverseObjectEnumerator];
1427		while(myRec = [locList nextObject])
1428		{
1429                    if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
1430                    {
1431                        if([gPrefBoss batchOpenFiles])
1432                            [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
1433                        else
1434                            [(MWFile *)[myRec objectForKey: @"_doc"] setOpenFakeFileWithWorkBench: gWorkBench];
1435                    }
1436
1437		    [[[myRec objectForKey: @"_doc"] filePointer] addCode: lgNewCodeName
1438                                                                    from: [[myRec objectForKey:@"_begin_loc"] intValue]
1439                                                                      to: [[myRec objectForKey:@"_end_loc"] intValue] from: self
1440                                                                 withDef: @""];
1441                    if([self global: @"simpleflag"])
1442                    {
1443                        NSString *rstr;
1444                        [oldCode setString: [myRec objectForKey: @"_code"]];
1445                        if([gPrefBoss guessUpdate] == NO)
1446                        {
1447                            rstr = [self processAddcodeWithOldCode: oldCode newCode: lgNewCodeName
1448                                                          onRecord: [myRec objectForKey: @"_data"] range: NSMakeRange(0, [[myRec objectForKey: @"_data"] length])];
1449
1450                            [myRec setObject: rstr
1451                                      forKey: @"_data"];
1452                        }
1453                        else
1454                        {
1455                            NSMutableDictionary *mynots = [NSMutableDictionary dictionary];
1456                            [mynots setObject: self forKey: @"origin"];
1457                            [mynots setObject: [[lgNewCodeName copy] autorelease] forKey: @"newCode"];
1458                            [mynots setObject: @"a" forKey: @"type"];
1459                            [mynots setObject: [[oldCode copy] autorelease] forKey: @"oldCode"];
1460                            [mynots setObject: myRec forKey: @"keyRecord"];
1461                            [mynots setObject: [myRec objectForKey: @"_data"]
1462                                       forKey: @"keyData"];
1463
1464
1465                            [[NSNotificationCenter defaultCenter] postNotificationName: @"TAMSResultDidChange"
1466                                                                                object: gWorkBench userInfo: mynots];
1467                            /*[self adjustAllToAddcodeWithNewCode: lgNewCodeName
1468oldCode: oldCode keyRecord: myRec];*/
1469                        }
1470                    }
1471		}
1472                if([gPrefBoss batchOpenFiles] == 0)
1473                {
1474                    locList = [myLocalRecs reverseObjectEnumerator];
1475                    while(myRec = [locList nextObject])
1476                    {
1477                        [(MWFile *)[myRec objectForKey: @"_doc"] closeFakeFile];
1478
1479                    }
1480                }
1481                [self updateRecCountAtRow];
1482                if([gPrefBoss cancelAfterAddCode] == 1)
1483                    [self doUnmarkAll: nil];
1484		//have it reload
1485		if([gPrefBoss autoReloadValue])
1486		    [self refreshResults: self];
1487                [self displaySelData];
1488	    }
1489	}
1490	else
1491	{
1492	}
1493    }
1494    else if (recodeFlag == 1)
1495    {
1496	if([markedList count])
1497	{
1498	    if(returnCode == 1)
1499	    {
1500
1501		//is there something there?
1502		if([lgNewCodeName isEqualToString: @""] == YES) return;
1503		//refresh?
1504                if(lgNewCodeMode == CODEMODENEW)
1505                {
1506                    if(lgNewCodeColor == otherColor)
1507                        [gWorkBench newCode: lgNewCodeName definition: lgNewCodeDef
1508                                  realColor: lgNewRealColor];
1509                    else
1510                        [gWorkBench newCode: lgNewCodeName definition: lgNewCodeDef
1511                                      color: lgNewCodeColor];
1512                }
1513		//copy records
1514		myLocalRecs = [[NSMutableArray alloc] init];
1515		[myLocalRecs setArray: markedList];
1516
1517		//reverse sort
1518		[myLocalRecs sortUsingFunction: locationComp context: nil];
1519
1520		//go through and call the main docuement
1521		locList = [markedList reverseObjectEnumerator];
1522		while(myRec = [locList nextObject])
1523		{
1524                    if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
1525                    {
1526                        if([gPrefBoss batchOpenFiles] == 1)
1527                            [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
1528                        else
1529                            [(MWFile *)[myRec objectForKey: @"_doc"] setOpenFakeFileWithWorkBench: gWorkBench];
1530                    }
1531
1532		    [[[myRec objectForKey: @"_doc"] filePointer] recode: lgNewCodeName
1533                                                                  first: [[myRec objectForKey:@"_begin_loc"] intValue]
1534                                                                   last: [[myRec objectForKey:@"_end_loc"] intValue] from: self
1535                                                                withDef: @""];
1536                    [oldCode setString: [myRec objectForKey: @"_code"]];
1537                    /*
1538                     This is too crude, but is the start of refreshing the actual data,
1539                     what would need to happen is have tce or some such object translate this*/
1540
1541
1542                    {
1543                        NSString *rstr;
1544                        if([gPrefBoss guessUpdate] == NO)
1545                        {
1546                            [myRec setObject: [[lgNewCodeName copy] autorelease] forKey: @"_code"];
1547                            rstr = [self processRecodeWithOldCode: oldCode newCode: lgNewCodeName
1548                                                         onRecord: [myRec objectForKey: @"_data"] range: NSMakeRange(0, [[myRec objectForKey: @"_data"] length])];
1549
1550                            [myRec setObject: rstr
1551                                      forKey: @"_data"];
1552                        }
1553                        else
1554                        {
1555                            NSMutableDictionary *mynots = [NSMutableDictionary dictionary];
1556                            [mynots setObject: self forKey: @"origin"];
1557                            [mynots setObject: [[lgNewCodeName copy]autorelease] forKey: @"newCode"];
1558                            [mynots setObject: @"r" forKey: @"type"];
1559                            [mynots setObject: [[oldCode copy] autorelease] forKey: @"oldCode"];
1560                            [mynots setObject: myRec forKey: @"keyRecord"];
1561                            [mynots setObject: [[[myRec objectForKey: @"_data"] copy] autorelease] forKey: @"keyData"];
1562
1563                            /*[self adjustAllToRecodeWithNewCode: lgNewCodeName
1564oldCode: oldCode keyRecord: myRec];*/
1565
1566                            [[NSNotificationCenter defaultCenter] postNotificationName: @"TAMSResultDidChange"
1567                                                                                object: gWorkBench userInfo: mynots];
1568                        }
1569                    }
1570		}
1571                if([gPrefBoss batchOpenFiles] == 0)
1572                {
1573                    locList = [myLocalRecs reverseObjectEnumerator];
1574                    while(myRec = [locList nextObject])
1575                    {
1576                        [(MWFile *)[myRec objectForKey: @"_doc"] closeFakeFile];
1577
1578                    }
1579                }
1580		//have it reload
1581                [self updateRecCountAtRow];
1582                if([gPrefBoss cancelAfterRecode] == 1)
1583                    [self doUnmarkAll: nil];
1584		if([gPrefBoss autoReloadValue])
1585		    [self refreshResults: self];
1586                [self displaySelData];
1587                [myLocalRecs autorelease];
1588	    }
1589	}
1590	else
1591	{
1592	}
1593    }
1594    else if (recodeFlag == 2) //add root class
1595    {
1596	if([markedList count])
1597	{
1598	    if(returnCode == 1)
1599	    {
1600                NSMutableString *myNewPrefix;
1601                int m, i;
1602		//is there something there?
1603		if([lgNewCodeName isEqualToString: @""] == YES) return;
1604                myNewPrefix = [[NSMutableString alloc] initWithString: lgNewCodeName];
1605                m = [myNewPrefix length];
1606
1607                trimNSS(myNewPrefix);
1608
1609                for(i = m -1; i >= 0; i--)
1610                {
1611                    if([myNewPrefix characterAtIndex: i] == '>')
1612                        [myNewPrefix deleteCharactersInRange: NSMakeRange(i,1)];
1613                    else
1614                        break;
1615                }
1616
1617                {
1618                    if(lgNewCodeColor == otherColor)
1619                        [gWorkBench newCode: myNewPrefix definition: @""
1620                                  realColor: lgNewRealColor];
1621                    else
1622                        [gWorkBench newCode: myNewPrefix definition: @""
1623                                      color: lgNewCodeColor];
1624                }
1625		//refresh?
1626		//copy records
1627		myLocalRecs = [[NSMutableArray alloc] init];
1628		[myLocalRecs setArray: markedList];
1629
1630		//reverse sort
1631		[myLocalRecs sortUsingFunction: locationComp context: nil];
1632		//go through and call the main docuement
1633		locList = [markedList reverseObjectEnumerator];
1634		while(myRec = [locList nextObject])
1635		{
1636                    NSString *myHierCode;
1637                    if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
1638                    {
1639                        if([gPrefBoss batchOpenFiles] == 1)
1640                            [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
1641                        else
1642                            [(MWFile *)[myRec objectForKey: @"_doc"] setOpenFakeFileWithWorkBench: gWorkBench];
1643                    }
1644                    myHierCode = [NSString stringWithFormat: @"%@>%@", myNewPrefix, [myRec objectForKey: @"_code"]];
1645                    [myHierCode retain];
1646		    [[[myRec objectForKey: @"_doc"] filePointer] recode: myHierCode
1647                                                                  first: [[myRec objectForKey:@"_begin_loc"] intValue]
1648                                                                   last: [[myRec objectForKey:@"_end_loc"] intValue] from: self
1649                                                                withDef: @""];
1650                    [oldCode setString: [myRec objectForKey: @"_code"]];
1651                    /*
1652                     This is too crude, but is the start of refreshing the actual data,
1653                     what would need to happen is have tce or some such object translate this*/
1654
1655
1656                    {
1657                        NSString *rstr;
1658                        if([gPrefBoss guessUpdate] == NO)
1659                        {
1660                            [myRec setObject: [[myHierCode copy] autorelease] forKey: @"_code"];
1661                            rstr = [self processRecodeWithOldCode: oldCode newCode: myHierCode
1662                                                         onRecord: [myRec objectForKey: @"_data"] range: NSMakeRange(0, [[myRec objectForKey: @"_data"] length])];
1663
1664                            [myRec setObject: rstr
1665                                      forKey: @"_data"];
1666                        }
1667                        else
1668                        {
1669                            NSMutableDictionary *mynots = [NSMutableDictionary dictionary];
1670                            [mynots setObject: self forKey: @"origin"];
1671                            [mynots setObject: [[myHierCode copy]autorelease] forKey: @"newCode"];
1672                            [mynots setObject: @"r" forKey: @"type"];
1673                            [mynots setObject: [[oldCode copy] autorelease] forKey: @"oldCode"];
1674                            [mynots setObject: myRec forKey: @"keyRecord"];
1675                            [mynots setObject: [[[myRec objectForKey: @"_data"] copy] autorelease] forKey: @"keyData"];
1676
1677                            /*[self adjustAllToRecodeWithNewCode: lgNewCodeName
1678oldCode: oldCode keyRecord: myRec];*/
1679
1680                            [[NSNotificationCenter defaultCenter] postNotificationName: @"TAMSResultDidChange"
1681                                                                                object: gWorkBench userInfo: mynots];
1682                        }
1683                    }
1684                    [myHierCode autorelease];
1685		}
1686                if([gPrefBoss batchOpenFiles] == 0)
1687                {
1688                    locList = [myLocalRecs reverseObjectEnumerator];
1689                    while(myRec = [locList nextObject])
1690                    {
1691                        [(MWFile *)[myRec objectForKey: @"_doc"] closeFakeFile];
1692
1693                    }
1694                }
1695		//have it reload
1696                [self updateRecCountAtRow];
1697                if([gPrefBoss cancelAfterRecode] == 1)
1698                    [self doUnmarkAll: nil];
1699		if([gPrefBoss autoReloadValue])
1700		    [self refreshResults: self];
1701                [self displaySelData];
1702                [myNewPrefix release];
1703                [myLocalRecs autorelease];
1704	    }
1705	}
1706	else
1707	{
1708	}
1709    }
1710    else if (recodeFlag == 3) //del root code
1711    {
1712	if([markedList count])
1713	{
1714	    if(returnCode == 1)
1715	    {
1716                NSMutableString *oldDataCode;
1717                int m, i;
1718                int clevel;
1719		//is there something there?
1720                clevel = [delRootLevels intValue];
1721                if(clevel <= 0) return;
1722
1723                oldDataCode = [[NSMutableString alloc] init];
1724		//refresh?
1725		//copy records
1726		myLocalRecs = [[NSMutableArray alloc] init];
1727		[myLocalRecs setArray: markedList];
1728
1729		//reverse sort
1730		[myLocalRecs sortUsingFunction: locationComp context: nil];
1731		//go through and call the main docuement
1732		locList = [markedList reverseObjectEnumerator];
1733		while(myRec = [locList nextObject])
1734		{
1735                    int oclevel;
1736                    NSString *myHierCode;
1737                    if([(MWFile *)[myRec objectForKey: @"_doc"] open] == NO)
1738                    {
1739                        if([gPrefBoss batchOpenFiles] == 1)
1740                            [gWorkBench openMWFile: [myRec objectForKey: @"_doc"] type: SOURCETYPE];
1741                        else
1742                            [(MWFile *)[myRec objectForKey: @"_doc"] setOpenFakeFileWithWorkBench: gWorkBench];
1743                    }
1744                    [oldDataCode setString: [myRec objectForKey: @"_code"]];
1745                    oclevel = [oldDataCode numberOfCodeComponents];
1746                    if(clevel < oclevel)
1747                        myHierCode = [oldDataCode lastCodeComponents: oclevel - clevel];
1748                    else
1749                        myHierCode = [oldDataCode lastCodeComponent];
1750                    [myHierCode retain];
1751		    [[[myRec objectForKey: @"_doc"] filePointer] recode: myHierCode
1752                                                                  first: [[myRec objectForKey:@"_begin_loc"] intValue]
1753                                                                   last: [[myRec objectForKey:@"_end_loc"] intValue] from: self
1754                                                                withDef: @""];
1755                    [oldCode setString: [myRec objectForKey: @"_code"]];
1756                    /*
1757                     This is too crude, but is the start of refreshing the actual data,
1758                     what would need to happen is have tce or some such object translate this*/
1759
1760
1761                    {
1762                        NSString *rstr;
1763                        if([gPrefBoss guessUpdate] == NO)
1764                        {
1765                            [myRec setObject: [[lgNewCodeName copy] autorelease] forKey: @"_code"];
1766                            rstr = [self processRecodeWithOldCode: oldDataCode newCode: myHierCode
1767                                                         onRecord: [myRec objectForKey: @"_data"] range: NSMakeRange(0, [[myRec objectForKey: @"_data"] length])];
1768
1769                            [myRec setObject: rstr
1770                                      forKey: @"_data"];
1771                        }
1772                        else
1773                        {
1774                            NSMutableDictionary *mynots = [NSMutableDictionary dictionary];
1775                            [mynots setObject: self forKey: @"origin"];
1776                            [mynots setObject: [[myHierCode copy]autorelease] forKey: @"newCode"];
1777                            [mynots setObject: @"r" forKey: @"type"];
1778                            [mynots setObject: [[oldDataCode copy] autorelease] forKey: @"oldCode"];
1779                            [mynots setObject: myRec forKey: @"keyRecord"];
1780                            [mynots setObject: [[[myRec objectForKey: @"_data"] copy] autorelease] forKey: @"keyData"];
1781
1782                            /*[self adjustAllToRecodeWithNewCode: lgNewCodeName
1783oldCode: oldCode keyRecord: myRec];*/
1784
1785                            [[NSNotificationCenter defaultCenter] postNotificationName: @"TAMSResultDidChange"
1786                                                                                object: gWorkBench userInfo: mynots];
1787                        }
1788                    }
1789                    [myHierCode autorelease];
1790		}
1791                if([gPrefBoss batchOpenFiles] == 0)
1792                {
1793                    locList = [myLocalRecs reverseObjectEnumerator];
1794                    while(myRec = [locList nextObject])
1795                    {
1796                        [(MWFile *)[myRec objectForKey: @"_doc"] closeFakeFile];
1797
1798                    }
1799                }
1800		//have it reload
1801                [self updateRecCountAtRow];
1802                if([gPrefBoss cancelAfterRecode] == 1)
1803                    [self doUnmarkAll: nil];
1804		if([gPrefBoss autoReloadValue])
1805		    [self refreshResults: self];
1806                [self displaySelData];
1807                [oldDataCode release];
1808                [myLocalRecs autorelease];
1809	    }
1810	}
1811	else
1812	{
1813	}
1814    }
1815
1816}
1817-(IBAction) doAddCode: (id) sender
1818{
1819    NSArray *clist;
1820    NSWindow *who;
1821    NSString *hcode;
1822
1823    if(![markedList count]) return;
1824    DIRTYWARN;
1825    hcode = [[markedList objectAtIndex: 0] objectForKey: @"_code"];
1826    //delete the menu items
1827    if([addCodeName numberOfItems])
1828        [addCodeName removeAllItems];
1829    //get a fresh list
1830    //add new
1831    //[addCodeName addItemWithTitle: @"New"];
1832    clist = [gWorkBench getHotCodeList];
1833    [addCodeName addItemsWithTitles: clist];
1834    [addCodeName selectItemAtIndex: 0];
1835    recodeFlag = 0;
1836    [codePrompt setStringValue: @"Code to add:"];
1837    if([self global: @"simpleflag"])
1838    {
1839	[newCodeName setStringValue: hcode];
1840        if([addCodeName itemWithTitle: hcode] != nil)
1841            [addCodeName selectItemWithTitle: hcode];
1842        else
1843            [addCodeName selectItemAtIndex: 0];
1844    }
1845    else
1846    {
1847	[newCodeName setStringValue: @""];
1848        [addCodeName selectItemAtIndex: 0];
1849
1850    }
1851    [newCodeDef setString: @""];
1852    [inheritedColorSwitch setState: NSOnState];
1853    //        [codeColorMenu selectItemAtIndex:
1854    //           [codeColorMenu indexOfItemWithTag: inheritedColor]];
1855    if([gPrefBoss detachedSheetValue])
1856        who = nil;
1857    else
1858        who = myWindow;
1859
1860
1861    [NSApp beginSheet: addCodeWindow
1862       modalForWindow: who
1863	modalDelegate: self
1864       didEndSelector: @selector(addCodeDidEnd:returnCode:contextInfo:)
1865          contextInfo: nil];
1866
1867    //return if nothing there
1868    //copy the records
1869    //reverse sort them
1870    //go through and call the main document
1871    //have it add a code
1872
1873}
1874
1875-(IBAction) cancelAddRoot: (id) sender
1876{
1877    [addRootPane orderOut: sender];
1878    [NSApp endSheet: addRootPane returnCode: 0];
1879
1880}
1881-(IBAction) okAddRoot: (id) sender
1882{
1883    if([addRootInherited state] == NSOnState)
1884        lgNewCodeColor = inheritedColor;
1885    else
1886        lgNewCodeColor = otherColor;
1887    //lgNewCodeColor = [[codeColorMenu selectedItem] tag];
1888    lgNewRealColor = [addRootColor color];
1889    [lgNewCodeName setString: [addRootName stringValue]];
1890    [addRootPane orderOut: sender];
1891    [NSApp endSheet: addRootPane returnCode: 1];
1892
1893}
1894-(IBAction) toggleAddRootColor: (id) sender
1895{
1896    [addRootInherited setState: NSOffState];
1897}
1898-(IBAction) doAddRootCode: (id) sender
1899{
1900    NSArray *clist;
1901    NSWindow *who;
1902    NSString *hcode;
1903
1904    if(![markedList count]) return;
1905    if(![self global: @"simpleflag"])
1906    {
1907        NSWARNING(@"Add root code only works with simple searches.");
1908        return;
1909    }
1910    recodeFlag = 2;
1911
1912    [addRootName setStringValue: @""];
1913    [addRootInherited setState: NSOnState];
1914    //        [codeColorMenu selectItemAtIndex:
1915    //           [codeColorMenu indexOfItemWithTag: inheritedColor]];
1916    if([gPrefBoss detachedSheetValue])
1917        who = nil;
1918    else
1919        who = myWindow;
1920
1921
1922    [NSApp beginSheet: addRootPane
1923       modalForWindow: who
1924	modalDelegate: self
1925       didEndSelector: @selector(addCodeDidEnd:returnCode:contextInfo:)
1926          contextInfo: nil];
1927
1928    //return if nothing there
1929    //copy the records
1930    //reverse sort them
1931    //go through and call the main document
1932    //have it add a code
1933
1934}
1935-(IBAction) cancelDelRoot: (id) sender
1936{
1937    [delRootPane orderOut: sender];
1938    [NSApp endSheet: delRootPane returnCode: 0];
1939
1940}
1941-(IBAction) okDelRoot: (id) sender
1942{
1943    [delRootPane orderOut: sender];
1944    [NSApp endSheet: delRootPane returnCode: 1];
1945
1946}
1947
1948-(IBAction) doDelRootCode: (id) sender
1949{
1950    NSArray *clist;
1951    NSWindow *who;
1952    NSString *hcode;
1953
1954    if(![markedList count]) return;
1955    if(![self global: @"simpleflag"])
1956    {
1957        NSWARNING(@"Delete root code only works with simple searches.");
1958        return;
1959    }
1960    recodeFlag = 3;
1961
1962    [delRootLevels setStringValue: @"1"];
1963    //        [codeColorMenu selectItemAtIndex:
1964    //           [codeColorMenu indexOfItemWithTag: inheritedColor]];
1965    if([gPrefBoss detachedSheetValue])
1966        who = nil;
1967    else
1968        who = myWindow;
1969
1970
1971    [NSApp beginSheet: delRootPane
1972       modalForWindow: who
1973	modalDelegate: self
1974       didEndSelector: @selector(addCodeDidEnd:returnCode:contextInfo:)
1975          contextInfo: nil];
1976
1977    //return if nothing there
1978    //copy the records
1979    //reverse sort them
1980    //go through and call the main document
1981    //have it add a code
1982
1983}
1984
1985-(BOOL) isMarked: (int) row
1986{
1987    if([markedList indexOfObject: [myData objectAtIndex: row]] == NSNotFound)
1988	return NO;
1989    else return YES;
1990}
1991
1992-(BOOL) isMarkedRecord: (id) theRecord
1993{
1994    if([markedList indexOfObject: theRecord] == NSNotFound)
1995	return NO;
1996    else return YES;
1997}
1998
1999-(void) printShowingPrintPanel: (BOOL) flag
2000   //-(IBAction) printDocument: (id) sender
2001   //-(IBAction) print: (id) Sender
2002{
2003    NSPrintInfo *printInfo = [self printInfo];
2004    NSPrintOperation *printOp;
2005    [printInfo setOrientation: NSLandscapeOrientation];
2006    [printInfo setHorizontalPagination: NSFitPagination];
2007    printOp = [NSPrintOperation printOperationWithView: theResults
2008                                             printInfo: printInfo];
2009    [printOp setShowPanels: YES];//flag];
2010        [printOp runOperation];
2011}
2012
2013
2014- (NSString *)windowNibName {
2015    // Implement this to return a nib to load OR implement -makeWindowControllers to manually create your controllers.
2016    return @"myPanedResults";
2017}
2018-(NSMutableArray *) arrayFromSubset: (NSArray *) who
2019{
2020    int n;
2021    NSMutableArray *newArr = [[NSMutableArray alloc] init];
2022
2023    FORALL(who)
2024    {
2025        if((n = [backData indexOfObject: temp]) != NSNotFound)
2026        {
2027
2028            [newArr addObject: [NSString stringWithFormat: @"%d", n]];
2029        }
2030    }
2031    ENDFORALL;
2032    return newArr;
2033
2034}
2035- (NSData *)dataRepresentationOfType:(NSString *)type {
2036    // Implement to provide a persistent data representation of your document OR remove this and implement the file-wrapper or file path based save methods.
2037    NSMutableData *dd;
2038
2039    int first;
2040    int ab;
2041    int cnt;
2042    MWFile *theDPtr;
2043    NSMutableArray *nameList, *fixedDataArray, *rootArray, *nKeys;
2044    NSMutableDictionary *nSets;
2045    unichar newLineChar;
2046    dd = [[NSMutableData alloc] init];
2047#ifdef USESXML
2048
2049    if([type isEqualToString: @"XML TAMS Result"])
2050    {
2051        return [self keyedDataRepresentation];
2052    }
2053#endif
2054    if([type isEqualToString: @"TAMS Result"])
2055    {
2056        rootArray = [[NSMutableArray alloc] init];
2057        if(gWorkBench)
2058        {
2059            ab = [gWorkBench absPath];
2060        }
2061        else
2062            ab = ABSPATHMODE;
2063        //1. save the version
2064        [rootArray addObject: @"10"];
2065        FORALL(fileList)
2066        {
2067            if([temp hasFile] == NO)
2068            {
2069                NSWARNING(@"Cannot save in TAMS format until all source files have been saved.");
2070                return nil;
2071            }
2072        }
2073        ENDFORALL;
2074
2075        //2. save the globals
2076        [rootArray addObject: [myGlobals getGlobals]];
2077        //3. save the file list
2078        nameList = [[NSMutableArray alloc] init];
2079        FORALL(fileList)
2080        {
2081            [nameList addObject: [[(MWFile *) temp name] copy]];
2082        }
2083        ENDFORALL;
2084        [rootArray addObject: nameList];
2085
2086        //4. save the data
2087        fixedDataArray = [[NSMutableArray alloc] init];
2088        FORALL(backData)
2089        {
2090            NSMutableDictionary *what;
2091            MWFile *myObj;
2092
2093            what = [[NSMutableDictionary alloc] init];
2094            [what addEntriesFromDictionary: temp];
2095            myObj = [temp objectForKey: @"_doc"];
2096            [what setObject: [[myObj name] copy] forKey: @"_doc"];
2097            [fixedDataArray addObject: what];
2098        }
2099        ENDFORALL;
2100        [rootArray addObject: fixedDataArray];
2101
2102        //5. save the visible data
2103        [rootArray addObject: [self arrayFromSubset: myData]];
2104
2105        //6. save the named sets
2106        nSets = [[NSMutableDictionary alloc] init];
2107        nKeys = [namedSelDict allKeys];
2108        FORALL(nKeys)
2109        {
2110            [nSets setObject: [self arrayFromSubset:
2111                [namedSelDict objectForKey: temp]] forKey: temp];
2112        }
2113        ENDFORALL;
2114        [rootArray addObject: nSets];
2115        //7. the limit string
2116        if(limitString)
2117            [rootArray addObject: limitString];
2118        else
2119            [rootArray addObject: @""];
2120        //8. the list of columns
2121        [rootArray addObject: colList];
2122        //9. the current string
2123        [rootArray addObject: [[[limitField stringValue] copy] autorelease]];
2124        //10. save the coder
2125        [rootArray addObject: [[codersString copy] autorelease]];
2126        //11. save autosets
2127        [rootArray addObject: [self autoSets]];
2128        //12. save the selected row
2129        [rootArray addObject: [NSNumber numberWithInt: [theResults selectedRow]]];
2130        //13. save marked list
2131        [rootArray addObject: [self arrayFromSubset: markedList]];
2132        //14. save summary reports
2133        [rootArray addObject: summReports];
2134        //15. save date string
2135        [rootArray addObject: [[dfString copy] autorelease]];
2136        [rootArray addObject: [NSNumber numberWithInt: dfIndex]];
2137        //16. save auto history
2138        [rootArray addObject: autoHistory];
2139        [rootArray addObject: [[autoHistoryStart copy] autorelease]];
2140        //17. save media dictionary
2141        [rootArray addObject: [[mediaDict copy] autorelease]];
2142        dd = [NSArchiver archivedDataWithRootObject: rootArray];
2143        return dd;
2144    }
2145
2146#ifdef HIER
2147    if([type isEqualToString: @"HierFormat1"] == YES)
2148    {
2149	//make an array
2150	unichar retChar;
2151	NSMutableArray aaa = [[NSMutableArray alloc] init];
2152	NSMutableString sss = [[NSMutableString alloc] init];
2153	if([gPrefBoss macNLValue])
2154	{
2155	    retchar = '\n';
2156	    newLineChar = '\r';
2157	}
2158	else
2159	{
2160	    retchar = '\r';
2161	    newLineChar = '\n';
2162	}
2163	if([myData count] == 0) {[dd release]; [aaa release]; return nil;}
2164	[aaa addObjectsFromArray: myData];
2165	//sort it
2166	[aaa sortUsingFunction: stringComp context: @"_code"];
2167
2168	//set the first tag
2169	[sss setString: [[myData objectAtIndex: 0] objectForKey @"_code"]];
2170	//print the head of the tree
2171	DATASTRING(dd, limitString);
2172	DATACHAR(dd, newLineChar);
2173	//print the first tag
2174	DATATAB(dd);
2175	DATASTRING(dd, sss);
2176	//loop til end of array
2177	FORALL(aaa)
2178	{
2179	    NSMutableString *thisTag = [[NSMutableString alloc] init];
2180	    //set this tag
2181	    [thisTag setString: [temp objectForKey: @"_code"]];
2182
2183	    //if this tag is != to last tag
2184	    if([thisTag isEqualToString: sss] == NO)
2185	    {
2186		//print new tag
2187		DATATAB(dd);
2188		DATASTRING(dd, thisTag);
2189		[sss setString: thisTag];
2190	    }
2191	    //print the data
2192	    DATATAB(dd);DATATAB(dd);
2193	    DATASTRING(dd, [temp objectForKey: @"_data"]);
2194	    //add all the extra stuff
2195	    DATACHAR(dd, '['); DATASTRING(dd, thisTab); DATACHAR(dd, ']');
2196	    //and a return
2197	    DATACHAR(dd, newLineChar);
2198	}
2199    }
2200    else
2201#endif
2202#ifdef XML
2203	;
2204    if([type isEqualToString: @"XML"] == YES)
2205    {
2206	DATASTRING(dd,@"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
2207	DATANL(dd);
2208	DATASTRING(dd,@"<tamsdata>"); DATANL(dd);
2209	cnt = 0;
2210	FORALL(myData)
2211	{
2212	    id key;
2213	    id ans;
2214	    NSEnumerator *ns;
2215	    NSMutableString *sss=[[NSMutableString alloc] init];
2216
2217            // DATASTRING(dd, [[NSNumber numberWithInt: cnt] stringValue]);
2218	    cnt++;
2219	    ns = [colList objectEnumerator];
2220	    DATATAB(dd); DATASTRING(dd, @"<tamsrecord recnum=\"");
2221	    DATASTRING(dd, [[NSNumber numberWithInt: cnt] stringValue]);
2222	    DATASTRING(dd,@"\">");DATANL(dd);
2223	    while(key = [ns nextObject])
2224	    {
2225		ans = [temp objectForKey: key];
2226		//if([ans length] == 0) continue;
2227		DATATAB(dd);
2228		DATATAB(dd);
2229		if([key isEqualToString: @"_begin_loc"] == YES)
2230		{
2231		    DATASTRING(dd, @"<");DATASTRING(dd, key); DATASTRING(dd, @">");
2232		    DATASTRING(dd, ans);
2233		    DATASTRING(dd, @"</");DATASTRING(dd, key); DATASTRING(dd, @">");DATANL(dd);
2234
2235		    DATATAB(dd);
2236		    DATATAB(dd);
2237		    DATASTRING(dd, @"<_end_loc>");
2238		    DATASTRING(dd, [temp objectForKey: @"_end_loc"]);
2239		    DATASTRING(dd, @"</_end_loc>");DATANL(dd);
2240
2241		    //do the document stuff here
2242		}
2243                else if([key isEqualToString: @"_line_number"] == YES)
2244                {
2245		    DATASTRING(dd, @"<");DATASTRING(dd, key); DATASTRING(dd, @">");
2246		    DATASTRING(dd, ans);
2247		    DATASTRING(dd, @"</");DATASTRING(dd, key); DATASTRING(dd, @">");DATANL(dd);
2248
2249                }
2250                else if([key isEqualToString: @"_doc"] == YES)
2251                {
2252		    theDPtr = [temp objectForKey: @"_doc"];
2253
2254		    DATATAB(dd);
2255		    DATATAB(dd);
2256		    DATASTRING(dd, @"<_document>");
2257		    if([gWorkBench mwFileExists: (MWFile*)theDPtr] == YES)
2258		    {
2259                        if([theDPtr hasFile] == YES)
2260                            DATASTRING(dd, [theDPtr path]);
2261                        else
2262                            DATASTRING(dd, [theDPtr name]);
2263		    }
2264		    else
2265		    {
2266			DATASTRING(dd,@"???");
2267		    }
2268		    DATASTRING(dd, @"</_document>");DATANL(dd);
2269
2270                }
2271		else
2272		{
2273		    [sss setString: ans];
2274                    if([sss length] > 0)
2275                        [sss replaceOccurrencesOfString: @">" withString: @":" options: NSCaseInsensitiveSearch range: NSMakeRange(0, [sss length])];
2276		    DATASTRING(dd, @"<");DATASTRING(dd, key); DATASTRING(dd, @">");
2277                    if([key isEqualToString: @"_data"] == YES)
2278                    {
2279                        //this just inserts the line number and an escaped tab if appropriate
2280                        NSNumber * what;
2281
2282                        what = [temp objectForKey: @"_line_number"];
2283                        if(what != nil)
2284                        {
2285                            if([what intValue] > 0 && [gPrefBoss TAScanForLN] == 1)
2286                            {
2287                                DATASTRING(dd, what);
2288                                DATASTRING(dd, @"\\t");
2289                            }
2290                        }
2291                    }
2292
2293                    DATASTRING(dd, sss);
2294                    DATASTRING(dd, @"</");DATASTRING(dd, key); DATASTRING(dd, @">");DATANL(dd);
2295
2296		}
2297	    }
2298	    [sss release];
2299
2300	    DATATAB(dd); DATASTRING(dd, @"</tamsrecord>");DATANL(dd);
2301	}
2302	ENDFORALL;
2303	DATASTRING(dd,@"</tamsdata>"); DATANL(dd);
2304
2305    }
2306    else
2307#endif
2308        //This is text
2309    {
2310	if([gPrefBoss macNLValue])
2311	    newLineChar = '\r';
2312	else
2313	    newLineChar = '\n';
2314	first = 1;
2315	cnt = 1;
2316	if([myData count] == 0) {[dd release]; return nil;}
2317	//write the headers
2318	if([self global: @"headerflag"])
2319	{
2320	    DATACHAR(dd, '#');
2321	    FORALL(colList)
2322	    {
2323		DATACHAR(dd,'\t');
2324		DATASTRING(dd, temp);
2325	    }
2326	    ENDFORALL;
2327	    DATATAB(dd);
2328	    DATASTRING(dd, @"_end_loc");
2329	    DATACHAR(dd, newLineChar);
2330	}
2331
2332	FORALL(myData)
2333	{
2334	    id key;
2335	    id ans;
2336	    NSEnumerator *ns;
2337
2338	    DATASTRING(dd, [[NSNumber numberWithInt: cnt] stringValue]);
2339	    cnt++;
2340	    ns = [colList objectEnumerator];
2341	    while(key = [ns nextObject])
2342	    {
2343		DATATAB(dd);
2344		ans = [temp objectForKey: key];
2345		if([key isEqualToString: @"_data"] == YES)
2346                {
2347                    //this just inserts the line number and an escaped tab if appropriate
2348                    NSNumber * what;
2349
2350                    what = [temp objectForKey: @"_line_number"];
2351                    if(what != nil)
2352                    {
2353                        if([what intValue] > 0 && [gPrefBoss TAScanForLN] == 1)
2354                        {
2355                            DATASTRING(dd, what);
2356                            DATASTRING(dd, @"\\t");
2357                        }
2358                    }
2359                }
2360		if([key isEqualToString: @"_begin_loc"] == YES)
2361		{
2362		    DATASTRING(dd, ans /*[ans stringValue] */);
2363		    DATATAB(dd);
2364		    DATASTRING(dd, [temp objectForKey: @"_end_loc"] );
2365		    //do the document stuff here
2366		}
2367                else if( [key isEqualToString: @"_line_number"] == YES)
2368                {
2369		    DATASTRING(dd, ans /*[ans stringValue]*/);
2370
2371                }
2372                else if([key isEqualToString: @"_doc"] == YES)
2373                {
2374		    theDPtr = [temp objectForKey: @"_doc"];
2375		    if([gWorkBench mwFileExists: (MWFile *)theDPtr] == YES)
2376		    {
2377                        if([(MWFile *) theDPtr hasFile] == YES)
2378                        {
2379                            DATASTRING(dd, [theDPtr path]);
2380                        }
2381                        else
2382                        {
2383                            DATASTRING(dd, [theDPtr name]);
2384                        }
2385
2386		    }
2387		    else
2388		    {
2389			DATASTRING(dd,@"???");
2390		    }
2391
2392                }
2393		else
2394		{
2395		    DATASTRING(dd, ans);
2396
2397		}
2398	    }
2399	    DATACHAR(dd, newLineChar);;
2400	}
2401	ENDFORALL;
2402    }
2403    //[myWindow setDocumentEdited: NO];
2404    //[self updateChangeCount: NSChangeCleared];
2405
2406    [dd retain];
2407    return dd;
2408}
2409/*
2410 - (void)document:(NSDocument *)doc didSave:(BOOL)didSave contextInfo:(void *)contextInfo
2411 {
2412     if(didSave == YES)
2413     {
2414         [myWindow setDocumentEdited: NO];
2415         [self updateChangeCount: NSChangeCleared];
2416	 NSLog(@"result name $@\n",[self fileName]);
2417         //[self autorelease];
2418     }
2419
2420
2421 }
2422 */
2423-(IBAction) niceClose: (id) Sender
2424{
2425    [myWindow performClose: self];
2426}
2427
2428-(void) setTitleFromFile
2429{
2430    if([[self getMWFile] hasFile])
2431    {
2432        [myWindow setTitle: [[self getMWFile] name]];
2433    }
2434}
2435
2436-(void) willClose
2437{
2438    // [self saveDocumentWithDelegate: self didSaveSelector:
2439    //    @selector(document:didSave:contextInfo:) contextInfo:(void *)nil];
2440    if(gWorkBench)
2441    {
2442        if([self fileName])
2443        {
2444            [[self getMWFile] setOpenFile: self];
2445            [[self getMWFile] setHasFile: YES];
2446        }
2447        else
2448        {
2449            [[self getMWFile] setOpen: NO];
2450            [[self getMWFile] setHasFile: NO];
2451        }
2452    }
2453    if(gWorkBench){
2454        if([[self getMWFile] hasFile] == NO)
2455        {
2456            [[self getMWFile] setOpen: NO];
2457            [gWorkBench unregisterResult: [self getMWFile]];
2458            gWorkBench = nil;
2459            //should release it as well
2460        }
2461        else
2462        {
2463            [[self getMWFile] setOpen: NO];
2464        }
2465    }
2466    else
2467        [[self getMWFile] setOpen: NO];
2468
2469    //[self disconnect];
2470    [[NSNotificationCenter defaultCenter] removeObserver: self name: @"TAMSResultDidChange" object: nil ];
2471
2472    ;
2473}
2474
2475- (void)windowWillClose:(NSNotification *)aNotification
2476{
2477#if CLOSEBUG
2478#else
2479    [self willClose];
2480#endif
2481}
2482
2483-(void)handleAnEOF: (MWFile *) mf
2484{
2485    NSString *ss;
2486    [self clearComments];
2487    [self setCurrMWFile: mf];
2488    if([self global: @"sectionsearch"] && ([gWorkBench isInitFile: mf] == YES))
2489    {
2490        [[tce ctRunVault] removeAllObjects];
2491    }
2492
2493    if([self global: @"eofIsEndFlag"] && ([gWorkBench isInitFile: mf] == NO))
2494        [self handleEnd: NO flush: NO];
2495    if(mf)
2496        ss = [NSString stringWithFormat: @"%@ has unterminated coded passages", [mf name]];
2497    else ss = [NSString stringWithString: @"There are unterminated coded passages"];
2498
2499    [tce ctDelAllZones];
2500
2501    if([self global: @"zapuniversal"]) //([gPrefBoss zapUnivValue])
2502    {
2503        int i, n;
2504        NSArray *who;
2505        who = [univVault allKeys];
2506        n = [who count];
2507        for(i = 0; i < n; i++)
2508        {
2509
2510            [univVault setObject: @"" forKey: [who objectAtIndex: i]];
2511        }
2512    }
2513
2514    FORALL([tce ctRunVault])
2515    {
2516        if([temp openRun])
2517        {
2518            [tce ctCloseAllOpenRuns];
2519            if([self global: @"sectionsearch"] == YES && [gWorkBench isInitFile: mf] == YES)
2520                ; //don't do anything
2521            else
2522                NSWARNING(ss);//@"There are unterminated coded passages");
2523                break;
2524	}
2525    }
2526    ENDFORALL;
2527    SETGLOBAL(@"lastRepeat", 0);
2528    /*
2529     NSWARNING(ss);
2530     //NSWARNING(@"You have unterminated coded passages");
2531
2532     [self handleEnd: NO flush: YES]; */
2533
2534}
2535
2536
2537-(void)handleEachEOF: (NSNotification *)anote
2538{
2539    NSString *ss;
2540
2541    if([self global: @"sectionsearch"] && ([gWorkBench isInitFile: [anote object]] == YES))
2542    {
2543	[[tce ctRunVault] removeAllObjects];
2544    }
2545
2546    if([self global: @"eofIsEndFlag"] && ([gWorkBench isInitFile: [anote object]] == NO))
2547	[self handleEnd: NO flush: NO];
2548    [self clearComments];
2549
2550    if([anote object])
2551        ss = [NSString stringWithFormat: @"%@ has unterminated coded passages", [[anote object] name]];
2552    else ss = [NSString stringWithString: @"There are unterminated coded passages"];
2553
2554    [tce ctDelAllZones];
2555    if([self global: @"skipinnertopofdoc"] == 0)
2556        innerRFlag = 1;
2557    else
2558        innerRFlag = 0;
2559    [self clearComments];
2560    if([self global: @"zapuniversal"]) //([gPrefBoss zapUnivValue])
2561    {
2562        int i, n;
2563        NSArray *who;
2564        who = [univVault allKeys];
2565        n = [who count];
2566        for(i = 0; i < n; i++)
2567        {
2568
2569            [univVault setObject: @"" forKey: [who objectAtIndex: i]];
2570        }
2571    }
2572
2573    FORALL([tce ctRunVault])
2574    {
2575	if([temp openRun])
2576	{
2577	    [tce ctCloseAllOpenRuns];
2578            if([self global: @"sectionsearch"] == YES && [gWorkBench isInitFile: [anote object]] == YES)
2579                ; //don't do anything
2580            else
2581                NSWARNING(ss);//@"There are unterminated coded passages");
2582                break;
2583	}
2584    }
2585    ENDFORALL;
2586    /*
2587     NSWARNING(ss);
2588     //NSWARNING(@"You have unterminated coded passages");
2589
2590     [self handleEnd: NO flush: YES]; */
2591
2592}
2593-(id) subsetFromArray: (NSArray *) who
2594{
2595    NSMutableArray *aa = [[NSMutableArray alloc] init];
2596    FORALL(who)
2597    {
2598        id testValue;
2599        testValue = [backData objectAtIndex: [temp intValue]];
2600        [aa addObject: [backData objectAtIndex: [temp intValue]]];
2601    }ENDFORALL;
2602    return aa;
2603}
2604
2605- (BOOL)loadDataRepresentation:(NSData *)data ofType:(NSString *)type {
2606    // Implement to load a persistent data representation of your document OR remove this and implement the file-wrapper or file path based load methods.
2607    NSArray *rootArray;
2608    if([type isEqualToString: @"TAMS Result"] || [type isEqualToString: @"XML TAMS Result"])
2609    {
2610        //rootArray = [NSUnarchiver unarchiveObjectWithData: data];
2611
2612        mySavedData = data;
2613        [mySavedData retain];
2614        [savedDataType setString: type];
2615    }
2616    return YES;
2617}
2618
2619-(void) loadSavedData
2620{
2621    {
2622        NSArray *rootArray;
2623        NSMutableArray *dataArray;
2624        NSMutableDictionary *theDict;
2625        NSArray *theSetNames, *fl;
2626        int selRow;
2627        NSDictionary *theSavedNS;
2628        //        BOOL apm;
2629        //        NSMutableString *wbPath = [[NSMutableString alloc] init];
2630        selRow = 0;
2631#ifdef USESXML
2632        if([savedDataType isEqualToString: @"XML TAMS Result"]){
2633            [self loadKeyedData];
2634            return;
2635        }
2636#endif
2637        if(!gWorkBench)
2638        {
2639            NSWARNING(@"Cannot open file directly. Must open through a workbench/project");
2640            return;
2641        }
2642
2643
2644        rootArray = [NSUnarchiver unarchiveObjectWithData: mySavedData];
2645        if([[rootArray objectAtIndex: 0] isEqualToString: @"2.0a"] ||[
2646            [rootArray objectAtIndex: 0] intValue] >= 3)
2647        {
2648
2649
2650            //2. save the globals
2651            [myGlobals setGlobals: [rootArray objectAtIndex: 1]];
2652            //need to load the flag values
2653            //3. save the file list; have to convert to absolute paths
2654            fl = [rootArray objectAtIndex: 2];
2655            FORALL(fl)
2656            {
2657                if(![gWorkBench fileForName: temp])
2658                {
2659                    NSString *msg1 = [NSString  stringWithFormat:@"Cannot continue. Missing source file \"%@\" for this result.", temp];
2660                    NSWARNING(msg1);
2661                    return;
2662
2663                }
2664                else
2665                    [fileList addObject: [gWorkBench fileForName: temp]];
2666            }
2667            ENDFORALL;
2668
2669            //4. save the data
2670            dataArray = [rootArray objectAtIndex: 3];
2671            FORALL(dataArray)
2672            {
2673                theDict = [[NSMutableDictionary alloc] initWithDictionary: temp];
2674                [theDict setObject: [gWorkBench fileForName:
2675                    [temp objectForKey: @"_doc"]]
2676                            forKey:  @"_doc"];
2677                [backData addObject: theDict];
2678            }
2679            ENDFORALL;
2680
2681            //5. save the visible data
2682            [myData addObjectsFromArray: [self subsetFromArray: [rootArray objectAtIndex: 4]]];
2683
2684            //6. save the named sets
2685            //get the dictionary
2686            theSavedNS = [rootArray objectAtIndex: 5];
2687            //get the keys
2688            theSetNames = [theSavedNS allKeys];
2689            //work through them
2690            FORALL(theSetNames)
2691            {
2692                [namedSelDict setObject: [self subsetFromArray:
2693                    [theSavedNS objectForKey: temp]] forKey: temp];
2694            }
2695            ENDFORALL;
2696            //if([theSetNames count]) [self renewNamedSelMenu];
2697
2698            //7. get the limit string
2699            if(!limitString)
2700                limitString = [[NSMutableString alloc] init];
2701            [limitString setString: [rootArray objectAtIndex: 6]];
2702            //8. get colList
2703            [colList addObjectsFromArray: [rootArray objectAtIndex: 7]];
2704            //[myWindow setTitle: [[[self getMWFile] path] lastPathComponent]];
2705            //9.
2706            [limitField setStringValue: [rootArray objectAtIndex: 8]];
2707            //10. get the Coder's list
2708            if([[rootArray objectAtIndex: 0] intValue] >= 3)
2709                [codersString setString: [rootArray objectAtIndex: 9]];
2710            //11. get the automatic sets
2711            if([[rootArray objectAtIndex: 0] intValue] >= 4)
2712            {
2713                [autoSets addEntriesFromDictionary: [rootArray objectAtIndex: 10]];
2714            }
2715            [self rebuildAutoSetMenu];
2716            //12. get the selected row
2717            if([[rootArray objectAtIndex: 0] intValue] >= 5)
2718            {
2719                selRow = [[rootArray objectAtIndex: 11] intValue];
2720                [self markBackArray: [rootArray objectAtIndex: 12]];
2721            }
2722            //13. summary reports
2723            if([[rootArray objectAtIndex: 0] intValue] >= 6)
2724            {
2725                [summReports addEntriesFromDictionary: [rootArray objectAtIndex: 13]];
2726                [self rebuildSummReportMenu];
2727            }
2728            if([[rootArray objectAtIndex: 0] intValue] >= 7)
2729            {
2730                [dfString setString: [rootArray objectAtIndex: 14]];
2731                dfIndex = [[rootArray objectAtIndex: 15] intValue];
2732            }
2733            if([[rootArray objectAtIndex: 0] intValue] >= 8)
2734            {
2735                [autoHistory addObjectsFromArray: [rootArray objectAtIndex: 16]];
2736            }
2737            if([[rootArray objectAtIndex: 0] intValue] >= 9)
2738            {
2739                [autoHistoryStart setString: [rootArray objectAtIndex: 17]];
2740            }
2741            if([[rootArray objectAtIndex: 0] intValue] >= 10)
2742            {
2743                [mediaDict addEntriesFromDictionary: [rootArray objectAtIndex: 18]];
2744            }
2745
2746            [[NSNotificationCenter defaultCenter] addObserver: self
2747                                                     selector: @selector(handleResultsDidChange:)
2748                                                         name: @"TAMSResultDidChange"
2749                                                       object: gWorkBench];
2750
2751            FORALL(fileList)
2752            {
2753                [[NSNotificationCenter defaultCenter] addObserver: self
2754                                                         selector: @selector(handleDirtySourceFlag:)
2755                                                             name: @"TAMSDocDidChange"
2756                                                           object: temp];
2757
2758                [[NSNotificationCenter defaultCenter] addObserver: self
2759                                                         selector: @selector(addCodeHandler:)
2760                                                             name: @"TAMSDocAddedCode"
2761                                                           object: temp];
2762
2763
2764
2765            }ENDFORALL;
2766
2767            [self setupTables];
2768            [dirtySourceFlag setState: NSOnState];
2769            UPDATERECCOUNT;
2770            [self updateChangeCount: NSChangeCleared];
2771            [self rebuildSummReportMenu];
2772
2773            [theResults reloadData];
2774            if(selRow >= 0 && [theResults numberOfRows] > 0)
2775            {
2776                [theResults selectRow: selRow byExtendingSelection: NO];
2777                [theResults scrollRowToVisible: selRow];
2778            }
2779
2780
2781        }
2782    }
2783}
2784
2785-(BOOL) windowShouldClose: (NSNotification *)aNotification
2786{
2787#if CLOSEBUG
2788    [self willClose];
2789#endif
2790    return YES;
2791}
2792
2793- (void)windowControllerDidLoadNib:(NSWindowController *)windowController
2794{
2795    [super windowControllerDidLoadNib: windowController];
2796    [self zeroSetStack];
2797    [theResults setDelegate: self];
2798    [theResults setDoubleAction: @selector(fetchRow:)];
2799    [self rebuildSummReportMenu];
2800	//[self clearTable];
2801
2802    ;// [self executeTAMS];
2803}
2804-(void) executeTAMS
2805{
2806    //get the data
2807    if(!tce ) return;
2808    [self rebuildAutoSetMenu]; //only secure place to put it
2809    [self rebuildSummReportMenu];
2810    if([tce gCurrentDataSource] != nil)
2811    {
2812	dataSource = [tce gCurrentDataSource];
2813	//[[myWindow windowController] setShouldCloseDocument: YES];
2814	//[self resetStorage]; //need to zero out the arrays, send inits to all the processes
2815	//ctInitRV();
2816	//[tce initLimit];
2817	[self clearTable];
2818	[self setGlobal: @"firstwriteflag" to: 1];
2819	[self setGlobal: @"rawflag" to: [dataSource rawF]];
2820	[self setGlobal: @"emptyflag" to: [dataSource emptyF]];
2821	[self setGlobal: @"exactflag" to: [dataSource exactF]];
2822	[self setGlobal: @"simpleflag" to: [dataSource simpleF]];
2823	[self setGlobal: @"regexcharflag" to: [dataSource regexCharF]];
2824	[self setGlobal: @"nonregexcharflag" to: [dataSource nonRegexCharF]];
2825        [self setGlobal: @"sectionsearch" to: [dataSource sectionF]];
2826	[self setGlobal: @"raw1stflag" to: [dataSource rawF]];
2827	[self setGlobal: @"empty1stflag" to: [dataSource emptyF]];
2828	[self setGlobal: @"exact1stflag" to: [dataSource exactF]];
2829	[self setGlobal: @"simple1stflag" to: [dataSource simpleF]];
2830	[self setGlobal: @"section1stflag" to: [dataSource sectionF]];
2831	[self setGlobal: @"regexchar1stflag" to: [dataSource regexCharF]];
2832	[self setGlobal: @"nonregexchar1stflag" to: [dataSource nonRegexCharF]];
2833
2834
2835	if([gPrefBoss countSectionsValue])
2836	    SETGLOBAL(@"emptysectionflag", 1);
2837	else
2838	    SETGLOBAL(@"emptysectionflag",0);
2839	//[myWindow setReleasedWhenClosed: YES];
2840	[fileList removeAllObjects];
2841	[colList removeAllObjects];
2842        [codersString setString: [dataSource codersList]];
2843	[self buildCoderList];
2844
2845        //get the search
2846	if(limitString != nil) [limitString release];
2847	limitString = [[NSMutableString alloc] init];
2848	[limitString setString: [dataSource theLimitString]];
2849	[fileList addObjectsFromArray: [tce hotFileList]];
2850        [[NSNotificationCenter defaultCenter] addObserver: self
2851                                                 selector: @selector(handleResultsDidChange:)
2852                                                     name: @"TAMSResultDidChange"
2853                                                   object: gWorkBench];
2854	FORALL(fileList)
2855	{
2856            [[NSNotificationCenter defaultCenter] addObserver: self
2857                                                     selector: @selector(handleDirtySourceFlag:)
2858                                                         name: @"TAMSDocDidChange"
2859                                                       object: temp];
2860
2861            [[NSNotificationCenter defaultCenter] addObserver: self
2862                                                     selector: @selector(addCodeHandler:)
2863                                                         name: @"TAMSDocAddedCode"
2864                                                       object: temp];
2865
2866
2867
2868	}ENDFORALL;
2869
2870	[[NSNotificationCenter defaultCenter] addObserver: self
2871                                                 selector: @selector(handleEachEOF:)
2872                                                     name: @"TAMSFileHasEnded"
2873                                                   object: nil];
2874        [self setOriginalStateString];
2875
2876	if([limitString length])
2877	{
2878            /*
2879             if([self global: @"sectionsearch"] == 1)
2880             {
2881                 [limitField setStringValue: [NSString stringWithFormat: @"Section: %@", limitString]];
2882             }
2883             else
2884             [limitField setStringValue: limitString];
2885             */
2886	    [self setGlobal: @"limitflag" to: 1];
2887	    [tce handlelimit: limitString];
2888	    [self doTamsSearch: limitString];
2889	    [tce ctCloseAllOpenRuns];
2890	    if([[tce ctRunVault] count])
2891		[self handleEnd: NO flush: NO];
2892	}
2893	else
2894	{
2895            /*            if([self global: @"sectionsearch"] == 1)
2896        {
2897
2898                [limitField setStringValue: [NSString stringWithFormat: @"Section: unlimited", limitString]];
2899        }
2900            else
2901            [limitField setStringValue: @"Unlimited"];
2902            */
2903	    [self setGlobal: @"limitflag" to: 0];
2904	    [self doTamsSearch: nil];
2905	    [tce ctCloseAllOpenRuns];
2906	    if([[tce ctRunVault] count])
2907		[self handleEnd: NO flush: NO];
2908	}
2909	[tce setGCurrentTAMS: nil];
2910        //do the search
2911	//do the tables
2912	//reload
2913	[self setupTables];
2914	[myWindow makeKeyAndOrderFront: self];
2915	[backData removeAllObjects];
2916	[backData addObjectsFromArray: myData];
2917
2918        [self updateChangeCount: NSChangeDone];
2919
2920	UPDATERECCOUNT;
2921	[theResults reloadData];
2922	[[NSNotificationCenter defaultCenter] removeObserver:self
2923                                                        name: @"TAMSFileHasEnded" object: nil];
2924    }
2925
2926    [tce release];
2927
2928}
2929#ifdef SECTIONSEARCH
2930-(NSMutableDictionary *) token2Dictionary: (ctQChar *) qq
2931{
2932    NSALLOC(NSMutableDictionary, myD);
2933
2934    [myD setObject: [[[qq buff] copy] autorelease] forKey: @"code"];
2935    [myD setObject: [[[qq coder] copy] autorelease] forKey: @"coder"];
2936    [myD setObject: @"Open" forKey: @"state"];
2937    return [myD autorelease];
2938
2939}
2940
2941-(void) removeCloseTags: (NSMutableArray *) aa
2942{
2943    int i, n;
2944    NSMutableDictionary *tt;
2945
2946    n = [aa count];
2947    for(i = n - 1; i >= 0; i--)
2948    {
2949        tt = [aa objectAtIndex: i];
2950        if([[tt objectForKey: @"state"] isEqualToString: @"Closed"])
2951            [aa removeObject: tt];
2952    }
2953}
2954
2955-(void) addTokenForChar: (ctQChar *) qq forSection: (coderec *) ms
2956{
2957    NSMutableArray *aa = [ms sectionCodes];
2958    FORALL(aa)
2959    {
2960        if([[temp objectForKey: @"code"] isEqualToString: [qq buff]] &&
2961           [[temp objectForKey: @"coder"] isEqualToString: [qq coder]])
2962        {
2963            if([[temp objectForKey: @"state"] isEqualTo: @"Closed"])
2964            {
2965                [temp setObject: @"Open" forKey: @"state"];
2966                return;
2967            }
2968        }
2969
2970    }
2971    ENDFORALL;
2972    [aa addObject: [self token2Dictionary: qq]];
2973}
2974
2975-(void) closeTokenForChar: (ctQChar *) qq forSection: (coderec *) ms
2976{
2977    NSMutableArray *aa = [ms sectionCodes];
2978    FORALL(aa)
2979    {
2980        if([[temp objectForKey: @"code"] isEqualToString: [qq buff]] &&
2981           [[temp objectForKey: @"coder"] isEqualToString: [qq coder]])
2982        {
2983            [temp setObject: @"Close" forKey: @"Closed"];
2984        }
2985    }
2986    ENDFORALL;
2987}
2988#endif
2989
2990-(void) setCurrMWFile: (MWFile *) who
2991{
2992    currMWFile = who;
2993}
2994-(MWFile *) currMWFile
2995{
2996    return currMWFile;
2997}
2998
2999- (void) doTamsSearch: (NSString *) aLimString
3000{
3001    int nn;
3002    ctQChar *qq;
3003#ifdef REGEXSEARCH
3004    AGRegex *regex;
3005    AGRegexMatch *match;
3006    NSArray *fl;
3007    int rsi, rsj, rsk, rsnn3, rsnn, rsnn2;
3008    int charZoom;
3009    int chtype;
3010    unsigned opt;
3011    long rsln;
3012    NSRange rsr, rsr2, rsr3;
3013#endif
3014#ifdef SECTIONSEARCH
3015    coderec *mySect;
3016
3017    mySect = nil;
3018#endif
3019#ifdef REGEXSEARCH
3020#endif
3021    qq = nil;
3022    qq = [[ctQChar alloc] init];
3023    nn = [self global: @"simpleflag"];
3024    //setup();
3025    [tce setGCurrentTAMS: self];
3026#ifdef REGEXSEARCH
3027    charZoom = [gPrefBoss zoomFactorValue];
3028    if([self global: @"nonregexcharflag"])
3029    {
3030        fl = [tce hotFileList];
3031        [colList addObject: @"_code"];
3032        [colList addObject: @"_data"];
3033        [colList addObject: @"_begin_loc"];
3034        [colList addObject: @"_doc"];
3035        opt = 0;
3036        if([self global: @"exactflag"] == 0)
3037            opt = NSCaseInsensitiveSearch;
3038        rsnn = [fl count];
3039        for(rsi = 0 ; rsi < rsnn; rsi++)
3040        {
3041            MWFile *rsFile;
3042            NSString *rsString;
3043            fl = [tce hotFileList];
3044            rsFile = [fl objectAtIndex: rsi];
3045            rsString = [rsFile string];
3046            rsln = [rsString length];
3047            rsnn2 = 1;
3048            rsr3 = NSMakeRange(0, rsln - 1);
3049            while(rsnn2)
3050            {
3051                rsr = [rsString rangeOfString: limitString
3052                                      options: opt
3053                                        range: rsr3];
3054                if(rsr.location != NSNotFound)
3055                {
3056                    NSALLOC(NSMutableDictionary,theRec);
3057                    rsr2 = rsr;
3058                    if(charZoom > rsr2.location)
3059                    {
3060                        rsr2.length += charZoom;
3061                        rsr2.location = 0;
3062                    }
3063                    else
3064                    {
3065                        rsr2.length += charZoom;
3066                        rsr2.location -= charZoom;
3067                    }
3068                    rsr2.length += charZoom;
3069                    if(rsr2.location + rsr2.length >= rsln)
3070                        rsr2.length = rsln - rsr2.location;
3071                    [theRec setObject: rsFile forKey: @"_doc"];
3072                    [theRec setObject: [[limitString copy] autorelease] forKey: @"_code"];
3073                    [theRec setObject: [rsString substringWithRange: rsr2]
3074                               forKey: @"_data"];
3075                    /*[theRec setObject: [[[match groupAtIndex: rsk] copy] autorelease]
3076forKey: @"_data"];*/
3077                    [theRec setObject: [[NSNumber numberWithLong:
3078                        rsr.location] stringValue]
3079                               forKey: @"_begin_loc"];
3080                    [theRec setObject: [[NSNumber numberWithLong:
3081                        rsr.location +
3082                        rsr.length] stringValue]
3083                               forKey: @"_end_loc"];
3084                    rsr3.location = rsr.location + rsr.length;
3085                    rsr3.length = rsln - rsr3.location;
3086                    [myData addObject: theRec];
3087                }
3088                else
3089                    rsnn2 = 0;
3090            }
3091
3092        }
3093        if(!qq) [qq release];
3094        return;
3095    }
3096
3097#define NEWREGEXSEARCHCODE
3098    if([self global: @"regexcharflag"])
3099    {
3100        NSRange tr;
3101
3102        opt = 0;
3103        if([self global: @"exactflag"] == 0) opt = AGRegexCaseInsensitive;
3104        if([self global: @"emptyflag"] == 1) opt |= AGRegexMultiline;
3105        //regex = [[AGRegex alloc] initWithPattern: limitString options: opt];
3106
3107        fl = [tce hotFileList];
3108        [colList addObject: @"_code"];
3109        [colList addObject: @"_data"];
3110        [colList addObject: @"_begin_loc"];
3111        [colList addObject: @"_doc"];
3112        rsnn = [fl count];
3113        for(rsi = 0 ; rsi < rsnn; rsi++)
3114        {
3115            MWFile *rsFile;
3116            NSString *rsString;
3117            NSMutableDictionary *theRec;
3118            NSAutoreleasePool *myPool;
3119            int sbstr;
3120            if([codersString isEqualToString: @""] == YES)
3121                sbstr = 0;
3122            else
3123                sbstr = [codersString intValue];
3124            //NSLog(@"str: %@; int:%d\n", codersString, sbstr);
3125            fl = [tce hotFileList];
3126            rsFile = [fl objectAtIndex: rsi];
3127            rsString = [rsFile string];
3128            rsln = [rsString length];
3129            tr = NSMakeRange(0,0);
3130            for(;;)
3131            {
3132                //fl = [regex findAllInString: rsString];
3133                theRec = [[NSMutableDictionary alloc] init];
3134                myPool = [[NSAutoreleasePool alloc] init];
3135                rsr = rsr2 = [rsString findString: limitString selectedRange: tr options:opt wrap:NO regex: YES multiline: YES substring: sbstr];
3136                [myPool release];
3137                if(rsr.location == NSNotFound) break;
3138
3139                {
3140                    if(charZoom > rsr2.location)
3141                    {
3142                        rsr2.length += charZoom;
3143                        rsr2.location = 0;
3144                    }
3145                    else
3146                    {
3147                        rsr2.length += charZoom;
3148                        rsr2.location -= charZoom;
3149                    }
3150                    rsr2.length += charZoom;
3151                    if(rsr2.location + rsr2.length >= rsln)
3152                        rsr2.length = rsln - rsr2.location;
3153                    [theRec setObject: [rsString substringWithRange: rsr2]                                 forKey: @"_data"];
3154
3155                    [theRec setObject: rsFile forKey: @"_doc"];
3156                    [theRec setObject: [[limitString copy] autorelease] forKey: @"_code"];
3157                    /*[theRec setObject: [[[match groupAtIndex: rsk] copy] autorelease]
3158forKey: @"_data"];*/
3159                    [theRec setObject: [[NSNumber numberWithLong:
3160                        rsr.location] stringValue]
3161                               forKey: @"_begin_loc"];
3162                    [theRec setObject: [[NSNumber numberWithLong:
3163                        rsr.location +
3164                        rsr.length] stringValue]
3165                               forKey: @"_end_loc"];
3166                    [myData addObject: [theRec autorelease]];
3167                }
3168                tr.location = rsr.location + rsr.length;
3169                tr.length = 0;
3170
3171            }//for(;;)
3172
3173        }
3174        //[regex release];
3175        return;
3176    }
3177
3178#endif
3179
3180#ifdef SCANCODE
3181    while((chtype = [tce scanNext: qq]) != ENDOFALLFILES)
3182#else
3183        while([tce readnext: qq] != EOF)
3184#endif
3185        {
3186            if(chtype != ENDOFFILE)
3187            {
3188                [self setCurrMWFile: [qq source]];
3189            }
3190#ifdef SECTIONSEARCH
3191            if([self global: @"sectionsearch"])
3192            {
3193                //we need to add the open dictionary
3194                if([tce hasSectionRun] == NO)
3195                {
3196                    [tce ctOpenSectionRun];
3197                }
3198#ifdef SCANCODE
3199                switch(chtype)
3200#else
3201                    switch([qq tokentype])
3202#endif
3203                    {
3204                        case TOKEN:
3205                            //handle inner repeat
3206                            if([self isRepeat: [qq buff]] && [self isInnerRepeat: [qq buff]]
3207                               && innerRFlag)
3208                            {
3209                                [self handleEnd: YES flush: NO];
3210                            }
3211                            else
3212
3213                            {
3214                                innerRFlag = 1;
3215                            }
3216
3217                            //handle last repeat
3218                            if([self isRepeat: [qq buff]] && [self global: @"lastRepeat"])
3219                            {
3220                                [self handleEnd: YES flush: NO];
3221
3222                                SETGLOBAL(@"lastRepeat", 0);//[self setGlobal: @"lastRepeat" 0];
3223                            }
3224                            if([self isLastRepeat: [qq buff]] == YES) {SETGLOBAL(@"lastRepeat", 1);}
3225                            if([tce hasSectionRun] == NO)
3226                            {
3227                                [tce ctOpenSectionRun];
3228                            }
3229                            if([self isRepeat: [qq buff]] == YES)
3230                                [tce ctOpenRun: qq];
3231                            [tce ctAddSectionTag: [self token2Dictionary:qq]];
3232
3233                            [tce ctAddOpenChar: qq]; break;
3234                            break;
3235                        case ENDTOKEN:
3236                            if([tce hasSectionRun] == NO)
3237                            {
3238                                [tce ctOpenSectionRun];
3239
3240                            }
3241                            if([extraComment length])[qq addExtra: [self getComment]];
3242                            [tce ctAddOpenChar: qq];
3243                            [tce ctCloseSectionTagForCode: [qq buff] Coder: [qq coder]];
3244                            [tce ctCloseRun: qq];
3245                            break;
3246                        case CHAR:
3247                            if([tce hasSectionRun] == NO)
3248                            {
3249                                [tce ctOpenSectionRun];
3250
3251                            }
3252                            [tce ctAddOpenChar: qq]; break;
3253
3254                        case META:
3255                            [self handlemeta: qq]; break;
3256                            if([tce hasSectionRun] == NO)
3257                            {
3258                                mySect = [tce ctOpenSectionRun];
3259
3260                            }
3261                                break;
3262
3263                        case ENDOFFILE:
3264                            [self handleAnEOF: [qq source]];
3265                            break;
3266                    };
3267
3268                continue;
3269            }
3270
3271
3272
3273#endif
3274            // regular simple and non-simple searches
3275            if(/*![self global: @"limitflag"] || */[self global: @"simpleflag"])
3276            {
3277#ifdef SCANCODE
3278                switch(chtype)
3279#else
3280		    switch([qq tokentype])
3281#endif
3282		    {
3283			case TOKEN:
3284                            if([self isRepeat: [qq buff]] && [self isInnerRepeat: [qq buff]]
3285                               && innerRFlag)
3286                                [self handleEnd: YES flush: NO];
3287                            else
3288                            {
3289                                innerRFlag = 1;
3290                            }
3291                                if([self isRepeat: [qq buff]] && [self global: @"lastRepeat"])
3292                                {
3293                                    [self handleEnd: YES flush: NO];
3294
3295                                    SETGLOBAL(@"lastRepeat", 0);//[self setGlobal: @"lastRepeat" 0];
3296                                }
3297
3298                                if([self isLastRepeat: [qq buff]] == YES)
3299                                {
3300                                    SETGLOBAL(@"lastRepeat", 1);
3301                                }
3302
3303                                if([self global: @"simpleflag"] && aLimString)
3304                                {
3305                                    //aCode = [[ctLimitCrit alloc] initWithString: aLimString];
3306                                    //if(isStringTrue(aCode, [qq buff]) || [self isRepeat: [qq buff]])
3307                                    if([tce isTagTrue: qq] || [self isRepeat: [qq buff]])
3308                                    {
3309                                        [tce ctOpenRun: qq];
3310                                    }
3311
3312                                }
3313                                else
3314                                    [tce ctOpenRun: qq];
3315			    [tce ctAddZone: qq];
3316			    if([self global: @"rawflag"]) [tce ctAddOpenChar: qq];
3317                                break;
3318
3319			case ENDTOKEN:
3320                            if([extraComment length])[qq addExtra: [self getComment]];
3321			    [tce ctCloseRun: qq];
3322			    [tce ctDelZone: qq ];
3323			    if([self global: @"rawflag"]) [tce ctAddOpenChar: qq];
3324                                if([self global: @"basicflag"])
3325                                    [self handleEnd: YES flush: NO];
3326                                    break;
3327
3328			case CHAR:
3329			    [tce ctAddOpenChar: qq]; break;
3330
3331			case META:
3332			    [self handlemeta: qq]; break;
3333
3334                        case ENDOFFILE:
3335                            [self handleAnEOF: [qq source]];
3336                            break;
3337		    };
3338            }
3339	    //here is the limit logic
3340            else if(/*[self global: @"limitflag"] && */ ![self global: @"simpleflag"])
3341            {
3342                int zoneFlag;
3343                if(chtype == ENDTOKEN) if([extraComment length])[qq addExtra: [self getComment]];
3344                if(chtype == ENDOFFILE)
3345                {
3346                    [self handleAnEOF: [qq source]];
3347                    continue;
3348                }
3349                if(chtype == TOKEN)
3350                {
3351                    if([self isRepeat: [qq buff]] && [self isInnerRepeat: [qq buff]]
3352                       && innerRFlag)
3353                        [self handleEnd: YES flush: NO];
3354                    else
3355                        innerRFlag = 1;
3356                    if([self isRepeat: [qq buff]] && [self global: @"lastRepeat"])
3357                    {
3358                        [self handleEnd: YES flush: NO];
3359
3360                        SETGLOBAL(@"lastRepeat", 0);//[self setGlobal: @"lastRepeat" 0];
3361                    }
3362
3363                    if([self isLastRepeat: [qq buff]] == YES)
3364                    {
3365                        SETGLOBAL(@"lastRepeat", 1);
3366                    }
3367
3368                }
3369                zoneFlag = [tce handleLimChar: qq];
3370                if(zoneFlag == STARTLIM)
3371                {
3372                    //if([self isRepeat: [qq buff]]) continue;
3373                    [tce ctOpenLimRun: qq];
3374                }
3375                else if (zoneFlag == ENDLIM)
3376                {
3377                    [tce ctCloseLimRun: qq];
3378                    if([self global:@"basicflag"])
3379                        [self handleEnd: YES flush: NO];
3380                }
3381                else if (zoneFlag == INLIM) [tce ctAddLimChar:qq];
3382            }
3383        }
3384            /*
3385             if([self global: @"eofIsEndFlag"]) //if([gPrefBoss EOFIsEndValue])
3386             [self handleEnd: NO flush: NO];
3387             */
3388	    [tce checkZones];
3389}
3390
3391- (void)savePanelDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void  *)contextInfo
3392{
3393    if(returnCode == NSCancelButton) return;
3394    if(returnCode == NSOKButton)
3395    {
3396	[self writeToFile:[[NSSavePanel savePanel] filename]
3397                   ofType: @"DocumentType"];
3398    }
3399}
3400
3401-(NSMutableArray *) convertString: (NSString *)  theString onChar: (unichar) breakChar
3402{
3403    int i, len;
3404    unichar c;
3405    NSMutableString *ss = [[NSMutableString alloc] init];
3406    NSMutableArray *ans = [[NSMutableArray alloc] init];
3407    len = [theString length];
3408    [ss setString: @""];
3409
3410    for(i = 0; i < len; i++)
3411    {
3412	c = [theString characterAtIndex: i];
3413	if(c == ' ')
3414	{
3415	    ;
3416	}
3417	else if (c == breakChar)
3418	{
3419	    if([ss length] > 0)
3420	    {
3421		[ans addObject: [ss copy]];
3422		[ss setString: @""];
3423	    }
3424	}
3425	else
3426	{
3427	    [ss ADDCHAR(c)];
3428	}
3429    }
3430    if([ss length])
3431    {
3432	[ans addObject: [ss copy]];
3433    }
3434    return ans;
3435}
3436
3437-(void) addToList: (NSMutableArray *) aList usingString: (NSString *) aString
3438{
3439    NSMutableArray *ans;
3440    int i,n;
3441    if(aString == nil) return;
3442    if([aString isEqualToString: @""]) return;
3443    ans = [self convertString: aString onChar: ','];
3444    //ans = convertStringToArray(aString, ',');
3445    //[ans retain];
3446    n = [ans count];
3447    for(i = 0; i < n; i++)
3448    {
3449        if(arrayContainsString(aList , [ans objectAtIndex: i]) == NO)
3450            [aList addObject: [ans objectAtIndex: i]];
3451    }
3452    //[aList addObjectsFromArray: ans];
3453}
3454
3455-(BOOL)isHotCoder: (NSMutableDictionary *) rec
3456{
3457    if([codersList count] == 0) return YES;
3458    FORALL(codersList)
3459    {
3460	if([temp isEqualToString: @"*"] == YES)
3461	{
3462	    if([[rec objectForKey: @"_coder"] isEqualToString: @""] == YES) return YES;
3463	}
3464	else
3465	    if([temp isEqualToString: [rec objectForKey: @"_coder"]] == YES) return YES;
3466    }
3467    ENDFORALL;
3468    return NO;
3469}
3470
3471-(void) doContWithDict: (NSMutableDictionary *) theVault
3472{
3473    int iii, nnn, ii, nn;
3474    NSMutableDictionary *contList, *contValue;
3475    NSArray *myKeyArray, *myContArray;
3476
3477    myKeyArray = [theVault allKeys];
3478    nnn = [myKeyArray count];
3479    for(iii = 0; iii < nnn; iii++)
3480    {
3481
3482        //work through
3483        //look up the repeat variabl
3484        if((contList = [repCont objectForKey: [myKeyArray objectAtIndex: iii]]) != nil)
3485        {
3486            //get the contingency
3487            contValue = [contList objectForKey: [theVault objectForKey: [myKeyArray objectAtIndex: iii]]];
3488            if(contValue != nil)
3489            {
3490                myContArray = [contValue allKeys];
3491
3492                //set for each
3493                nn = [myContArray count];
3494
3495                for(ii = 0; ii < nn; ii++)
3496                {
3497                    //if it's a repeat
3498                    if([self isRepeat: [myContArray objectAtIndex: ii]]
3499                       || [self isUniversal: [myContArray objectAtIndex: ii]] )
3500                    {
3501                        [theVault setObject:
3502                            [contValue objectForKey:
3503                                [myContArray objectAtIndex: ii]]
3504                                     forKey: [myContArray objectAtIndex: ii]];
3505                    }
3506
3507                }
3508            }
3509            else //zap the contingent variables
3510            {
3511
3512            }
3513
3514        }
3515    }
3516
3517}
3518
3519-(void) assignRepeat: (NSString *) rname withValue: (NSString *) rvalue
3520{
3521    NSMutableString *ss, *tt;
3522    if([fieldMap count] > 0)
3523    {
3524        ss = [fieldMap objectForKey: rname];
3525        if(ss == nil)
3526            [repVault setObject: rvalue forKey: rname];
3527        else
3528            [repVault setObject: rvalue forKey: ss];
3529    }
3530    else
3531        [repVault setObject: rvalue forKey: rname];
3532}
3533int sectionTotCnt = 0;
3534-(void) handleEnd: (BOOL) section flush: (BOOL) flushFlag
3535{
3536    NSEnumerator *myenums ;
3537    coderec  *mykey;
3538    NSString *ss, *st;
3539    NSMutableArray *doneList;
3540    int n;
3541    int realcnt;
3542    int fflag;
3543    fflag = 1; //first time through the emptys
3544    realcnt = 0;
3545
3546    n= 0;
3547    if([self global: @"emptyflag"])
3548	n = 1;
3549    if(section == YES && MYGLOBAL(@"emptysectionflag") == NO && [self global: @"sectionsearch"])
3550        return; //we're not done
3551    if([self global: @"sectionsearch"])
3552    {
3553        /* being here means that the section has ended, since this is called for !end*/
3554
3555        [tce ctCloseSectionRun];
3556
3557        /* filter results */
3558        [tce filterSectionRuns];
3559    }
3560    //|| (section == YES && [self global: @"emptysectionflag"])
3561    //first handle all of the repeats
3562    //need to make this conditional on emptyflag
3563    /*
3564     if([self global: @"emptyflag"])
3565     [repVault removeAllObjects];
3566     */
3567    //set the repeats
3568    FORALL([tce ctRunVault])
3569    {
3570        st = [temp theName]; //for debugging
3571                             //if([self isRepeat: [temp theName]])
3572        if([temp runType] == REPEATRUN)
3573	{
3574	    if(ss = [temp record])
3575            {
3576                [self assignRepeat: [temp theName] withValue: [ss copy]];
3577		//[repVault setObject: [ss copy] forKey: ];
3578
3579            }
3580	    else
3581                [self assignRepeat: [temp theName] withValue: @""];
3582            //[repVault setObject: @"" forKey: [temp theName]];
3583
3584	}
3585    }
3586    ENDFORALL;
3587
3588    [self doContWithDict: repVault];
3589
3590    if([self global: @"firstwriteflag"])
3591    {
3592	//[colList addObject: @"#"];
3593	FORALL(univList)
3594    {
3595	    [colList addObject:  temp];
3596    }
3597	ENDFORALL;
3598	FORALL(repList)
3599	{
3600	    [colList addObject:  temp];
3601	}
3602	ENDFORALL;
3603	[colList addObject: @"_code"];
3604	[colList addObject: @"_data"];
3605	[colList addObject: @"_comment"];
3606	[colList addObject: @"_coder"];
3607        [colList addObject: @"_doc"];
3608        if([tce hasLineNumbers] && [gPrefBoss TAScanForLN])
3609            [colList addObject: @"_line_number"];
3610	[colList addObject: @"_begin_loc"];
3611 	[self setGlobal: @"firstwriteflag" to: 0];
3612	sectionTotCnt = 0;
3613    }
3614
3615
3616    myenums = [[tce ctRunVault] objectEnumerator];
3617
3618    while(mykey = [myenums nextObject])
3619    {
3620	NSMutableDictionary *myrec;
3621
3622	//if([mykey openRun] == YES) continue;
3623	if([self isRepeat: [mykey theName]] == YES)
3624	    continue;
3625	//if it isn't in our approved coder list nix it
3626	//if([self isValidCoder: [mykey theCoder]] == NO)
3627	//    continue;
3628	//we're not a repeat so this one counts
3629	//make a dictionary of
3630	myrec = [[NSMutableDictionary alloc] init];
3631	// the univerals
3632        FORALL(univList)
3633        {
3634            [myrec setObject: [univVault objectForKey: temp] forKey: temp];
3635        }
3636        ENDFORALL;
3637	//the repeats
3638        FORALL(repList)
3639        {
3640            NSString *tt;
3641
3642            if(tt = [repVault objectForKey: temp])
3643                [myrec setObject: tt forKey: temp];
3644            else
3645                [myrec setObject: @"" forKey: temp];
3646
3647        }
3648        ENDFORALL;
3649	//This is where we need to add handling for cross code stuff
3650        if([mykey hasInfo] == YES && [mykey openRun] ==NO)
3651        {
3652            if([mykey runType] != SECTIONRUN)
3653                [myrec setDictionary: [mykey affiliatedInfo]];
3654        }
3655	//ask if it has cross code
3656	//use that instead
3657	//if it is open and doesn't have one give it one
3658	//otherwise
3659	//the code
3660        [myrec setObject: [[mykey theName] copy] forKey: @"_code"];
3661	//the comment
3662        [myrec setObject: [[mykey comment] copy] forKey: @"_comment"];
3663	//the comment
3664        [myrec setObject: [[mykey theCoder] copy] forKey: @"_coder"];
3665	//the document
3666        [myrec setObject: [mykey doc] forKey: @"_doc"];
3667	//the index
3668
3669        [myrec setObject: [[NSNumber numberWithLong: [mykey beginLoc]] stringValue]
3670                  forKey: @"_begin_loc"];
3671
3672        [myrec setObject: [[NSNumber numberWithLong: [mykey endLoc]] stringValue]
3673                  forKey: @"_end_loc"];
3674        if([tce hasLineNumbers] && [gPrefBoss TAScanForLN])
3675	    [myrec setObject: [[NSNumber numberWithInt: [mykey lineStart]] stringValue]
3676                      forKey: @"_line_number"];
3677
3678 	//the data
3679        [myrec setObject: [[mykey record] copy] forKey: @"_data"];
3680	if( [mykey hasInfo] == NO && [mykey openRun] == YES
3681            && ![self global: @"backloadrepeatflag"])
3682	{
3683            if([mykey runType] != SECTIONRUN)
3684                [mykey setAffiliatedInfo: myrec];
3685	    if([self isHotCoder: myrec] == YES) realcnt++;
3686	}
3687	else if([mykey openRun] == NO)
3688	{
3689	    if([self isHotCoder: myrec] == YES)
3690	    {
3691		[myData addObject: myrec];
3692		realcnt++;
3693	    }
3694	}
3695    }
3696    sectionTotCnt += realcnt;
3697    // empty flag case
3698    if(((section == NO) || (section == YES && MYGLOBAL(@"emptysectionflag")))
3699       && n && sectionTotCnt == 0)
3700    {
3701
3702	NSMutableDictionary *myrec;
3703	myrec = [[NSMutableDictionary alloc] init];
3704	// the univerals
3705        FORALL(univList)
3706        {
3707            [myrec setObject: [univVault objectForKey: temp] forKey: temp];
3708        }
3709        ENDFORALL;
3710	//the repeats
3711        FORALL(repList)
3712        {
3713            NSString *tt;
3714            if(tt = [repVault objectForKey: temp])
3715            {
3716                [myrec setObject: tt forKey: temp];
3717            }
3718            else
3719                [myrec setObject: @"" forKey: temp];
3720
3721        }
3722        ENDFORALL;
3723
3724	//the code
3725        [myrec setObject: @"*EMPTY*" forKey: @"_code"];
3726	//the data
3727        [myrec setObject: @"" forKey: @"_data"];
3728	//the comment
3729        [myrec setObject: @"" forKey: @"_comment"];
3730	//the document
3731
3732	//the index
3733
3734	if([[tce ctRunVault] count])
3735	{
3736	    mykey = [[tce ctRunVault] objectAtIndex: 0];
3737	    [myrec setObject: [[NSNumber numberWithLong: [mykey beginLoc]]
3738                stringValue]
3739                      forKey: @"_begin_loc"];
3740
3741	    [myrec setObject: [[NSNumber numberWithLong: [mykey endLoc]]
3742                stringValue]
3743                      forKey: @"_end_loc"];
3744
3745	    [myrec setObject: [mykey doc] forKey: @"_doc"];
3746	}
3747	else
3748	{
3749            int tl;
3750            MWFile *www;
3751	    [myrec setObject:(  [NSNumber numberWithLong: tl = [tce getCharLocation]])
3752                      forKey: @"_begin_loc"];
3753
3754	    [myrec setObject:([NSNumber numberWithLong: tl = [tce getCharLocation]])
3755                      forKey: @"_end_loc"];
3756
3757	    /*if([tce hotSearchDocument] != nil)*/
3758            [myrec setObject: (www=[self currMWFile]) forKey: @"_doc"];
3759            // else [myrec setObject: [ stringWithString: @"NO DOC"] forKey: @"_doc"];
3760            tl = 0;
3761#ifdef rightCode
3762            int tl;
3763            MWFile *www;
3764	    [myrec setObject:( tl = [NSNumber numberWithLong: [tce getCharLocation]])
3765                      forKey: @"_begin_loc"];
3766
3767	    [myrec setObject:( tl = [NSNumber numberWithLong: [tce getCharLocation]])
3768                      forKey: @"_end_loc"];
3769
3770	    [myrec setObject: (www=[self currMWFile]) forKey: @"_doc"];
3771            tl = 0;
3772#endif
3773
3774	}
3775
3776        [myData addObject: myrec];
3777    }
3778
3779
3780    // empty the data source
3781    //[ctRunVault removeAllObjects];
3782    doneList = [[NSMutableArray alloc] init];
3783    FORALL([tce ctRunVault])
3784    {
3785	if([temp openRun] == NO) [doneList addObject: temp];
3786	else if([self global: @"rawflag"] && [self global: @"basicflag"] == 0)
3787	    [temp addString: @"{!end}"];
3788    }
3789    ENDFORALL;
3790    FORALL(doneList)
3791    {
3792	[[tce ctRunVault] removeObject: temp];
3793    }
3794    ENDFORALL;
3795    [doneList removeAllObjects];
3796    [doneList release];
3797    //if clean remove the repeats
3798    if(MYGLOBAL(@"cleanflag") && (section == NO))
3799    {
3800	[repVault removeAllObjects];
3801    }
3802    if(section == NO || MYGLOBAL(@"emptysectionflag") == 1) sectionTotCnt = 0;
3803}
3804
3805/*
3806 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
3807 */
3808
3809#define IFVER2
3810-(void) handleIf: (NSString *) cList
3811{
3812    AGRegex *myExpr, *myExpr2;
3813    AGRegexMatch *myMatch;
3814    NSArray *myMatch2;
3815    NSMutableDictionary *theBase, *tb2;
3816
3817    //first look for the regex
3818#ifdef IFVER1
3819    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]*\\\"(.*)\\\""];
3820#endif
3821#ifdef IFVER2
3822    myExpr = [[AGRegex alloc] initWithPattern: @"^[\\t\\ \\n\\r]*([a-zA-Z0-9\\_]+)[\\t\\ \\n\\r]*=[\\t\\ \\n\\r]*\\\"([^\\\"]*)\\\"[\\t\\ \\n\\r]*=>"];
3823    myExpr2 = [[AGRegex alloc] initWithPattern: @"=>[\\t\\ \\n\\r]*([a-zA-Z0-9\\_]+)[\\t\\ \\n\\r]*=[\\t\\ \\n\\r]*\\\"([^\\\"]*)\\\""];
3824#endif
3825    myMatch = [myExpr findInString: cList];
3826    if( [myMatch count])
3827    {
3828        theBase = [repCont objectForKey: [myMatch groupAtIndex: 1]];
3829#ifdef IFVER2
3830        myMatch2 = [myExpr2 findAllInString: cList];
3831#endif
3832        if(theBase != nil)
3833        {
3834            if((tb2 = [theBase objectForKey: [myMatch groupAtIndex: 2]]) != nil)
3835            {
3836#ifdef IFVER2
3837                int n2, i2;
3838
3839                n2 = [myMatch2 count];
3840                for(i2 = 0; i2 < n2; i2++)
3841                {
3842                    [tb2 setObject: [[myMatch2 objectAtIndex: i2] groupAtIndex: 2]
3843                            forKey: [[myMatch2 objectAtIndex: i2] groupAtIndex: 1]];
3844                }
3845#endif
3846#ifdef IFVER1
3847                [tb2 setObject: [myMatch groupAtIndex: 4] forKey: [myMatch groupAtIndex: 3]];
3848#endif
3849
3850            }
3851            else
3852            {
3853                int n2, i2;
3854                //tb2 = [[NSMutableDictionary alloc] init];
3855                tb2 = [NSMutableDictionary dictionary];
3856#ifdef IFVER2
3857
3858                n2 = [myMatch2 count];
3859                for(i2 = 0; i2 < n2; i2++)
3860                {
3861                    [tb2 setObject: [[myMatch2 objectAtIndex: i2] groupAtIndex: 2]
3862                            forKey: [[myMatch2 objectAtIndex: i2] groupAtIndex: 1]];
3863                }
3864#endif
3865#ifdef IFVER1
3866                [tb2 setObject: [myMatch groupAtIndex: 4] forKey: [myMatch groupAtIndex: 3]];
3867#endif
3868                [theBase setObject: tb2 forKey: [myMatch groupAtIndex: 2]];
3869            }
3870        }
3871        else
3872        {
3873            theBase = [NSMutableDictionary dictionary];//[[NSMutableDictionary alloc] init];
3874            tb2 = [NSMutableDictionary dictionary];// [[NSMutableDictionary alloc] init];
3875#ifdef IFVER1
3876                [tb2 setObject: [myMatch groupAtIndex: 4] forKey: [myMatch groupAtIndex: 3]];
3877#endif
3878#ifdef IFVER2
3879                {
3880                    int n2, i2;
3881
3882                    n2 = [myMatch2 count];
3883                    for(i2 = 0; i2 < n2; i2++)
3884                    {
3885                        [tb2 setObject: [[myMatch2 objectAtIndex: i2] groupAtIndex: 2]
3886                                forKey: [[myMatch2 objectAtIndex: i2] groupAtIndex: 1]];
3887                    }
3888                }
3889#endif
3890                [theBase setObject: tb2 forKey: [myMatch groupAtIndex: 2]];
3891                [repCont setObject: theBase forKey: [myMatch groupAtIndex: 1]];
3892        }
3893    }
3894
3895    //apply changes to any universals
3896    [self doContWithDict: univVault];
3897
3898}
3899#ifdef FIELDMAP
3900-(void) handleMap: (NSString *) namelist
3901{
3902    NSArray *aa, *bb;
3903    NSMutableString *ss, *tt;
3904    ss = [NSMutableString string];
3905    tt = [NSMutableString string];
3906    aa = [namelist componentsSeparatedByString:  @","];
3907    //break up the commas
3908
3909    //for each
3910    FORALL(aa)
3911    {
3912        bb = [temp componentsSeparatedByString: @"->"];
3913        //separate out the parts for each
3914        //copy to a nsmutalbestring
3915        if([bb count] != 2) continue;
3916        [ss setString: [bb objectAtIndex: 0]];
3917        trimNSS(ss);
3918
3919        [tt setString: [bb objectAtIndex: 1]];
3920        trimNSS(tt);
3921
3922        [fieldMap setObject: tt forKey: ss];
3923    }ENDFORALL;
3924
3925    //strip them
3926    //add to dictionary
3927}
3928#endif
3929-(void) handleSetRepeat: (NSString *) namelist
3930{
3931    NSMutableArray *myUList;
3932    int n;
3933    NSMutableString *s1, *s2, *s3;
3934    NSMutableArray *oneUVar;
3935    NSEnumerator *myen;
3936
3937    s1 = [[NSMutableString alloc] init];
3938    s2 = [[NSMutableString alloc] init];
3939
3940    myUList = convertStringToArray(namelist, ',');
3941    myen = [myUList objectEnumerator];
3942    n = [myUList count];
3943    [s1 setString: @""];
3944    [s2 setString: @""];
3945    while(s3 = [myen nextObject])
3946    {
3947	oneUVar = convertStringToArray(s3, '=');
3948	if([oneUVar count] == 2)
3949	{
3950	    [s1 setString: [oneUVar objectAtIndex: 0]];
3951	    trimNSS(s1);
3952	    [s2 setString: [oneUVar objectAtIndex: 1]];
3953	    trimNSS(s2);
3954
3955	    //add to both the list and the dictionary
3956	    trimNSS(s2);
3957	    trimCharNSS(s2,'\"');
3958            if(arrayContainsString(repList, s1) == NO)
3959                [repList addObject: [s1 copy]];
3960            if([self isRepeat: s1] && [self isInnerRepeat: s1])
3961                [self handleEnd: YES flush: NO];
3962            [self assignRepeat: [[s1 copy] autorelease] withValue:  [[s2 copy] autorelease]];
3963	    //[repVault setObject: [[s2 copy] autorelease] forKey:[[s1 copy] autorelease] ];
3964
3965	    [s1 setString: @""];
3966	    [s2 setString: @""];
3967	}
3968    }
3969    //apply contingencies
3970    [self doContWithDict: repVault];
3971}
3972
3973-(void) handleUniversal: (NSString *) namelist
3974{
3975    NSMutableArray *myUList;
3976    int n;
3977    NSMutableString *s1, *s2, *s3;
3978    NSMutableArray *oneUVar;
3979    NSEnumerator *myen;
3980
3981    s1 = [[NSMutableString alloc] init];
3982    s2 = [[NSMutableString alloc] init];
3983
3984    myUList = convertStringToArray(namelist, ',');
3985    myen = [myUList objectEnumerator];
3986    n = [myUList count];
3987    [s1 setString: @""];
3988    [s2 setString: @""];
3989    while(s3 = [myen nextObject])
3990    {
3991	oneUVar = convertStringToArray(s3, '=');
3992	if([oneUVar count] == 2)
3993	{
3994	    [s1 setString: [oneUVar objectAtIndex: 0]];
3995	    trimNSS(s1);
3996	    [s2 setString: [oneUVar objectAtIndex: 1]];
3997	    trimNSS(s2);
3998
3999	    //add to both the list and the dictionary
4000	    trimNSS(s2);
4001	    trimCharNSS(s2,'\"');
4002            if(arrayContainsString(univList, s1) == NO)
4003                [univList addObject: [s1 copy]];
4004	    [univVault setObject: [[s2 copy] autorelease] forKey: [[s1 copy] autorelease]];
4005	    [s1 setString: @""];
4006	    [s2 setString: @""];
4007	}
4008    }
4009    //apply contingencies
4010    [self doContWithDict: univVault];
4011}
4012
4013/* switchboard for the meta commands */
4014-(void) handlemeta: (ctQChar *) myc
4015{
4016    int i;
4017    NSMutableString *buff;
4018    buff = [[NSMutableString alloc] init];
4019    /* trim the data */
4020
4021    if([[myc extra] length])
4022    {
4023        i = 0;
4024        while([[myc extra] characterAtIndex: i] == ' ')
4025        {
4026            i++;
4027            if(i >= [[myc extra] length]) break;
4028        }
4029        [buff setString: [[myc extra] substringFromIndex: i]];
4030    }
4031    else [buff setString: @""];
4032    ON(@"end")
4033    {
4034        SETGLOBAL(@"basicflag",0);
4035        [self handleEnd: NO flush: NO];
4036        if([self global: @"skipinneratend"] == 1)
4037            innerRFlag = 0;
4038    }
4039    else ON(@"backloadrepeat")
4040        SETGLOBAL(@"backloadrepeatflag", 1);
4041    else ON(@"frontloadrepeat") SETGLOBAL(@"backloadrepeatflag", 0);
4042    else ON(@"endsection"){
4043        SETGLOBAL(@"basicflag", 0);
4044        [self handleEnd: YES flush: NO];
4045        if([self global: @"skipinneratend"] == 1)
4046            innerRFlag = 0;
4047    }
4048    //media
4049    else ON(@"mediafile") {
4050        [mediaDict setObject: [[[myc extra] copy] autorelease] forKey:[[[[myc source] path] copy] autorelease] ];
4051    }
4052    //repeat and ailiases
4053    else ON(@"repeat")
4054        [self addToList: repList usingString: buff];
4055    else ON(@"context")
4056        [self addToList: repList usingString: buff];
4057    else ON(@"contextcode")
4058        [self addToList: repList usingString: buff];
4059    //inner and aliases
4060    else ON(@"first") {[lastRepList removeAllObjects]; [innerRepList removeAllObjects];[self addToList: innerRepList usingString: buff]; SETGLOBAL(@"basicflag",0);}
4061    else ON(@"inner") {[lastRepList removeAllObjects]; [innerRepList removeAllObjects];[self addToList: innerRepList usingString: buff]; SETGLOBAL(@"basicflag",0);}
4062    else ON(@"innerrepeat") {[lastRepList removeAllObjects]; [innerRepList removeAllObjects];[self addToList: innerRepList usingString: buff]; SETGLOBAL(@"basicflag",0);}
4063    else ON(@"firstrepeat") {[lastRepList removeAllObjects]; [innerRepList removeAllObjects];[self addToList: innerRepList usingString: buff]; SETGLOBAL(@"basicflag",0);}
4064    else ON(@"skipinnertopofdoc")
4065    {
4066        SETGLOBAL(@"skipinnertopofdoc",1);
4067        innerRFlag = 0;
4068    }
4069    else ON(@"noskipinnertopofdoc")
4070    {
4071        SETGLOBAL(@"skipinnertopofdoc",0);
4072        innerRFlag = 1;
4073    }
4074    else ON(@"skipinneratend") SETGLOBAL(@"skipinneratend",1);
4075    else ON(@"noskipinneratend") SETGLOBAL(@"skipinneratend",0);
4076    //last repeat and aliases
4077    else ON(@"lastrepeat")
4078    {SETGLOBAL(@"basicflag",0); [innerRepList removeAllObjects]; [lastRepList removeAllObjects]; [self addToList: lastRepList usingString: buff];SETGLOBAL(@"lastRepeat",0);}
4079    else ON(@"last")
4080    {[innerRepList removeAllObjects]; [lastRepList removeAllObjects]; [self addToList: lastRepList usingString: buff];SETGLOBAL(@"lastRepeat",0);}
4081#ifdef FIELDMAP
4082    else ON(@"zapmap")
4083        [fieldMap removeAllObjects];
4084#endif
4085    //struct and unstruct and aliases
4086    else ON(@"basic")
4087        SETGLOBAL(@"basicflag", 1);
4088    else ON(@"unstruct")
4089        SETGLOBAL(@"basicflag", 1);
4090    else ON(@"unstructured")
4091        SETGLOBAL(@"basicflag", 1);
4092    else ON(@"structured")
4093        SETGLOBAL(@"basicflag",0);
4094    else ON(@"struct")
4095        SETGLOBAL(@"basicflag",0);
4096
4097    else ON(@"block")
4098        [self addToList: blockList usingString: buff];
4099    else ON(@"universal")
4100        [self handleUniversal: buff];
4101    else ON(@"setrepeat")
4102        [self handleSetRepeat: buff];
4103    else ON(@"name")
4104    {
4105        if([self isUniversal: @"FileName"] == NO)
4106            [univList addObject: @"FileName"];
4107        [univVault setObject: trimCharNSS(trimNSS(buff), '\"') forKey: @"FileName"];
4108
4109    }
4110    else ON(@"setcomment") [self setComment: buff];
4111    else ON(@"appendcomment") [self appendComment: buff];
4112    else ON(@"endcomment") [self endComment: buff];
4113    else ON(@"endlastcomment") [self endLastComment];
4114    else ON(@"clearcomments") [self clearComments];
4115    else ON(@"zapuniversal") SETGLOBAL(@"zapuniversal", 1);
4116    else ON(@"sectionsearch") SETGLOBAL(@"sectionsearch", 1);
4117    else ON(@"nozapuniversal") SETGLOBAL(@"zapuniversal", 0);
4118    else ON(@"nopar") SETGLOBAL(@"noparflag ", 0);
4119    else ON(@"par") SETGLOBAL(@"noparflag", 0);
4120    else ON(@"empty") SETGLOBAL(@"emptyflag", 0);
4121    else ON(@"noempty") SETGLOBAL(@"emptyflag", 0);
4122    else ON(@"emptysection") SETGLOBAL(@"emptysectionflag",1);
4123    else ON(@"noemptysection") SETGLOBAL(@"emptysectionflag",0);
4124    else ON(@"if") {[self handleIf: buff];}
4125#ifdef FIELDMAP
4126    else ON(@"map") {[self handleMap: buff];}
4127#endif
4128    else ON(@"escapeon") SETGLOBAL(@"escapeflag", 1);
4129    else ON(@"escapeoff") SETGLOBAL(@"escapeflag", 0);
4130    else ON(@"start")
4131        SETGLOBAL(@"startflag", 1);
4132    else ON(@"stop")
4133        SETGLOBAL(@"startflag", 0);
4134    //else ON(@"zap")
4135    //	handlezap();
4136    else ON(@"clean")
4137    {
4138        SETGLOBAL(@"cleanflag", 1);
4139        [repVault removeAllObjects];
4140    }
4141    else ON(@"dirty")
4142        SETGLOBAL(@"cleanflag", 0);
4143    else ON(@"tab")
4144        SETGLOBAL(@"tabflag", 1);
4145    else ON(@"notab")
4146        SETGLOBAL(@"tabflag", 0);
4147    else ON(@"eofisend") SETGLOBAL(@"eofIsEndFlag", 1);
4148    else ON(@"eofisnotend") SETGLOBAL(@"eofIsEndFlag", 0);
4149    else ON(@"limit")
4150    {
4151        SETGLOBAL(@"limitflag", 0);
4152        if(limitString == nil)
4153        {
4154            limitString = [[NSMutableString alloc] init];
4155        }
4156        [limitString setString: buff];
4157    }
4158    //else ON(@"zero")
4159    //	handlezero();
4160    //else ON(@"zerozero")
4161    //	zeromark = 0L;
4162    else ON(@"header") {SETGLOBAL(@"headerflag", 1); SETGLOBAL(@"firstwriteflag", 0);}
4163    else ON(@"noheader") {SETGLOBAL(@"headerflag", 0);
4164        SETGLOBAL(@"firstwriteflag", 0);}
4165    else ON(@"quote") SETGLOBAL(@"quoteflag", 1);
4166    else ON(@"noquote") SETGLOBAL(@"quoteflag", 0);
4167    else ON(@"exact") SETGLOBAL(@"exactflag", 1);
4168    else ON(@"notexact") SETGLOBAL(@"exactflag", 0);
4169    else ON(@"raw") SETGLOBAL(@"rawflag", 1);
4170    else ON(@"notraw") SETGLOBAL(@"rawflag", 0);
4171    else ON(@"append") [fmode setString: @"a"];
4172    else ON(@"notappend") [fmode setString: @"w"];
4173    //else ON(@"conname") handlecon(buff.val());
4174    //else ON(@"datname") handledat(buff.val());
4175    //else ON(@"macnl") setnewline(MACNL);
4176    //else ON(@"unixnl") setnewline(UNIXNL);
4177    else ON(@"noblank") SETGLOBAL(@"blankflag", 0);
4178    else ON(@"blank") SETGLOBAL(@"blankflag", 1);
4179    else ON(@"paranum") SETGLOBAL(@"lineflag", 0);
4180    else ON(@"noparanum") SETGLOBAL(@"lineflag", 0);
4181    else ON(@"recnum") SETGLOBAL(@"lnumflag", 1);
4182    else ON(@"norecnum") SETGLOBAL(@"lnumflag", 0);
4183    else ON(@"dummy") ;
4184    else ON(@"comment");
4185    else ;
4186
4187}
4188-(NSMutableString *) limString
4189{
4190    if(limitString)
4191        return limitString;
4192    else
4193        return @"";
4194}
4195
4196-(IBAction) toggleCaseSensitive: (id) sender
4197{
4198    int state;
4199    if(caseSortFlag == NO)
4200    {
4201	NSLog(@"about to turn on case\n");
4202        [[[NSApp delegate] caseMenuItem] setState: NSOffState];
4203        caseSortFlag = YES;
4204	NSLog(@"turned on case\n");
4205    }
4206    else
4207    {
4208	NSLog(@"about to turn off case\n");
4209        [[[NSApp delegate] caseMenuItem] setState: NSOnState];
4210	NSLog(@"turned off case\n");
4211        caseSortFlag = NO;
4212    }
4213}
4214-(void) resetCaseSensitive
4215{
4216    if(caseSortFlag == YES)
4217    {
4218        [[[NSApp delegate] caseMenuItem] setState: NSOnState];
4219    }
4220    else
4221    {
4222        [[[NSApp delegate] caseMenuItem] setState: NSOffState];
4223    }
4224}
4225-(BOOL) getCaseSensitive {return caseSortFlag;}
4226
4227-(IBAction) sortUpAZ: (id) sender
4228{
4229    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
4230    [fakeMI setTag: 2];
4231    [fakeMI autorelease];
4232    [self sortUp: fakeMI];
4233}
4234-(IBAction) sortUpDate: (id) sender
4235{
4236    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
4237    [fakeMI setTag: 1];
4238    [fakeMI autorelease];
4239    [self sortUp: fakeMI];
4240}
4241-(IBAction) sortUpCodeWithin: (id) sender
4242{
4243    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
4244    [fakeMI setTag: 15];
4245    [fakeMI autorelease];
4246    [self sortUp: fakeMI];
4247}
4248
4249-(IBAction) sortUpCode: (id) sender
4250{
4251    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
4252    [fakeMI setTag: 5];
4253    [fakeMI autorelease];
4254    [self sortUp: fakeMI];
4255}
4256
4257-(IBAction) sortUpFloat: (id) sender
4258{
4259    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
4260    [fakeMI setTag: 3];
4261    [fakeMI autorelease];
4262    [self sortUp: fakeMI];
4263}
4264
4265-(IBAction) sortUpInt: (id) sender
4266{
4267    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
4268    [fakeMI setTag: 4];
4269    [fakeMI autorelease];
4270    [self sortUp: fakeMI];
4271}
4272-(IBAction) sortUpIntWithin: (id) sender
4273{
4274    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
4275    [fakeMI setTag: 14];
4276    [fakeMI autorelease];
4277    [self sortUp: fakeMI];
4278}
4279-(IBAction) sortUpAZWithin: (id) sender
4280{
4281    NSMenuItem *fakeMI=[[NSMenuItem alloc] init];
4282    [fakeMI setTag: 12];
4283    [fakeMI autorelease];
4284    [self sortUp: fakeMI];
4285}
4286
4287-(IBAction) sortUp: (id) Sender
4288{
4289    //get the column
4290    int n;
4291    int tt;
4292    NSMutableDictionary *ssi;
4293    int myType;
4294    id key;
4295
4296    n = [theResults selectedColumn];
4297    if(n > 0)
4298    {
4299	key = [[[theResults tableColumns] objectAtIndex: n] identifier];
4300	tt = [Sender tag];
4301	if(tt < 10) //not within
4302	{
4303	    [sortStack removeAllObjects];
4304	    myType = tt;
4305	}
4306	else
4307	    myType = tt - 10;
4308
4309        //	ssi = [[MWSortStackItem alloc] initWithID: key direction: YES type: myType dateFormat: dfString codeLevel: aCodeLevel];
4310        ssi = [NSMutableDictionary dictionary];
4311        [ssi setObject: [[key copy] autorelease] forKey: @"col"];
4312        [ssi setObject: [[dfString copy] autorelease] forKey: @"dateFormat"];
4313        [ssi setObject: [NSNumber numberWithBool: YES] forKey: @"up"];
4314        [ssi setObject: [NSNumber numberWithInt: myType] forKey: @"type"];
4315        [ssi setObject: [NSNumber numberWithInt: aCodeLevel] forKey: @"codeLevel"];
4316        if([self getCaseSensitive] == YES) [ssi setObject: @"C" forKey: @"case"];
4317
4318        //	[ssi autorelease];
4319	[sortStack addObject: ssi];
4320	[myData sortUsingFunction: stackComp context: sortStack];
4321        [theResults reloadData];
4322        MAKEDIRTY;
4323
4324    }
4325    else
4326	NSWARNING(@"No data column selected");
4327
4328}
4329-(void) sortData: (NSMutableArray *) who withStack: (NSArray *) stack
4330{
4331    NSMutableArray *a = [[NSMutableArray alloc] init];
4332    FORALL(stack)
4333    {
4334        [a addObject: temp];
4335        [who sortUsingFunction: stackComp context: a];
4336    }
4337    ENDFORALL;
4338    [a release];
4339}
4340-(NSMutableArray *) sortStackCopy
4341{
4342    return [[sortStack copy] autorelease];
4343}
4344
4345-(IBAction) sortDown: (id) Sender
4346{
4347    //get the column
4348    int n;
4349    int tt;
4350    NSMutableDictionary *ssi;
4351    int myType;
4352    id key;
4353    n = [theResults selectedColumn];
4354    if(n > 0)
4355    {
4356	key = [[[theResults tableColumns] objectAtIndex: n] identifier];
4357	tt = [Sender tag];
4358	if(tt < 10) //not within
4359	{
4360	    [sortStack removeAllObjects];
4361	    myType = tt;
4362	}
4363	else
4364	    myType = tt - 10;
4365
4366	//ssi = [[MWSortStackItem alloc] initWithID: key direction: NO type: myType dateFormat: dfString codeLevel: aCodeLevel];
4367	//[ssi autorelease];
4368        ssi = [NSMutableDictionary dictionary];
4369        [ssi setObject: [[key copy] autorelease] forKey: @"col"];
4370        [ssi setObject: [[dfString copy] autorelease] forKey: @"dateFormat"];
4371        [ssi setObject: [NSNumber numberWithBool: NO] forKey: @"up"];
4372        [ssi setObject: [NSNumber numberWithInt: myType] forKey: @"type"];
4373        [ssi setObject: [NSNumber numberWithInt: aCodeLevel] forKey: @"codeLevel"];
4374        if([self getCaseSensitive] == YES) [ssi setObject: @"C" forKey: @"case"];
4375        [sortStack addObject: ssi];
4376	[myData sortUsingFunction: stackComp context: sortStack];
4377	[theResults reloadData];
4378        MAKEDIRTY;
4379    }
4380    else
4381	NSWARNING (@"No data column selected");
4382
4383
4384
4385}
4386-(IBAction) sortColumn: (id) Sender
4387{
4388    //get the column
4389    int n;
4390    id key;
4391    n = [theResults selectedColumn];
4392    if(n > 0)
4393    {
4394	key = [[[theResults tableColumns] objectAtIndex: n] identifier];
4395        //sort
4396	if([key isEqualToString: @"_begin_loc"] == YES)
4397	    [myData sortUsingFunction: longFwdComp context: key];
4398	else
4399	    [myData sortUsingFunction: stringComp context: key];
4400    }
4401    UPDATERECCOUNT;
4402    [theResults reloadData];
4403
4404}
4405-(IBAction) smartSort: (id) Sender
4406{
4407    //get the column
4408    int n;
4409    id key;
4410    n = [theResults selectedColumn];
4411    if(n > 0)
4412    {
4413	key = [[[theResults tableColumns] objectAtIndex: n] identifier];
4414        //sort
4415	if([key isEqualToString: @"_begin_loc"] == YES ||[key isEqualToString: @"_line_number"] )
4416	    [self sortUpInt: nil];
4417	else if ([key isEqualToString: @"_code"] == YES)
4418	    [self sortUpCode: nil];
4419        else
4420            [self sortUpAZ: nil];
4421    }
4422    UPDATERECCOUNT;
4423    [theResults reloadData];
4424
4425}
4426-(void) dateFmtDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
4427{
4428    if(returnCode == 1)
4429    {
4430        int dtag = [[dateFormatMenu selectedItem] tag];
4431        dfIndex = dtag;
4432	if(dtag == 99)
4433	{
4434	    [dfString setString: [dateFormatOther stringValue]];
4435	}
4436	else
4437	{
4438	    [dfString setString: dateFmt[dtag]];
4439	}
4440        MAKEDIRTY;
4441    }
4442}
4443-(IBAction) okSetDateFmt: (id) Sender
4444{
4445    [dateFormatSheet orderOut: Sender];
4446    [NSApp endSheet: dateFormatSheet returnCode: 1];
4447
4448}
4449-(IBAction) cancelSetDateFmt: (id) Sender
4450{
4451    [dateFormatSheet orderOut: Sender];
4452    [NSApp endSheet: dateFormatSheet returnCode: 0];
4453
4454}
4455-(IBAction) doSetDateFmt: (id) Sender
4456{
4457    NSWindow *who;
4458
4459    if([gPrefBoss detachedSheetValue])
4460        who = nil;
4461    else
4462        who = myWindow;
4463    if(dfIndex < 0) [dateFormatMenu selectItemAtIndex: 0];
4464    else if( dfIndex < 99)
4465    {
4466        [dateFormatMenu selectItemWithTag: dfIndex];
4467        [dateFormatOther setStringValue: @""];
4468    }
4469    else
4470    {
4471        [dateFormatMenu selectItemWithTag: dfIndex];
4472        [dateFormatOther setStringValue: dfString];
4473    }
4474
4475
4476    [NSApp beginSheet: dateFormatSheet
4477       modalForWindow: who
4478	modalDelegate: self
4479       didEndSelector: @selector(dateFmtDidEnd:returnCode:contextInfo:)
4480          contextInfo: nil];
4481
4482}
4483
4484/*---------------------  Selected Records ----------------*/
4485
4486-(NSMutableArray*) handleStep: (NSMutableDictionary *) who onArray: (NSMutableArray *) ss
4487{
4488    NSMutableArray *ans = [NSMutableArray array];
4489    id cstype;
4490    int csIntType;
4491    id extype;
4492    BOOL exBoolType;
4493
4494    if([[who objectForKey: @"stepType"] isEqualToString: @"sel"] == YES)
4495    {
4496        switch( [[who objectForKey: @"mode"] intValue])
4497        {
4498            case SELECTREVERSE:
4499            case SELECTADDITIONAL:
4500                [ans setArray: ss];
4501                [self handleSelect: [[who objectForKey: @"mode"] intValue]
4502                        selectType: [[who objectForKey: @"type"] intValue]
4503                        withString: [who objectForKey: @"searchValue"]
4504                           withCol: [who objectForKey: @"col"]
4505                            floatV: [[who objectForKey: @"float"] intValue]
4506                            regexV: [[who objectForKey: @"regex"] intValue]
4507                        startArray: backData
4508                          endArray: ans];
4509                break;
4510            case SELECTCODESET:
4511                cstype = [who objectForKey: @"type"];
4512                if (cstype == nil)
4513                    csIntType = SELECT;
4514                else
4515                    csIntType = [cstype intValue];
4516                extype = [who objectForKey: @"exact"];
4517                if(extype == nil) exBoolType = YES;
4518                else exBoolType = [extype boolValue];
4519
4520                [self selectDataFrom: ss to: ans forCodeSet: [who objectForKey: @"name"] type: csIntType exact: exBoolType];
4521                break;
4522
4523            default:
4524                [self handleSelect: [[who objectForKey: @"mode"] intValue]
4525                        selectType: [[who objectForKey: @"type"] intValue]
4526                        withString: [who objectForKey: @"searchValue"]
4527                           withCol: [who objectForKey: @"col"]
4528                            floatV: [[who objectForKey: @"float"] intValue]
4529                            regexV: [[who objectForKey: @"regex"] intValue]
4530                        startArray: ss
4531                          endArray: ans];
4532                break;
4533        };
4534
4535    }
4536    //put runing an autoset here
4537    else if([[who objectForKey: @"stepType"] isEqualToString: @"autoset"] == YES)
4538    {
4539        [ans setArray: [self applyAutoSetWithName:
4540
4541              [who objectForKey: @"name"] toArray: ss]];
4542
4543    }
4544
4545    else
4546    {
4547        [self handleSet:
4548            [[who objectForKey: @"op"] intValue]
4549
4550                withSet: [self getAutoSetWithName: [who objectForKey: @"obj"]]
4551             startArray: ss endArray: ans];
4552    }
4553
4554    return ans;
4555}
4556
4557-(NSMutableArray*) getSetWithName: (NSString*) who
4558{
4559    NSMutableArray  *aa;
4560
4561    aa = [namedSelDict objectForKey: who];
4562    if(aa == nil)
4563        return [self getAutoSetWithName: who];
4564    else
4565        return [NSMutableArray arrayWithArray: aa];
4566
4567}
4568-(NSMutableDictionary *) autoHistoryAsProgram
4569{
4570    NSMutableDictionary *myMac = [NSMutableDictionary dictionary];
4571    [myMac setObject: [self autoHistory] forKey: @"program"];
4572    [myMac setObject: @"All" forKey: @"start"];
4573    return myMac;
4574}
4575-(NSMutableArray*) applyAutoSetWithName: (NSString *) who toArray: (NSMutableArray *) showing
4576{
4577    NSMutableArray *ans = [NSMutableArray array];
4578    NSMutableDictionary *myMac;
4579    NSMutableArray *myProg;
4580    NSMutableArray *sData, *s2, *s1;
4581    NSArray *ss;
4582    if([self isAutoSet: who] == NO) return showing;
4583    sData = [[NSMutableArray alloc] init];
4584    myMac = [self autoSetForName: who];
4585
4586    myProg = [myMac objectForKey: @"program"];
4587    ss = [myMac objectForKey: @"sort"];
4588
4589    if([[myMac objectForKey: @"start"] isEqualToString: @"All"] == YES)
4590        [sData addObjectsFromArray: backData];
4591    else if([[myMac objectForKey: @"start"] isEqualToString: @"Visible"] == YES)
4592        [sData addObjectsFromArray: showing];
4593    else
4594        [sData addObjectsFromArray: [self getAutoSetWithName: [myMac objectForKey: @"start"]]];
4595    s2 = sData;
4596    if(ss != nil)
4597        [self sortData: sData withStack: ss];
4598    if(myProg)
4599    {
4600        FORALL(myProg)
4601    {
4602            s1 = [self handleStep: temp onArray: s2];
4603            s2 = s1; //keep sending it back in
4604    }
4605        ENDFORALL;
4606    }
4607    [ans addObjectsFromArray: s2];
4608    [sData release];
4609    return ans;
4610}
4611
4612-(NSMutableArray*) getAutoSetWithName: (NSString *) who
4613{
4614    NSMutableArray *ans = [NSMutableArray array];
4615    NSMutableDictionary *myMac;
4616    NSMutableArray *myProg;
4617    NSMutableArray *sData, *s2, *s1;
4618    NSArray *ss;
4619
4620    sData = [[NSMutableArray alloc] init];
4621    if(who == nil)
4622    {
4623        myMac = [self autoHistoryAsProgram];
4624    }
4625    else
4626        myMac = [self autoSetForName: who];
4627
4628    myProg = [myMac objectForKey: @"program"];
4629    ss = [myMac objectForKey: @"sort"];
4630
4631    if([[myMac objectForKey: @"start"] isEqualToString: @"All"] == YES)
4632        [sData addObjectsFromArray: backData];
4633    else if([[myMac objectForKey: @"start"] isEqualToString: @"Visible"] == YES)
4634        [sData addObjectsFromArray: myData];
4635    else
4636        [sData addObjectsFromArray: [self getAutoSetWithName: [myMac objectForKey: @"start"]]];
4637    s2 = sData;
4638    if(ss != nil)
4639        [self sortData: sData withStack: ss];
4640    if(myProg)
4641    {
4642        FORALL(myProg)
4643    {
4644            s1 = [self handleStep: temp onArray: s2];
4645            s2 = s1; //keep sending it back in
4646    }
4647        ENDFORALL;
4648    }
4649    [ans addObjectsFromArray: s2];
4650    [sData release];
4651    return ans;
4652}
4653-(void) handleSet: (int) opType withSet: (NSArray *) mm startArray: (NSMutableArray*) a1 endArray: (NSMutableArray*) a2
4654{
4655    int i,n;
4656    NSMutableArray *final = [[NSMutableArray alloc] init];
4657
4658    {
4659        //get subset
4660        //mm = [namedSelDict objectForKey: [[setMathSetMenu selectedItem] title]];
4661        //opType = [[setMathOpMenu selectedItem] tag];
4662        switch (opType)
4663        {
4664            case 1: //intersect with
4665                FORALL(mm)
4666            {
4667                    if([a1 indexOfObject: temp] == NSNotFound)
4668                    {
4669                    }
4670                    else
4671                        [final addObject: temp];
4672            }
4673                ENDFORALL;
4674                [a2 addObjectsFromArray: final];
4675                break;
4676
4677            case 2: //union
4678                FORALL(mm)
4679            {
4680                    if([a1 indexOfObject: temp] == NSNotFound)
4681                    {
4682                        [final addObject: temp];
4683                    }
4684            }
4685                ENDFORALL;
4686                [a2 addObjectsFromArray: final];
4687                break;
4688
4689            case 3: //Don't intersect with
4690                n = [mm count];
4691                for(i = 0; i < n; i++)
4692                {
4693                    [a1 removeObject: [mm objectAtIndex: i]];
4694                }
4695                    break;
4696
4697            case 4: //not in union with
4698                n = [backData count];
4699                for(i = 0; i < n; i++)
4700                {
4701                    if([a1 containsObject: [backData objectAtIndex: i]] == YES ||
4702                       [mm containsObject: [backData objectAtIndex: i]] == YES)
4703                    {
4704                    }
4705                    else
4706                    {
4707                        [a1 addObject: [backData objectAtIndex: i]];
4708                    }
4709                }
4710                    [a2 addObjectsFromArray: final];
4711                break;
4712
4713            case 5: // XOR
4714                n = [mm count];
4715                for(i = 0; i < n ; i++)
4716                {
4717                    [a2 addObjectsFromArray: a1];
4718                    if([a2 containsObject: [mm objectAtIndex: i]] == YES)
4719                    {
4720                        [a2 removeObject: [mm objectAtIndex: i]];
4721                    }
4722                    else
4723                    {
4724                        [a2 addObject: [mm objectAtIndex: i]];
4725                    }
4726                }
4727                    break;
4728
4729        };
4730        [final release];
4731    }
4732
4733}
4734
4735-(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
4736{
4737    NSMutableArray *findList, *findFromList;
4738    NSRange a;
4739    AGRegex *myRegex;
4740    AGRegexMatch *myRegexMatch;
4741    NSString *fString;
4742
4743    int n, i, cres, frflag;
4744
4745    findList = [[NSMutableArray alloc] init];
4746    findFromList = [[NSMutableArray alloc] init];
4747    if(selectMode == SELECTREVERSE)
4748    {
4749        [findList setArray: a1];
4750        [findList removeObjectsInArray: a2];
4751        [a2 setArray: findList];
4752        [findList release];
4753        [findFromList release];
4754        return;
4755    }
4756
4757    [findFromList addObjectsFromArray: a1];
4758
4759    n = [findFromList count];
4760    for(i =0; i < n; i++)
4761    {
4762        if([@"_doc" isEqualToString: colName ] == YES)
4763        {
4764            fString =  [(MWFile *)[[findFromList objectAtIndex: i] objectForKey:
4765                colName] name];
4766        }
4767        else
4768            fString = [[findFromList objectAtIndex: i] objectForKey:
4769                colName];
4770	switch(st)
4771	{
4772	    case SELALPHA:
4773                if(rf)
4774                {
4775                    myRegex = [[AGRegex alloc] initWithPattern: compValue
4776                                                       options: AGRegexCaseInsensitive];
4777                    myRegexMatch = [myRegex findInString: fString];
4778                    if([myRegexMatch count])
4779                    {
4780                        [findList addObject: [findFromList objectAtIndex: i]];
4781                    }
4782                    [myRegex release];
4783                    //[myRegexMatch release];
4784                }
4785                else
4786                {
4787                    a = [fString rangeOfString: compValue options: NSCaseInsensitiveSearch];
4788                    if(a.location != NSNotFound)
4789                    {
4790                        [findList addObject: [findFromList objectAtIndex: i]];
4791                    }
4792                }
4793		break;
4794
4795	    case SELALPHACASE:
4796                if(rf)
4797                {
4798                    myRegex = [[AGRegex alloc] initWithPattern: compValue];
4799                    myRegexMatch = [myRegex findInString: fString];
4800                    if([myRegexMatch count])
4801                    {
4802                        [findList addObject: [findFromList objectAtIndex: i]];
4803                    }
4804                    [myRegex release];
4805                    [myRegexMatch release];
4806                }
4807                else
4808                {
4809                    a = [fString  rangeOfString: compValue ];
4810                    if(a.location != NSNotFound)
4811                    {
4812                        [findList addObject: [findFromList objectAtIndex: i]];
4813                    }
4814                }
4815		break;
4816
4817            case SELEXACT: //no regex for this one
4818            {
4819                int ans;
4820                ans = [fString
4821                        isEqualToString: compValue ];
4822                if(ans == YES)
4823                {
4824                    [findList addObject: [findFromList objectAtIndex: i]];
4825                }
4826            }
4827		break;
4828
4829	    case SELEQUAL:
4830		if(fp)
4831		{
4832		    if([fString doubleValue]
4833                       == [compValue doubleValue])
4834		    {
4835			[findList addObject: [findFromList objectAtIndex: i]];
4836		    }
4837		}
4838		else
4839		    if([fString intValue]
4840                       == [compValue intValue])
4841		    {
4842			[findList addObject: [findFromList objectAtIndex: i]];
4843		    }
4844
4845		break;
4846
4847	    case SELGT:
4848		if(fp)
4849		{
4850		    if([fString doubleValue]
4851                       > [compValue doubleValue])
4852		    {
4853			[findList addObject: [findFromList objectAtIndex: i]];
4854		    }
4855		}
4856		else
4857		    if([fString intValue]
4858                       > [compValue intValue])
4859		    {
4860			[findList addObject: [findFromList objectAtIndex: i]];
4861		    }
4862
4863		break;
4864
4865	    case SELGTE:
4866		if(fp)
4867		{
4868		    if([fString doubleValue]
4869                       >= [compValue doubleValue])
4870		    {
4871			[findList addObject: [findFromList objectAtIndex: i]];
4872		    }
4873		}
4874		else
4875		    if([fString intValue]
4876                       >= [compValue intValue])
4877		    {
4878			[findList addObject: [findFromList objectAtIndex: i]];
4879		    }
4880
4881		break;
4882
4883	    case SELLT:
4884		if(fp)
4885		{
4886		    if([fString doubleValue]
4887                       < [compValue doubleValue])
4888		    {
4889			[findList addObject: [findFromList objectAtIndex: i]];
4890		    }
4891		}
4892		else
4893		    if([fString intValue]
4894                       < [compValue intValue])
4895		    {
4896			[findList addObject: [findFromList objectAtIndex: i]];
4897		    }
4898
4899		break;
4900	    case SELLTE:
4901		if(fp)
4902		{
4903		    if([fString doubleValue]
4904                       <= [compValue doubleValue])
4905		    {
4906			[findList addObject: [findFromList objectAtIndex: i]];
4907		    }
4908		}
4909		else
4910		    if([fString intValue]
4911                       <= [compValue intValue])
4912		    {
4913			[findList addObject: [findFromList objectAtIndex: i]];
4914		    }
4915
4916		break;
4917	    case SELDATE:
4918                cres = [(NSDate *) [NSCalendarDate dateWithString:
4919                    fString
4920                                                   calendarFormat: dfString] compare:
4921                    [NSCalendarDate dateWithString: compValue
4922                                    calendarFormat: dfString]];
4923                if(cres == NSOrderedSame)
4924                    [findList addObject: [findFromList objectAtIndex: i]];
4925		    break;
4926
4927	    case SELBEFOREDATE:
4928                cres = [(NSDate *) [NSCalendarDate dateWithString:
4929                    fString
4930                                                   calendarFormat: dfString] compare:
4931                    [NSCalendarDate dateWithString: compValue
4932                                    calendarFormat: dfString]];
4933                if(cres == NSOrderedAscending)
4934                    [findList addObject: [findFromList objectAtIndex: i]];
4935		    break;
4936
4937	    case SELAFTERDATE:
4938                cres = [(NSDate *) [NSCalendarDate dateWithString:
4939                    fString
4940                                                   calendarFormat: dfString] compare:
4941                    [NSCalendarDate dateWithString: compValue
4942                                    calendarFormat: dfString]];
4943                if(cres == NSOrderedDescending)
4944                    [findList addObject: [findFromList objectAtIndex: i]];
4945		    break;
4946
4947	    case SELBEFOREEQDATE:
4948                cres = [(NSDate *) [NSCalendarDate dateWithString:
4949                    fString
4950                                                   calendarFormat: dfString] compare:
4951                    [NSCalendarDate dateWithString: compValue
4952                                    calendarFormat: dfString]];
4953                if(cres == NSOrderedAscending || cres == NSOrderedSame)
4954                    [findList addObject: [findFromList objectAtIndex: i]];
4955		    break;
4956
4957	    case SELAFTEREQDATE:
4958                cres = [(NSDate *) [NSCalendarDate dateWithString:
4959                    fString
4960                                                   calendarFormat: dfString] compare:
4961                    [NSCalendarDate dateWithString: compValue
4962                                    calendarFormat: dfString]];
4963                if(cres == NSOrderedDescending || cres == NSOrderedSame)
4964                    [findList addObject: [findFromList objectAtIndex: i]];
4965		    break;
4966
4967
4968
4969	    default: ;
4970	}
4971    }
4972    if(selectMode == SELECTADDITIONAL)
4973    {
4974	n = [findList count];
4975	if(n == 0)
4976        {
4977            NSWARNING(@"No records found");
4978            frflag=0;
4979        }
4980	else
4981	{
4982            frflag = 1;
4983	    for(i = 0; i<n; i++)
4984	    {
4985		if([a2 indexOfObject: [findList objectAtIndex: i]]
4986                   == NSNotFound)
4987		{
4988		    [a2 addObject: [findList objectAtIndex: i]];
4989		}
4990	    }
4991	}
4992    }
4993    else if(selectMode == SELECTFEWER)
4994    {
4995	n = [findList count];
4996	if(n == 0)
4997        {
4998            NSWARNING(@"No records found");
4999            frflag=0;
5000        }
5001	else
5002	{
5003            [a2 setArray: a1];
5004            [a2 removeObjectsInArray: findList];
5005
5006        }
5007
5008    }
5009    else if (selectMode == SELECT)
5010    {
5011	if([findList count] == 0)
5012        {
5013            NSWARNING(@"No records found");
5014            frflag = 0;
5015        }
5016	else
5017	{
5018	    [a2 removeAllObjects];
5019	    [a2 addObjectsFromArray: findList];
5020            frflag = 1;
5021	}
5022    }
5023    //Clean up
5024    [findList release];
5025    [findFromList release];
5026
5027}
5028
5029-(void) selectDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
5030{
5031    NSMutableArray *findList, *findFromList;
5032    NSMutableString *compValue;
5033    NSRange a;
5034    AGRegex *myRegex;
5035    AGRegexMatch *myRegexMatch;
5036    NSString *fString;
5037
5038    int rr, n, st, fp, rf, i, cres, frflag;
5039    if(returnCode == 0) return;
5040    rr = [theResults selectedRow];
5041    findList = [[NSMutableArray alloc] init];
5042    findFromList = [[NSMutableArray alloc] init];
5043    compValue = [[NSMutableString alloc] init];
5044    [compValue setString: [selectField stringValue]];
5045    st = [[selectMenu selectedItem] tag];
5046    fp = [selectFloat intValue];
5047    rf = [selectRegexFlag intValue];
5048    frflag = 0;
5049    //this block is for autohistory
5050    {
5051        NSMutableDictionary *ahd = [NSMutableDictionary dictionary];
5052        [ahd setObject: @"sel" forKey: @"stepType"];
5053        [ahd setObject: [NSNumber numberWithInt: selectMode] forKey: @"mode"];
5054        [ahd setObject: [NSNumber numberWithInt: st] forKey: @"type"];
5055        [ahd setObject: [[compValue copy] autorelease] forKey: @"searchValue"];
5056        [ahd setObject: [[SELECTEDCOLUMNID(theResults) copy] autorelease] forKey: @"col"];
5057        [ahd setObject: [NSNumber numberWithInt: fp] forKey: @"float"];
5058        [ahd setObject: [NSNumber numberWithInt: rf] forKey: @"regex"];
5059        [autoHistory addObject: ahd];
5060    }
5061    if(selectMode == SELECTADDITIONAL)
5062    {
5063	[findFromList addObjectsFromArray: backData];
5064    }
5065    else
5066    {
5067	[findFromList addObjectsFromArray: myData];
5068    }
5069    n = [findFromList count];
5070    for(i =0; i < n; i++)
5071    {
5072        if([@"_doc" isEqualToString: SELECTEDCOLUMNID(theResults) ] == YES)
5073        {
5074            fString =  [(MWFile *)[[findFromList objectAtIndex: i] objectForKey:
5075                SELECTEDCOLUMNID(theResults)] name];
5076        }
5077        else
5078            fString = [[findFromList objectAtIndex: i] objectForKey:
5079                SELECTEDCOLUMNID(theResults)];
5080	switch(st)
5081	{
5082	    case SELALPHA:
5083                if(rf)
5084                {
5085                    myRegex = [[AGRegex alloc] initWithPattern: compValue
5086                                                       options: AGRegexCaseInsensitive];
5087                    myRegexMatch = [myRegex findInString: fString];
5088                    if([myRegexMatch count])
5089                    {
5090                        [findList addObject: [findFromList objectAtIndex: i]];
5091                    }
5092                    [myRegex release];
5093                    //[myRegexMatch release];
5094                }
5095                else
5096                {
5097                    a = [fString rangeOfString: compValue options: NSCaseInsensitiveSearch];
5098                    if(a.location != NSNotFound)
5099                    {
5100                        [findList addObject: [findFromList objectAtIndex: i]];
5101                    }
5102                }
5103		break;
5104
5105	    case SELALPHACASE:
5106                if(rf)
5107                {
5108                    myRegex = [[AGRegex alloc] initWithPattern: compValue];
5109                    myRegexMatch = [myRegex findInString: fString];
5110                    if([myRegexMatch count])
5111                    {
5112                        [findList addObject: [findFromList objectAtIndex: i]];
5113                    }
5114                    [myRegex release];
5115                    [myRegexMatch release];
5116                }
5117                else
5118                {
5119                    a = [fString  rangeOfString: compValue ];
5120                    if(a.location != NSNotFound)
5121                    {
5122                        [findList addObject: [findFromList objectAtIndex: i]];
5123                    }
5124                }
5125		break;
5126
5127            case SELEXACT: //no regex for this one
5128            {
5129                int ans;
5130                ans = [fString
5131                        isEqualToString: compValue ];
5132                if(ans == YES)
5133                {
5134                    [findList addObject: [findFromList objectAtIndex: i]];
5135                }
5136            }
5137		break;
5138
5139	    case SELEQUAL:
5140		if(fp)
5141		{
5142		    if([fString doubleValue]
5143                       == [compValue doubleValue])
5144		    {
5145			[findList addObject: [findFromList objectAtIndex: i]];
5146		    }
5147		}
5148		else
5149		    if([fString intValue]
5150                       == [compValue intValue])
5151		    {
5152			[findList addObject: [findFromList objectAtIndex: i]];
5153		    }
5154
5155		break;
5156
5157	    case SELGT:
5158		if(fp)
5159		{
5160		    if([fString doubleValue]
5161                       > [compValue doubleValue])
5162		    {
5163			[findList addObject: [findFromList objectAtIndex: i]];
5164		    }
5165		}
5166		else
5167		    if([fString intValue]
5168                       > [compValue intValue])
5169		    {
5170			[findList addObject: [findFromList objectAtIndex: i]];
5171		    }
5172
5173		break;
5174
5175	    case SELGTE:
5176		if(fp)
5177		{
5178		    if([fString doubleValue]
5179                       >= [compValue doubleValue])
5180		    {
5181			[findList addObject: [findFromList objectAtIndex: i]];
5182		    }
5183		}
5184		else
5185		    if([fString intValue]
5186                       >= [compValue intValue])
5187		    {
5188			[findList addObject: [findFromList objectAtIndex: i]];
5189		    }
5190
5191		break;
5192
5193	    case SELLT:
5194		if(fp)
5195		{
5196		    if([fString doubleValue]
5197                       < [compValue doubleValue])
5198		    {
5199			[findList addObject: [findFromList objectAtIndex: i]];
5200		    }
5201		}
5202		else
5203		    if([fString intValue]
5204                       < [compValue intValue])
5205		    {
5206			[findList addObject: [findFromList objectAtIndex: i]];
5207		    }
5208
5209		break;
5210	    case SELLTE:
5211		if(fp)
5212		{
5213		    if([fString doubleValue]
5214                       <= [compValue doubleValue])
5215		    {
5216			[findList addObject: [findFromList objectAtIndex: i]];
5217		    }
5218		}
5219		else
5220		    if([fString intValue]
5221                       <= [compValue intValue])
5222		    {
5223			[findList addObject: [findFromList objectAtIndex: i]];
5224		    }
5225
5226		break;
5227	    case SELDATE:
5228                cres = [(NSDate *) [NSCalendarDate dateWithString:
5229                    fString
5230                                                   calendarFormat: dfString] compare:
5231                    [NSCalendarDate dateWithString: compValue
5232                                    calendarFormat: dfString]];
5233                if(cres == NSOrderedSame)
5234                    [findList addObject: [findFromList objectAtIndex: i]];
5235		    break;
5236
5237	    case SELBEFOREDATE:
5238                cres = [(NSDate *) [NSCalendarDate dateWithString:
5239                    fString
5240                                                   calendarFormat: dfString] compare:
5241                    [NSCalendarDate dateWithString: compValue
5242                                    calendarFormat: dfString]];
5243                if(cres == NSOrderedAscending)
5244                    [findList addObject: [findFromList objectAtIndex: i]];
5245		    break;
5246
5247	    case SELAFTERDATE:
5248                cres = [(NSDate *) [NSCalendarDate dateWithString:
5249                    fString
5250                                                   calendarFormat: dfString] compare:
5251                    [NSCalendarDate dateWithString: compValue
5252                                    calendarFormat: dfString]];
5253                if(cres == NSOrderedDescending)
5254                    [findList addObject: [findFromList objectAtIndex: i]];
5255		    break;
5256
5257	    case SELBEFOREEQDATE:
5258                cres = [(NSDate *) [NSCalendarDate dateWithString:
5259                    fString
5260                                                   calendarFormat: dfString] compare:
5261                    [NSCalendarDate dateWithString: compValue
5262                                    calendarFormat: dfString]];
5263                if(cres == NSOrderedAscending || cres == NSOrderedSame)
5264                    [findList addObject: [findFromList objectAtIndex: i]];
5265		    break;
5266
5267	    case SELAFTEREQDATE:
5268                cres = [(NSDate *) [NSCalendarDate dateWithString:
5269                    fString
5270                                                   calendarFormat: dfString] compare:
5271                    [NSCalendarDate dateWithString: compValue
5272                                    calendarFormat: dfString]];
5273                if(cres == NSOrderedDescending || cres == NSOrderedSame)
5274                    [findList addObject: [findFromList objectAtIndex: i]];
5275		    break;
5276
5277
5278
5279	    default: ;
5280	}
5281    }
5282    if(selectMode == SELECTADDITIONAL)
5283    {
5284	n = [findList count];
5285	if(n == 0)
5286        {
5287            NSWARNING(@"No records found");
5288            frflag=0;
5289        }
5290	else
5291	{
5292            frflag = 1;
5293	    for(i = 0; i<n; i++)
5294	    {
5295		if([myData indexOfObject: [findList objectAtIndex: i]]
5296                   == NSNotFound)
5297		{
5298		    [myData addObject: [findList objectAtIndex: i]];
5299		}
5300	    }
5301	}
5302    }
5303    else if(selectMode == SELECTFEWER)
5304    {
5305	n = [findList count];
5306	if(n == 0)
5307        {
5308            NSWARNING(@"No records found");
5309            frflag=0;
5310        }
5311	else
5312	{
5313            [myData removeObjectsInArray: findList];
5314            frflag = 1;
5315        }
5316
5317    }
5318    else if (selectMode == SELECT)
5319    {
5320	if([findList count] == 0)
5321        {
5322            NSWARNING(@"No records found");
5323            frflag = 0;
5324        }
5325	else
5326	{
5327	    [myData removeAllObjects];
5328	    [myData addObjectsFromArray: findList];
5329            frflag = 1;
5330	}
5331    }
5332    if(frflag)
5333        if(selectMode ==SELECTADDITIONAL)
5334            [self addStateString: [NSString stringWithFormat: @"+%@: %@", compValue,
5335                SELECTEDCOLUMNID(theResults)]];
5336        else if(selectMode ==SELECTFEWER)
5337            [self addStateString: [NSString stringWithFormat: @"-%@: %@", compValue,
5338                SELECTEDCOLUMNID(theResults)]];
5339        else
5340            [self addStateString: [NSString stringWithFormat: @"%@: %@", compValue,
5341                SELECTEDCOLUMNID(theResults)]];
5342    [self updateRecCountVertical];
5343    [theResults reloadData];
5344    //Clean up
5345    [findList release];
5346    [findFromList release];
5347    [compValue release];
5348
5349}
5350
5351-(IBAction) doSelect: (id) Sender
5352{
5353    [self pushSetStack];
5354    [selectSheet orderOut: Sender];
5355    [NSApp endSheet: selectSheet returnCode: 1];
5356
5357}
5358-(IBAction) cancelSelect: (id) Sender
5359{
5360    [selectSheet orderOut: Sender];
5361    [NSApp endSheet: selectSheet returnCode: 0];
5362
5363}
5364-(NSMutableArray *) allData {return backData;}
5365
5366-(IBAction) selectAllRecs: (id) Sender
5367{
5368    [self pushSetStack];
5369    [myData removeAllObjects];
5370    [autoHistory removeAllObjects];
5371    [autoHistoryStart setString: @""];
5372    [myData addObjectsFromArray: backData];
5373    [theResults reloadData];
5374    [self updateRecCountVertical];
5375    [self setOriginalStateString];
5376}
5377-(IBAction) selectAdditionalRecs: (id) Sender
5378{
5379    int n;
5380    NSWindow *who;
5381
5382    if([gPrefBoss detachedSheetValue])
5383        who = nil;
5384    else
5385        who = myWindow;
5386    //check if col is selected
5387    n = [theResults selectedColumn];
5388    if(n <= 0)
5389    {
5390	NSWARNING(@"You must pick a column to select data within.");
5391	return;
5392    }
5393
5394    //if yes put up the sheet
5395    //save the type of search
5396    selectMode = SELECTADDITIONAL;
5397    //first fill in the blank!
5398    [selectField setStringValue: @""];
5399    [selectMenu selectItemAtIndex: 0];
5400    [selectRegexFlag setIntValue: 0];
5401    [selectFloat setIntValue: 0];
5402    [NSApp beginSheet: selectSheet
5403       modalForWindow: who
5404	modalDelegate: self
5405       didEndSelector: @selector(selectDidEnd:returnCode:contextInfo:)
5406          contextInfo: nil];
5407
5408}
5409-(IBAction) selectFewerRecs: (id) Sender
5410{
5411    int n;
5412    NSWindow *who;
5413
5414    if([gPrefBoss detachedSheetValue])
5415        who = nil;
5416    else
5417        who = myWindow;
5418    //check if col is selected
5419    n = [theResults selectedColumn];
5420    if(n <= 0)
5421    {
5422	NSWARNING(@"You must pick a column to select data within.");
5423	return;
5424    }
5425
5426    //if yes put up the sheet
5427    //save the type of search
5428    selectMode = SELECTFEWER;
5429    //first fill in the blank!
5430    [selectField setStringValue: @""];
5431    [selectMenu selectItemAtIndex: 0];
5432    [selectRegexFlag setIntValue: 0];
5433    [selectFloat setIntValue: 0];
5434    [NSApp beginSheet: selectSheet
5435       modalForWindow: who
5436	modalDelegate: self
5437       didEndSelector: @selector(selectDidEnd:returnCode:contextInfo:)
5438          contextInfo: nil];
5439
5440}
5441
5442-(IBAction) selectRecs: (id) Sender
5443{
5444    int n;
5445    NSWindow *who;
5446    //check if col is selected
5447    n = [theResults selectedColumn];
5448    if(n <= 0)
5449    {
5450	NSWARNING(@"You must pick a column to select data within.");
5451	return;
5452    }
5453
5454    //if yes put up the sheet
5455    //save the type of search
5456    selectMode = SELECT;
5457    //first fill in the blank!
5458    [selectField setStringValue: @""];
5459    [selectMenu selectItemAtIndex: 0];
5460    [selectRegexFlag setIntValue: 0];
5461    [selectFloat setIntValue: 0];
5462    if([gPrefBoss detachedSheetValue])
5463        who = nil;
5464    else
5465        who = myWindow;
5466    [NSApp beginSheet: selectSheet
5467       modalForWindow: who
5468	modalDelegate: self
5469       didEndSelector: @selector(selectDidEnd:returnCode:contextInfo:)
5470          contextInfo: nil];
5471
5472}
5473-(IBAction) selectReverseRecs: (id) Sender
5474{
5475    int i,n;
5476    NSMutableArray *findData;
5477
5478    findData = [[NSMutableArray alloc] init];
5479
5480    n = [backData count];
5481    for(i = 0; i < n; i++)
5482    {
5483        if([myData indexOfObject: [backData objectAtIndex: i]] == NSNotFound)
5484        {
5485            [findData addObject: [backData objectAtIndex: i]];
5486        }
5487    }
5488    if([findData count] <= 0)
5489    {
5490	NSWARNING(@"No data found.");
5491	return;
5492    }
5493    //this block is for autohistory
5494    {
5495        NSMutableDictionary *ahd = [NSMutableDictionary dictionary];
5496        [ahd setObject: @"sel" forKey: @"stepType"];
5497        [ahd setObject: [NSNumber numberWithInt: SELECTREVERSE] forKey: @"mode"];
5498        [autoHistory addObject: ahd];
5499    }
5500    [self pushSetStack];
5501    [myData removeAllObjects];
5502    [myData addObjectsFromArray: findData];
5503    [findData release];
5504    UPDATERECCOUNT;
5505    [theResults reloadData];
5506    [self addStateString: @"reversed"];
5507}
5508
5509-(IBAction) removeSelected: (id) Sender
5510{
5511    if(NSYESNOQUESTION(@"Really remove the selected from the dataset?") == NO) return;
5512    [backData removeObjectsInArray: myData];
5513    [myData removeAllObjects];
5514    [myData addObjectsFromArray: backData];
5515    [self clearNamedSelMenu: nil];
5516    [self zeroSetStack];
5517    UPDATERECCOUNT;
5518    [theResults reloadData];
5519    [self setOriginalStateString];
5520    [self addStateString: @"-selected"];
5521}
5522
5523-(IBAction) removeUnselected: (id) Sender
5524{
5525    if(NSYESNOQUESTION(@"Really remove the unselected from the dataset?") == NO) return;
5526    [backData removeAllObjects];
5527    [backData addObjectsFromArray: myData];
5528    [self clearNamedSelMenu: nil];
5529    [self zeroSetStack];
5530    UPDATERECCOUNT;
5531    [theResults reloadData];
5532    [self setOriginalStateString];
5533    [self addStateString: @"-unselected"];
5534}
5535
5536-(IBAction) selectMarked: (id) Sender
5537{
5538    int i, n;
5539    NSMutableArray *fd = [[NSMutableArray alloc] init];
5540    n = [backData count];
5541    for(i = 0; i < n; i++)
5542    {
5543        if([self isMarkedRecord: [backData objectAtIndex: i]] == YES)
5544            [fd addObject: [backData objectAtIndex: i]];
5545    }
5546    if([fd count])
5547    {
5548        [self pushSetStack];
5549        [myData removeAllObjects];
5550        [myData addObjectsFromArray: fd];
5551        UPDATERECCOUNT;
5552        [theResults reloadData];
5553    }
5554    else
5555    {
5556        NSWARNING(@"No marked records");
5557    }
5558    [fd release];
5559    [self setStateString: @"marked"];
5560
5561}
5562
5563-(IBAction) addMarkedToSelected: (id) Sender;
5564{
5565    [self pushSetStack];
5566    FORALL(backData)
5567    {
5568        if([self isMarkedRecord: temp] == YES)
5569        {
5570            if([myData indexOfObject: temp] == NSNotFound)
5571            {
5572                [myData addObject: temp];
5573            }
5574        }
5575    }ENDFORALL;
5576    UPDATERECCOUNT;
5577    [theResults reloadData];
5578    [self addStateString: @"+marked"];
5579}
5580
5581-(IBAction) addUnmarkedToSelected: (id) Sender;
5582{
5583    [self pushSetStack];
5584    FORALL(backData)
5585    {
5586        if([self isMarkedRecord: temp] == NO)
5587        {
5588            if([myData indexOfObject: temp] == NSNotFound)
5589            {
5590                [myData addObject: temp];
5591            }
5592        }
5593    }ENDFORALL;
5594    UPDATERECCOUNT;
5595    [theResults reloadData];
5596    [self addStateString: @"+unmarked"];
5597
5598}
5599
5600-(IBAction) removeUnmarkedFromSelected: (id) Sender;
5601{
5602    NSMutableArray *found = [[NSMutableArray alloc] init];
5603    FORALL(myData)
5604    {
5605        if([self isMarkedRecord: temp] == YES)
5606        {
5607            [found addObject: temp];
5608        }
5609    }ENDFORALL;
5610    if([found count])
5611    {
5612        [self pushSetStack];
5613        [myData removeAllObjects];
5614        [myData addObjectsFromArray: found];
5615        UPDATERECCOUNT;
5616        [theResults reloadData];
5617    }
5618    [found release];
5619    [self setStateString: @"-unmarked"];
5620
5621}
5622-(IBAction) removeMarkedFromSelected: (id) Sender;
5623{
5624    NSMutableArray *found = [[NSMutableArray alloc] init];
5625    FORALL(myData)
5626    {
5627        if([self isMarkedRecord: temp] == NO)
5628        {
5629            [found addObject: temp];
5630        }
5631    }ENDFORALL;
5632    if([found count])
5633    {
5634        [self pushSetStack];
5635        [myData removeAllObjects];
5636        [myData addObjectsFromArray: found];
5637        UPDATERECCOUNT;
5638        [theResults reloadData];
5639    }
5640    [found release];
5641    [self addStateString: @"-marked"];
5642
5643}
5644
5645
5646-(IBAction) selectUnmarked: (id) Sender
5647{
5648    int i, n;
5649    NSMutableArray *fd = [[NSMutableArray alloc] init];
5650
5651    n = [backData count];
5652    for(i = 0; i < n; i++)
5653    {
5654        if([self isMarkedRecord: [backData objectAtIndex: i]] == NO)
5655            [fd addObject: [backData objectAtIndex: i]];
5656    }
5657    if([fd count])
5658    {
5659        [self pushSetStack];
5660        [myData removeAllObjects];
5661        [myData addObjectsFromArray: fd];
5662        UPDATERECCOUNT;
5663        [theResults reloadData];
5664        [self setStateString: @"unmarked"];
5665    }
5666    else
5667    {
5668        NSWARNING(@"No unarked records");
5669    }
5670    [fd release];
5671
5672}
5673/*-----------         Named Selections ---------------*/
5674
5675-(IBAction) loadNamedSelection: (id) Sender
5676{
5677    NSString *selectedSelection;
5678
5679    selectedSelection = [Sender title];
5680    if([[namedSelDict objectForKey: selectedSelection] count])
5681    {
5682        [self pushSetStack];
5683        [myData removeAllObjects];
5684        [myData addObjectsFromArray: [namedSelDict objectForKey: selectedSelection]];
5685        UPDATERECCOUNT;
5686        [theResults reloadData];
5687        [self setStateString: selectedSelection];
5688    }
5689
5690}
5691
5692
5693-(void) backupNamedSel
5694{
5695    NSArray *nl;
5696    NSArray *nd;
5697
5698    nl = [namedSelDict allKeys];
5699    FORALL(nl)
5700    {
5701
5702        nd = [self arrayFromSubset: [namedSelDict objectForKey: temp]];
5703        [namedSelDict setObject: nd forKey: temp];
5704
5705    }
5706    ENDFORALL;
5707}
5708-(void) restoreNamedSel
5709{
5710    NSArray *nl;
5711    NSArray *nd;
5712
5713    nl = [namedSelDict allKeys];
5714    FORALL(nl)
5715    {
5716
5717        nd = [self subsetFromArray: [namedSelDict objectForKey: temp]];
5718        [namedSelDict setObject: nd forKey: temp];
5719
5720    }
5721    ENDFORALL;
5722}
5723
5724
5725-(IBAction) clearNamedSelMenu: (id) Sender
5726{
5727
5728    //delete the menu options
5729    if([namedSelDict count] == 0) return;
5730    if(Sender == nil)
5731    {
5732        if(NSYESNOQUESTION(@"The operation you have picked will probably create unreliable named sets. Delete all named sets? (I recommend clicking \"YES\")") == NO)
5733        {
5734            [self backupNamedSel];
5735            savedNamedSel = YES;
5736            return;
5737        }
5738    }
5739    else
5740        if(NSYESNOQUESTION(@"Delete all of this file's named sets?") ==NO) return;
5741    savedNamedSel = NO;
5742    [namedSelDict removeAllObjects];
5743    [self rebuildAutoSetMenu];
5744    UPDATERECCOUNT;
5745}
5746
5747
5748
5749-(void) renewNamedSelMenu
5750{
5751    int i,nm;
5752    NSMenu *namedSelMenu;
5753    NSMutableArray *theKeys;
5754    //delete the menu options
5755    // myMen = [[NSApp mainMenu] itemWithTag: NAMEDSELMENU] ;
5756    namedSelMenu = [[[NSApp delegate] namedSelectionMenu] submenu];
5757    nm = [namedSelMenu numberOfItems];
5758    for(i = nm-1; i >= NAMEDSELBASE; i--)
5759    {
5760	[namedSelMenu removeItemAtIndex: i];
5761    }
5762    theKeys = [NSMutableArray arrayWithArray: [namedSelDict allKeys]];
5763    [theKeys sortUsingFunction: nsStringComp context: nil];
5764    FORALL(theKeys)
5765    {
5766	NSMenuItem *mm;
5767
5768	mm = [[NSMenuItem alloc] init];
5769	[mm setTitle: temp];
5770	[mm setAction: @selector(loadNamedSelection:)];
5771	[namedSelMenu addItem: mm];
5772    }ENDFORALL;
5773
5774}
5775
5776-(void) namedSelDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
5777{
5778    NSMutableArray *mm;
5779
5780    if(returnCode)
5781    {
5782        if([namedSelDict objectForKey: [namedSelField stringValue]] != nil)
5783        {
5784            NSWARNING(@"Name already exists; use unique name");
5785            return;
5786        }
5787        mm = [[NSMutableArray alloc] init];
5788        [mm addObjectsFromArray: myData];
5789        [namedSelDict setObject: mm forKey: [namedSelField stringValue]];
5790        [mm release];
5791        [self rebuildAutoSetMenu];
5792        //[self renewNamedSelMenu];
5793        [self setStateString: [namedSelField stringValue]];
5794        [self updateOnlyRecCount];
5795        MAKEDIRTY;
5796    }
5797
5798}
5799
5800-(IBAction) cancelNamedSelection: (id) Sender
5801{
5802    [namedSelSheet orderOut: Sender];
5803    [NSApp endSheet: namedSelSheet returnCode: 0];
5804
5805}
5806
5807-(IBAction) okNamedSelection: (id) Sender
5808{
5809    if([self validSetName: [namedSelField stringValue]] == NO)
5810    {
5811        NSWARNING(@"You must use a unique set name");
5812        return;
5813    }
5814    [namedSelSheet orderOut: Sender];
5815    [NSApp endSheet: namedSelSheet returnCode: 1];
5816
5817}
5818-(IBAction) addNamedSelection: (id) Sender
5819{
5820    NSWindow *who;
5821    [namedSelField setStringValue: @""];
5822    if([gPrefBoss detachedSheetValue])
5823        who = nil;
5824    else
5825        who = myWindow;
5826    [NSApp beginSheet: namedSelSheet
5827       modalForWindow: who
5828	modalDelegate: self
5829       didEndSelector: @selector(namedSelDidEnd:returnCode:contextInfo:)
5830          contextInfo: nil];
5831
5832}
5833
5834- (void) windowDidBecomeKey:(NSNotification *)aNotification
5835{
5836    //[self renewNamedSelMenu];
5837    [self rebuildAutoSetMenu];
5838    [self rebuildSummReportMenu];
5839    [self resetCaseSensitive];
5840    /*
5841     if(exactCodeSetFlag)
5842     {
5843         [[[NSApp delegate] exactRsltCodeSetMenuItem] setState: NSOnState];
5844     }
5845     else
5846     {
5847         [[[NSApp delegate] exactRsltCodeSetMenuItem] setState: NSOffState];
5848     }
5849     */
5850    if(gWorkBench != nil)
5851    {
5852        if([gWorkBench reanalysisMode] == YES)
5853        {
5854            [[[NSApp delegate] reanalysisMenu] setState: NSOnState];
5855        }
5856        else
5857        {
5858            [[[NSApp delegate] reanalysisMenu] setState: NSOffState];
5859        }
5860    }
5861    [self displaySelData];
5862
5863
5864}
5865
5866/* ---------- Set Math with Named Sets ----------- */
5867-(void) setMathDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
5868{
5869    NSArray *mm;
5870    NSString *sn;
5871    int opType, i,n;
5872    NSMutableArray *final = [[NSMutableArray alloc] init];
5873
5874    if(returnCode)
5875    {
5876        //get subset
5877        sn = [[setMathSetMenu selectedItem] title];
5878        mm = [self getSetWithName: sn];
5879        opType = [[setMathOpMenu selectedItem] tag];
5880
5881        //this block is for autohistory
5882        if([self isAutoSet: sn])
5883        {
5884            NSMutableDictionary *ahd = [NSMutableDictionary dictionary];
5885            [ahd setObject: @"set" forKey: @"stepType"];
5886            [ahd setObject: [NSNumber numberWithInt: opType]
5887                    forKey: @"op"];
5888            [ahd setObject: [[sn copy] autorelease]
5889                    forKey: @"obj"];
5890            [autoHistory addObject: ahd];
5891        }
5892
5893
5894        switch (opType)
5895        {
5896            case 1: //intersect with
5897                FORALL(mm)
5898            {
5899                    if([myData indexOfObject: temp] == NSNotFound)
5900                    {
5901                    }
5902                    else
5903                        [final addObject: temp];
5904            }
5905                ENDFORALL;
5906                [myData removeAllObjects];
5907                [myData addObjectsFromArray: final];
5908                break;
5909
5910            case 2: //union
5911                FORALL(mm)
5912            {
5913                    if([myData indexOfObject: temp] == NSNotFound)
5914                    {
5915                        [final addObject: temp];
5916                    }
5917            }
5918                ENDFORALL;
5919                [myData addObjectsFromArray: final];
5920                break;
5921
5922            case 3: //Don't intersect with
5923                n = [mm count];
5924                for(i = 0; i < n; i++)
5925                {
5926                    [myData removeObject: [mm objectAtIndex: i]];
5927                }
5928                    break;
5929
5930            case 4: //not in union with
5931                n = [backData count];
5932                for(i = 0; i < n; i++)
5933                {
5934                    if([myData containsObject: [backData objectAtIndex: i]] == YES ||
5935                       [mm containsObject: [backData objectAtIndex: i]] == YES)
5936                    {
5937                    }
5938                    else
5939                    {
5940                        [final addObject: [backData objectAtIndex: i]];
5941                    }
5942                }
5943                    [myData removeAllObjects];
5944                [myData addObjectsFromArray: final];
5945                break;
5946
5947            case 5: // XOR
5948                n = [mm count];
5949                for(i = 0; i < n ; i++)
5950                {
5951                    if([myData containsObject: [mm objectAtIndex: i]] == YES)
5952                    {
5953                        [myData removeObject: [mm objectAtIndex: i]];
5954                    }
5955                    else
5956                    {
5957                        [myData addObject: [mm objectAtIndex: i]];
5958                    }
5959                }
5960                    break;
5961
5962        };
5963        [final release];
5964        UPDATERECCOUNT;
5965        [theResults reloadData];
5966        [self addStateString: [NSString stringWithFormat: @"%@ w/ %@",
5967            [[setMathOpMenu selectedItem] title],
5968            [[setMathSetMenu selectedItem] title]]];
5969    }
5970
5971}
5972
5973-(IBAction) cancelSetMath: (id) Sender
5974{
5975    [setMathSheet orderOut: Sender];
5976    [NSApp endSheet: setMathSheet returnCode: 0];
5977
5978}
5979
5980-(IBAction) okSetMath: (id) Sender
5981{
5982    [self pushSetStack];
5983    [setMathSheet orderOut: Sender];
5984    [NSApp endSheet: setMathSheet returnCode: 1];
5985
5986}
5987-(IBAction) doSetMath: (id) Sender
5988{
5989    //Need to rebuild the named selections menu
5990    //are there any?
5991    NSMutableArray *namedSels;
5992    NSWindow *who;
5993
5994    if([gPrefBoss detachedSheetValue])
5995        who = nil;
5996    else
5997        who = myWindow;
5998
5999    if([[self allSetNames] count] == 0)
6000    {
6001        NSWARNING(@"No named selections");
6002        return;
6003    }
6004    [setMathOpMenu selectItemAtIndex: 0];
6005    [setMathSetMenu removeAllItems];
6006    namedSels = [NSMutableArray arrayWithArray: [self allSetNames]];
6007    [namedSels sortUsingFunction: nsStringComp context: nil];
6008    FORALL(namedSels)
6009    {
6010        [setMathSetMenu addItemWithTitle: temp];
6011    }
6012    ENDFORALL;
6013
6014    [namedSelField setStringValue: @""];
6015    [NSApp beginSheet: setMathSheet
6016       modalForWindow: who
6017	modalDelegate: self
6018       didEndSelector: @selector(setMathDidEnd:returnCode:contextInfo:)
6019          contextInfo: nil];
6020
6021}
6022
6023/* find the record in the original file */
6024-(IBAction) fetchRow: (id) Sender
6025{
6026    int row, b, e;
6027    NSMutableDictionary *aRec;
6028    MWFile *who;
6029
6030    if(!gWorkBench)
6031    {
6032        NSWARNING(@"Project file has closed, cannot locate source files");
6033        return;
6034    }
6035
6036    //get the key numbers
6037    row = [theResults selectedRow];
6038    //make a range
6039    aRec = [myData objectAtIndex: row];
6040    b = [[aRec objectForKey: @"_begin_loc"] intValue];
6041    e = [[aRec objectForKey: @"_end_loc"] intValue];
6042    who = [aRec objectForKey: @"_doc"];
6043    //call the window
6044    if([gWorkBench mwFileExists: who] == NO)
6045    {
6046        NSWARNING(@"Cannot find the source file.");
6047    }
6048    else
6049    {
6050        [who closeFakeFile];
6051        [gWorkBench openMWFile: who type: SOURCETYPE];
6052        [[who filePointer] selectAndScrollRange: NSMakeRange(b, e-b) andMoveForward: YES];
6053    }
6054
6055}
6056
6057-(IBAction) refreshResults: (id) Sender
6058{
6059    int selRow;
6060    int tsim;
6061    NSMutableString *ols = [[NSMutableString alloc] init];
6062    //get the data
6063    FORALL(fileList)
6064    {
6065	if(FILEOPEN(temp) == NO)
6066	{
6067	    NSWARNING(@"Cannot find one of the original source files.");
6068	    return;
6069	}
6070    }
6071    ENDFORALL;
6072
6073    //if(dataSource)
6074    {
6075        int nnn;
6076
6077        [ols setString: [limitField stringValue]];
6078        [self clearNamedSelMenu: nil];
6079	tce = [[TAMSCharEngine alloc] initWithArrayAndStart: fileList];
6080	selRow = [theResults selectedRow];
6081	[self clearTable]; //do before the data goes away
6082                           //clean my own lists
6083
6084	[self initVariables];
6085        [self zeroSetStack];
6086	//[myData removeAllObjects];
6087        [myData autorelease];
6088        myData = [[NSMutableArray alloc] init];
6089        //	[backData removeAllObjects];
6090        [backData autorelease];
6091        backData = [[NSMutableArray alloc] init];
6092	[univList removeAllObjects];
6093	[repList removeAllObjects];
6094        [lastRepList removeAllObjects];
6095        [innerRepList removeAllObjects];
6096	[blockList removeAllObjects];
6097	[colList removeAllObjects];
6098	[markedList removeAllObjects];
6099	[univVault removeAllObjects];
6100	[repVault removeAllObjects];
6101	[normVault removeAllObjects];
6102	[sortStack removeAllObjects];
6103        [repCont removeAllObjects];
6104        [fieldMap removeAllObjects];
6105        [mediaDict removeAllObjects];
6106        [self clearComments];
6107	[self buildCoderList];
6108	if([gPrefBoss countSectionsValue])
6109	    SETGLOBAL(@"emptysectionflag", 1);
6110	else
6111	    SETGLOBAL(@"emptysectionflag",0);
6112        tsim = [self global: @"simpleflag"];
6113
6114        SETGLOBAL(@"rawflag", [self global: @"raw1stflag"]);
6115        SETGLOBAL(@"simpleflag", [self global: @"simple1stflag"]);
6116        tsim = [self global: @"simpleflag"];
6117
6118        SETGLOBAL(@"exactflag", [self global: @"exact1stflag"]);
6119        SETGLOBAL(@"emptyflag", [self global: @"empty1stflag"]);
6120        SETGLOBAL(@"sectionsearch", [self global: @"section1stflag"]);
6121
6122	[[NSNotificationCenter defaultCenter] addObserver: self
6123                                                 selector: @selector(handleEachEOF:)
6124                                                     name: @"TAMSFileHasEnded"
6125                                                   object: nil];
6126        tsim = [self global: @"simpleflag"];
6127        //get the search
6128        /* all of this is now handlied when the object is init'd*/
6129	//[limitString setString: [dataSource theLimitString]];
6130	//clearSearchList();
6131	//addArrayToSearchList(fileList);
6132	//startSearch();
6133
6134	if([limitString length])
6135	{
6136	    [self setGlobal: @"limitflag" to: 1];
6137	    [tce handlelimit: limitString];
6138            tsim = [self global: @"simpleflag"];
6139	    [self doTamsSearch: limitString];
6140	    [tce ctCloseAllOpenRuns];
6141	    if([[tce ctRunVault] count])
6142		[self handleEnd: NO flush: NO];
6143	}
6144	else
6145	{
6146	    [self setGlobal: @"limitflag" to: 0];
6147            tsim = [self global: @"simpleflag"];
6148	    [self doTamsSearch: nil];
6149	    [tce ctCloseAllOpenRuns];
6150	    if([[tce ctRunVault] count])
6151		[self handleEnd: NO flush: NO];
6152	}
6153	//gCurrentTAMS = nil;
6154
6155        //do the search
6156	//do the tables
6157	//reload
6158	[self setupTables];
6159	[myWindow makeKeyAndOrderFront: self];
6160	[backData removeAllObjects];
6161	[backData addObjectsFromArray: myData];
6162        [self setOriginalStateString];
6163        nnn = [[self autoHistory] count];
6164        if(nnn > 0)
6165        {
6166            [self doAutoSet: nil];
6167            [limitField setStringValue: ols];
6168        }
6169	UPDATERECCOUNT;
6170
6171	[theResults reloadData];
6172        [ols release];
6173	[[NSNotificationCenter defaultCenter] removeObserver:self
6174                                                        name: @"TAMSFileHasEnded" object: nil];
6175
6176	if([myData count] > 0)
6177	{
6178	    [myWindow setDocumentEdited: YES];
6179	    [self updateChangeCount: NSChangeDone];
6180	}
6181	if([theResults numberOfRows] > selRow && [theResults numberOfRows] > 0)
6182	    [theResults selectRow: selRow byExtendingSelection: NO];
6183	[dirtySourceFlag setState: NSOffState];
6184        if(savedNamedSel) [self restoreNamedSel];
6185        [tce release];
6186
6187    }
6188
6189}
6190
6191-(void) clearTable
6192{
6193    NSArray *tc = [theResults tableColumns];
6194    NSTableColumn *t;
6195    NSEnumerator *ten;
6196
6197    ten = [tc objectEnumerator];
6198    while(t = [ten nextObject])
6199	[theResults removeTableColumn: t];
6200}
6201
6202-(void) setupTables
6203{
6204    NSTableColumn *t;
6205    NSEnumerator *men;
6206    NSString *ss;
6207
6208    //delete the existing columns
6209    //create the right number of columns with the right headers
6210    //send a refresh
6211
6212    /*
6213     FORALL(tc)
6214     {
6215         [theResults removeTableColumn: temp];
6216     }
6217     ENDFORALL;
6218     */
6219    //create new ones
6220    if([myData count] == 0) return;
6221    //make the count stuff here
6222    t = [[NSTableColumn alloc] initWithIdentifier: @"#"];
6223    [t setWidth: COLWIDTH/2.0];
6224    [theResults addTableColumn: t];
6225    [[t headerCell] setStringValue: @"#"];
6226    //    md = [myData objectAtIndex: 0];
6227    men = [colList objectEnumerator];
6228    while(ss = [men nextObject])
6229    {
6230	//make column
6231        if([self isBlocked: ss]) continue;
6232        t = [[NSTableColumn alloc] initWithIdentifier: ss];
6233	[t setWidth: COLWIDTH];
6234        [theResults addTableColumn: t];
6235        [[t headerCell] setStringValue: ss];
6236
6237    }
6238    //    [theResults setTarget: self];
6239
6240    //    [theResults setAction: @selector(displaySelData)];
6241    [theResults setAllowsColumnReordering: YES];
6242//    [theResults setAutosizesAllColumnsToFit: YES];
6243    builtTable = YES;
6244	[theResults reloadData];
6245//	[theResults setAutosizesAllColumnsToFit: NO];
6246
6247}
6248
6249
6250- (int)numberOfRowsInTableView:(NSTableView *)aTableView
6251{
6252	if(myData == nil || builtTable == NO){
6253		NSLog(@"pop\'ng table before init\nb");
6254		return 0;
6255		}
6256    return [myData count];
6257}
6258- (id)tableView:(NSTableView *)aTableView
6259    objectValueForTableColumn:(NSTableColumn *)aTableColumn
6260            row:(int)rowIndex
6261{
6262    NSMutableString *numStr;
6263    NSString *ss = [aTableColumn identifier];
6264    NSDictionary *dd;
6265    if([ss isEqualToString: @"#"] == YES)
6266    {
6267	numStr = [[NSMutableString alloc] init];
6268	[numStr setString: [[NSNumber numberWithInt: rowIndex + 1] stringValue]];
6269	if([self isMarked: rowIndex] == YES)
6270	    [numStr appendString: @"+"];
6271	[numStr autorelease];
6272	return numStr;
6273    }
6274    else if([ss isEqualToString: @"_doc"] == YES)
6275    {
6276 	dd =[myData objectAtIndex: rowIndex];
6277	return [(MWFile *)[dd objectForKey: @"_doc"] name];
6278
6279    }
6280    else
6281    {
6282        dd = [myData objectAtIndex: rowIndex];
6283        return [dd objectForKey: ss];
6284    }
6285}
6286
6287-(void) setDataSource: (NSString *) theData{}
6288
6289-(BOOL)tableView: (NSTableView *) aTable shouldEditTableColumn: (NSTableColumn *) aCol row: (unsigned) arow
6290{
6291    return NO;
6292}
6293- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
6294{
6295    [self displaySelData];
6296}
6297- (void)tableView:(NSTableView*)tableView didClickTableColumn:(NSTableColumn *)tableColumn
6298{
6299    [self displaySelData];
6300}
6301
6302-(void) browseFieldDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
6303{
6304
6305    if(returnCode)
6306    {
6307        [browseField setString: [browseFieldMenu titleOfSelectedItem]];
6308        [self displaySelData];
6309    }
6310
6311}
6312
6313-(IBAction) cancelBrowseField: (id) Sender
6314{
6315    [browseFieldSheet orderOut: Sender];
6316    [NSApp endSheet: browseFieldSheet returnCode: 0];
6317
6318}
6319
6320-(IBAction) okBrowseField: (id) Sender
6321{
6322    [browseFieldSheet orderOut: Sender];
6323    [NSApp endSheet: browseFieldSheet returnCode: 1];
6324
6325}
6326-(IBAction) doBrowseField: (id) Sender
6327{
6328    NSWindow *who;
6329
6330    NSMutableArray *cols=[NSMutableArray array];
6331    NSArray *currCols;
6332
6333    currCols = [self tableColumns];
6334    FORALL(currCols)
6335    {
6336        [cols addObject: [temp identifier]];
6337    }
6338    ENDFORALL;
6339    [browseFieldMenu removeAllItems];
6340    [browseFieldMenu addItemsWithTitles: cols];
6341    [browseFieldMenu selectItemWithTitle: browseField];
6342    if([gPrefBoss detachedSheetValue])
6343        who = nil;
6344    else
6345        who = myWindow;
6346
6347    [NSApp beginSheet: browseFieldSheet
6348       modalForWindow: who
6349	modalDelegate: self
6350       didEndSelector: @selector(browseFieldDidEnd:returnCode:contextInfo:)
6351          contextInfo: nil];
6352
6353}
6354
6355-(void) displaySelData
6356{
6357    [self displaySelData: [theResults selectedRow]];
6358}
6359
6360-(void) displaySelData: (int) row
6361{
6362    NSString *ss;
6363    NSMutableString *s2, *s3;
6364    //get the selected row
6365    //get the appropriate data
6366    if([myData count] == 0)
6367    {
6368        [thisCell setString: @""];
6369
6370        return;
6371    }
6372
6373    if([myData count] - 1 < row) row = [myData count] - 1;
6374    if(row >= 0)
6375    {
6376        if([browseField isEqualToString: @"_doc"])
6377            ss = [[[myData objectAtIndex: row] objectForKey: browseField] name];
6378        else
6379            ss = [[myData objectAtIndex: row] objectForKey: browseField];
6380
6381        //set it to the textview
6382        s2 = [[NSMutableString alloc] init];
6383        s3 = [[NSMutableString alloc] init];
6384        [s2 setString: ss];
6385        [s2 replaceOccurrencesOfString: @"\\n" withString: @"\n"
6386                               options: NSLiteralSearch range: NSMakeRange(0, [s2 length])];
6387        [s2 replaceOccurrencesOfString: @"\\t" withString: @"\t"
6388                               options: NSLiteralSearch range: NSMakeRange(0, [s2 length])];
6389        [s2 replaceOccurrencesOfString: @"\\r" withString: @"\r"
6390                               options: NSLiteralSearch range: NSMakeRange(0, [s2 length])];
6391        if(stripTags)
6392        {
6393            MWFakeFile *mf;
6394            TAMSCharEngine *tx;
6395            ctQChar *qq;
6396            qq = [[ctQChar alloc] init];
6397
6398
6399            mf = [[MWFakeFile alloc] initWithString: s2];
6400            tx = [[TAMSCharEngine alloc] initWithFile: mf];
6401            [tx setAllowTab: 1];
6402            [tx setNoPar: 0];
6403            [tx startSearch];
6404            while([tx scanNext: qq withWarnings: NO] != ENDOFFILE)
6405                //while([tx readnext: qq] != EOF)
6406            {
6407                if([qq tokentype] == CHAR)
6408                {
6409                    [s3 appendString: [qq buff]];
6410                }
6411            }
6412            [tx release];
6413            [qq release];
6414            [mf release];
6415
6416        }
6417        else
6418            [s3 setString: s2];
6419        [s3 replaceOccurrencesOfString: @"\\n" withString: @"\n"
6420                               options: NSLiteralSearch range: NSMakeRange(0, [s3 length])];
6421        [s3 replaceOccurrencesOfString: @"\\t" withString: @"\t"
6422                               options: NSLiteralSearch range: NSMakeRange(0, [s3 length])];
6423        [s3 replaceOccurrencesOfString: @"\\r" withString: @"\r"
6424                               options: NSLiteralSearch range: NSMakeRange(0, [s3 length])];
6425
6426        if([gPrefBoss TAScanForLN] && [[[myData objectAtIndex: row] objectForKey: @"_line_number"] intValue]
6427           && [browseField isEqualToString: @"_data"])
6428        {
6429            [thisCell setString: [NSString stringWithFormat: @"%d\t%@",
6430                [[[myData objectAtIndex: row] objectForKey: @"_line_number"] intValue],
6431                s3]];
6432        }
6433        else
6434        {
6435            [thisCell setString: s3];
6436        }
6437        [s2 release];
6438        [s3 release];
6439        /*put colorize stuff here */
6440        //if([self global: @"nonregexcharflag"] || [self global: @"regexcharflag"]) return;
6441        if([gPrefBoss autoColorValue])
6442            [self doColorize: nil];
6443
6444    }
6445}
6446
6447-(IBAction) copyWithoutTags: (id) sender
6448{
6449    ctQChar *q;
6450    NSString *oText;
6451    NSMutableString *nText;
6452    NSRange r;
6453    MWFakeFile *ff;
6454    int ch;
6455    BOOL a;
6456
6457    r = [thisCell selectedRange];
6458    if(r.length == 0) return;
6459    oText = [[thisCell string] substringWithRange: r];
6460    ff = [[MWFakeFile alloc] initWithString: oText];
6461    nText = [[NSMutableString alloc] init];
6462    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
6463    [tc setAllowTab: 1];
6464    [tc setNoPar: 0];
6465    //start search
6466    [tc addFileToSearchList: ff];
6467
6468    [tc startSearch];
6469    q = [[ctQChar alloc] init];
6470    while((ch = [tc scanNext: q withWarnings: NO]) != ENDOFALLFILES)
6471    {
6472        if (ch == CHAR) [nText appendString: [q buff]];
6473    }
6474    [q release];
6475    [tc release];
6476    [ff release];
6477    [[NSPasteboard generalPasteboard]
6478	declareTypes:[NSArray arrayWithObject:NSStringPboardType]
6479               owner:self];
6480
6481    a = [[NSPasteboard generalPasteboard] setString: nText forType: NSStringPboardType];
6482    [nText autorelease];
6483}
6484
6485-(IBAction) doColorize: (id) sender
6486{
6487    NSTextStorage *ts = [thisCell textStorage];
6488    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
6489    ctQChar *q;
6490    MWFile *mf;
6491
6492    if(!gWorkBench) return;
6493    mf = [[MWFakeFile alloc] initWithString: [thisCell string]];
6494    [tc addFileToSearchList: mf];
6495    [tc startSearch];
6496
6497    q = [[ctQChar alloc] init];
6498
6499    [thisCell setTextColor: [NSColor blackColor]];
6500    [ts beginEditing];
6501    while([tc scanNext: q withWarnings: NO] != ENDOFFILE)
6502    {
6503        if([q tokentype] == TOKEN || [q tokentype] == ENDTOKEN)
6504        {
6505            /*
6506             [ts addAttribute:
6507                 NSForegroundColorAttributeName
6508                        value:  [gWorkBench colorForCode: [q buff]]
6509                        range: [q range]];
6510             */
6511            [thisCell setTextColor: [gWorkBench colorForCode: [q buff]] range: [q range]];
6512        }
6513
6514        //else if([q tokentype] == ENDOFFILE)
6515        else if([q tokentype] == META)
6516        {
6517            /*
6518             [ts addAttribute:
6519                 NSForegroundColorAttributeName
6520                        value:  getColorForInt([gPrefBoss tagColorValue])
6521                        range: [q range]];
6522             */
6523            [thisCell setTextColor: [gPrefBoss metaColor] range: [q range]];
6524        }
6525    }
6526    [ts endEditing];
6527
6528    [tc release];
6529    [mf release];
6530    [q release];
6531}
6532
6533- (BOOL)validateMenuItem:(NSMenuItem *)anItem
6534{
6535    BOOL ans = [super validateMenuItem: anItem];
6536
6537    if([[anItem title] isEqualToString: @"Save"] == YES)
6538    {
6539	return YES;
6540    }
6541    if([[anItem title] isEqualToString: @"Save As..."] == YES)
6542    {
6543	return YES;
6544    }
6545
6546    return ans;
6547
6548}
6549- (void) moveForward
6550{
6551    [myWindow makeKeyAndOrderFront: self];
6552}
6553
6554-(IBAction) moveWorkBenchForward: (id) sender
6555{
6556    [gWorkBench front];
6557
6558}
6559-(IBAction) showCodeBrowser: (id) Sender
6560{
6561    [gWorkBench showCodeBrowser: self];
6562}
6563-(NSString *)getTitle
6564{
6565    return [myWindow title];
6566}
6567-(void) setMWFile: (MWFile *) who{ myMWFID = who;}
6568-(MWFile *) getMWFile {return myMWFID;}
6569-(id) getGWorkBench: (id) who {return gWorkBench;}
6570-(void) setGWorkBench: (id) who {gWorkBench = who;}
6571- (void)document:(NSDocument *)doc didSave:(BOOL)didSave contextInfo:(void *)contextInfo
6572{
6573    MWFile *mw;
6574    mw = [self getMWFile];
6575    if(didSave == YES)
6576    {
6577	[myWindow setDocumentEdited: NO];
6578	[self updateChangeCount: NSChangeCleared];
6579        [mw setOpenFile: self]; //reset the path
6580        [mw setHasFile: YES];
6581        if(gWorkBench != nil) [gWorkBench setDirty];
6582    }
6583
6584}
6585-(IBAction) saveDocument: (id) Sender
6586{
6587
6588
6589    MWFile *mw;
6590    NSString *path;
6591    NSLog(@"in saveDocument--%@\n", [self fileName]);
6592    //[self saveToFile:nil saveOperation: NSSaveAsOperation delegate: self didSaveSelector:@selector(document:didSave:contextInfo:) contextInfo:nil ];
6593    if([self fileName]) [super saveDocument: nil];
6594	else
6595
6596    [self saveDocumentWithDelegate: self didSaveSelector: @selector(document:didSave:contextInfo:) contextInfo: nil];
6597    return;
6598    /*
6599     [super saveDocument: self];
6600     path = [self fileName];
6601     [gWorkBench setDirty];//kludge since we're too lazy to make our own save Doc
6602     if([self fileName])
6603     if([[mw path] isEqualToString: [self fileName]] ==NO)
6604     {
6605         [mw setOpenFile: self]; //reset the path
6606         [mw setHasFile: YES];
6607         [gWorkBench setDirty];
6608     }
6609     */
6610}
6611-(IBAction) saveDocumentAs: (id) Sender
6612{
6613
6614    MWFile *mw;
6615    [self runModalSavePanelForSaveOperation: NSSaveAsOperation delegate: self didSaveSelector: @selector(document:didSave:contextInfo:) contextInfo: nil];
6616    //[self saveDocumentWithDelegate: self didSaveSelector: @selector(document:didSave:contextInfo:) contextInfo: nil];
6617    return;
6618    /*
6619     [super saveDocumentAs: self];
6620     mw = [self getMWFile];
6621     [gWorkBench setDirty];//kludge since we're too lazy to make our own save Doc
6622     if([self fileName])
6623     if([[mw path] isEqualToString: [self fileName]] ==NO)
6624     {
6625         [mw setOpenFile: self]; //reset the path
6626         [mw setHasFile: YES];
6627         [gWorkBench setDirty];
6628     }
6629     */
6630}
6631
6632-(void) setStateString: (NSString *) what
6633{
6634    [limitField setStringValue: what];
6635}
6636
6637-(void) addStateString: (NSString *) what
6638{
6639    NSString *old;
6640    old = [limitField stringValue];
6641    [limitField setStringValue: [NSString stringWithFormat: @"%@; %@", old, what]];
6642}
6643-(void) setOriginalStateString
6644{
6645    if([self global: @"regexcharflag"] || [self global: @"nonregexcharflag"])
6646    {
6647        [limitField setStringValue: [NSString stringWithFormat: @"Find: %@",limitString]];
6648        return;
6649
6650    }
6651
6652    if([self global: @"sectionsearch"])
6653    {
6654        if([limitString length])
6655        {
6656            [limitField setStringValue: [NSString stringWithFormat: @"Section: %@",limitString]];
6657        }
6658        else
6659            [limitField setStringValue: @"Section: unlimited"];
6660
6661        return;
6662
6663    }
6664    else if(limitString)
6665    {
6666        if([limitString length])
6667        {
6668            [limitField setStringValue: limitString];
6669            return;
6670        }
6671    }
6672
6673    [limitField setStringValue: @"Unlimited"];
6674}
6675
6676-(IBAction) doSetStripTags: (id) sender
6677{
6678    NSMenuItem *tagMenu;
6679    tagMenu = [[NSApp delegate] toggleShowTagsMenuItem];
6680    if([self global: @"rawflag"] == NO) return;
6681    if(stripTags)
6682    {
6683        stripTags = NO;
6684        [tagMenu setState: NSOffState];
6685    }
6686    else
6687    {
6688        stripTags = YES;
6689        [tagMenu setState: NSOnState];
6690    }
6691    [self displaySelData];
6692}
6693
6694-(IBAction) doCollapseDown:(id) Sender
6695{
6696    //loop through
6697    NSString * compareValue;
6698    NSString *recKey;
6699    id compareRec;
6700    NSALLOC(NSMutableArray, tempStorage);
6701    int fflag;
6702    if([theResults selectedColumn] < 0)
6703    {
6704        NSWARNING(@"Need to select a column");
6705        [tempStorage release];
6706        return;
6707    }
6708
6709    recKey = SELECTEDCOLUMNID(theResults);
6710    if(recKey == nil) return;
6711    fflag = 1;
6712    FORALL(myData)
6713    {
6714        if(fflag == 1)
6715        {
6716            compareValue = [temp objectForKey: recKey];
6717            compareRec = temp;
6718            fflag = 2;
6719        }
6720        else if(fflag == 2)
6721        {
6722            if([[temp objectForKey: recKey] isEqualToString: compareValue] == YES)
6723            {
6724                compareRec = temp;
6725            }
6726            else
6727            {
6728                [tempStorage addObject: compareRec];
6729                compareRec = temp;
6730                compareValue = [temp objectForKey: recKey];
6731            }
6732        }
6733    }ENDFORALL;
6734    [self pushSetStack];
6735
6736    [tempStorage addObject: compareRec];
6737    [myData removeAllObjects];
6738    [myData addObjectsFromArray: tempStorage];
6739    [tempStorage release];
6740    {
6741        NSString *sss = [NSString stringWithFormat: @"cllpse dwn: %@", recKey];
6742
6743        [self addStateString: sss];
6744    }
6745
6746    UPDATERECCOUNT;
6747    [theResults reloadData];
6748
6749
6750    //get the compare value if 1st time or compare with value if it's the second+
6751    // is it different, save the new value
6752
6753
6754}
6755-(IBAction) doCollapseUp:(id) Sender
6756{
6757    //loop through
6758    NSString * compareValue;
6759    NSString *recKey;
6760    id compareRec;
6761    NSALLOC(NSMutableArray, tempStorage);
6762    int fflag;
6763
6764    if([theResults selectedColumn] < 0)
6765    {
6766        NSWARNING(@"Need to select a column");
6767        [tempStorage release];
6768        return;
6769    }
6770
6771
6772    recKey = SELECTEDCOLUMNID(theResults);
6773    fflag = 1;
6774    FORALL(myData)
6775    {
6776        if(fflag == 1)
6777        {
6778            compareValue = [temp objectForKey: recKey];
6779            compareRec = temp;
6780            fflag = 2;
6781        }
6782        else if(fflag == 2)
6783        {
6784            if([[temp objectForKey: recKey] isEqualToString: compareValue] == YES)
6785            {
6786                ; //do nothing since we want the topmost one to represent everyone
6787            }
6788            else
6789            {
6790                [tempStorage addObject: compareRec];
6791                compareRec = temp;
6792                compareValue = [temp objectForKey: recKey];
6793            }
6794        }
6795    }ENDFORALL;
6796    [self pushSetStack];
6797
6798    [tempStorage addObject: compareRec];
6799    [myData removeAllObjects];
6800    [myData addObjectsFromArray: tempStorage];
6801    [tempStorage release];
6802    {
6803        NSString *sss = [NSString stringWithFormat: @"cllpse up: %@", recKey];
6804
6805        [self addStateString: sss];
6806    }
6807    UPDATERECCOUNT;
6808    [theResults reloadData];
6809
6810
6811    //get the compare value if 1st time or compare with value if it's the second+
6812    // is it different, save the new value
6813
6814
6815}
6816
6817/* auto sets routines */
6818
6819-(IBAction) createAutoSet: (id) sender
6820{
6821    [autoSetWatcher runMacroEditor];
6822}
6823-(NSMutableDictionary *) autoSets
6824{
6825    return autoSets;
6826}
6827-(NSWindow *) myWindow
6828{
6829    return myWindow;
6830}
6831-(BOOL) isInfiniteLoop: (NSDictionary*)who  usingStack: (NSMutableArray *)mystack
6832{
6833    NSArray *pgm;
6834    int i, n;
6835    pgm = [who objectForKey: @"program"];
6836    n = [pgm count];
6837    for(i = 0; i< n; i++)
6838    {
6839        NSDictionary *w;
6840        w = [pgm objectAtIndex: i];
6841        if([[w objectForKey: @"stepType"] isEqualToString: @"autoset"] == YES)
6842        {
6843            if(addUniqueToArray(mystack, [w objectForKey: @"name"]) == NO) return YES;
6844            if([self isInfiniteLoop: [self autoSetForName:[w objectForKey: @"name"]] usingStack: mystack] == YES)
6845                return YES;
6846        }
6847        if([[w objectForKey: @"stepType"] isEqualToString: @"set"] == YES)
6848        {
6849            NSString *setName;
6850            setName = [w objectForKey: @"obj"];
6851            if(setName == nil) continue;
6852            if(addUniqueToArray(mystack, setName) == NO) return YES;
6853            if([self isInfiniteLoop: [self autoSetForName:setName] usingStack: mystack] == YES)
6854                return YES;
6855        }
6856
6857    }
6858    return NO;
6859}
6860
6861
6862-(IBAction) doAutoSet: (id) sender
6863{
6864    NSMutableDictionary *who;
6865    NSMutableArray *ans;
6866    NSString *title;
6867    NSMutableArray *oldHist;
6868    BOOL allFlag;
6869    allFlag = YES;
6870    if(sender != nil)
6871    {
6872        ans = [self getAutoSetWithName: [sender title]];
6873        who = [self autoSetForName: [sender title]];
6874        title = [sender title];
6875    }
6876    else
6877    {
6878        ans = [self getAutoSetWithName: nil];
6879        who = [self autoHistoryAsProgram];
6880        title = [self autoHistoryStart];
6881        oldHist = [[NSMutableArray alloc] initWithArray: autoHistory];
6882        [autoHistory removeAllObjects];
6883    }
6884
6885#ifdef NOSHOWZEROCOUNT
6886    if([ans count])
6887#endif
6888    {
6889        NSMutableArray *aa = [NSMutableArray array];
6890        [aa addObject: title];
6891        if([self isInfiniteLoop: who usingStack: aa])
6892        {
6893            if(NSYESNOQUESTION(@"Autoset has a potential infinite loop, continue?") == NO)
6894                return;
6895        }
6896        [self pushSetStack];
6897        [myData setArray: ans];
6898        [theResults reloadData];
6899        if([[who objectForKey: @"start"] isEqualToString: @"Visible"])
6900        {
6901            allFlag = NO;
6902            [self addStateString: [NSString stringWithFormat: @"->%@",title]];
6903        }
6904        else
6905        {
6906            [self setStateString: title];
6907        }
6908        [autoHistoryStart setString: title];
6909        if(sender != nil && allFlag == YES)
6910            [autoHistory removeAllObjects];
6911        else if(sender == nil)
6912        {
6913            [autoHistory setArray: oldHist];
6914            [oldHist release];
6915        }
6916
6917        UPDATERECCOUNT;
6918    }
6919    if([ans count] == 0) NSWARNING(@"No records found");
6920#ifdef NOSHOWZEROCOUNT
6921    else
6922    {
6923        NSWARNING(@"No records found");
6924    }
6925#endif
6926}
6927
6928-(IBAction) removeAllAutoSets: (id) sender
6929{
6930    if(NSYESNOQUESTION(@"Delete all of this file's autosets?") ==NO) return;
6931    [[self autoSets] removeAllObjects];
6932    [self rebuildAutoSetMenu];
6933    UPDATERECCOUNT;
6934}
6935
6936-(IBAction) doRunSet: (id) sender
6937{
6938    [self pushSetStack];
6939    if([namedSelDict objectForKey: [sender title]] == nil)
6940    {
6941        //put the autohistory block here
6942        //this block is for autohistory
6943        [self doAutoSet: sender];
6944        if([self isAutoSet: [sender title]])
6945        {
6946            NSMutableDictionary *ahd = [NSMutableDictionary dictionary];
6947            [ahd setObject: @"autoset" forKey: @"stepType"];
6948            [ahd setObject: [[[sender title] copy] autorelease] forKey: @"name"];
6949            [autoHistory addObject: ahd];
6950        }
6951
6952    }
6953    else
6954        [self loadNamedSelection: sender];
6955}
6956
6957-(void) rebuildAutoSetMenu
6958{
6959    int i, n, m;
6960    NSMenu *asmn;
6961    NSMutableArray *w1, *w2;
6962
6963    asmn = [[[NSApp delegate] autoSetMenu] submenu];
6964    m = [asmn numberOfItems];
6965
6966    if(m > AUTOSETBASE)
6967        for(i = AUTOSETBASE; i < m; i++)
6968        {
6969            [asmn removeItemAtIndex: AUTOSETBASE];
6970        }
6971            /*
6972             if(gWorkBench != nil)
6973             {
6974                 who = [gWorkBench allAutoSetNames];
6975                 if(m = [who count])
6976                     for(i = 0; i<m; i++)
6977                     {
6978                         NSMenuItem *mm;
6979
6980                         mm = [[NSMenuItem alloc] init];
6981                         [mm setTitle: [who objectAtIndex: i]];
6982                         [mm setAction: @selector(doAutoSet:)];
6983                         [asmn addItem: mm];
6984
6985                     }
6986             }
6987
6988             who = [[self autoSets] allKeys];
6989             */
6990            w1 = [NSMutableArray arrayWithArray: [namedSelDict allKeys]];
6991    w2 = [NSMutableArray arrayWithArray: [self allAutoSetNames]];
6992
6993    [w1 sortUsingFunction: nsStringComp  context: nil];
6994    [w2 sortUsingFunction: nsStringComp  context: nil];
6995
6996    //who = [self allSetNames];
6997    if((m = [w1 count]) > 0)
6998    {
6999        for(i=0; i< m; i++)
7000        {
7001            [asmn addItemWithTitle: [w1 objectAtIndex: i]
7002                            action: @selector(doRunSet:)
7003                     keyEquivalent: @""];
7004        }
7005    }
7006    n = [w2 count];
7007    if(m > 0 && n > 0)
7008        [asmn addItem: [NSMenuItem separatorItem]];
7009
7010    if(n > 0)
7011    {
7012        for(i=0; i< n; i++)
7013        {
7014            [asmn addItemWithTitle: [w2 objectAtIndex: i]
7015                            action: @selector(doRunSet:)
7016                     keyEquivalent: @""];
7017        }
7018    }
7019
7020}
7021
7022
7023
7024-(NSArray *) allSetNames
7025{
7026    NSMutableArray *aa;
7027
7028    aa = [NSMutableArray array];
7029    [aa addObjectsFromArray: [self allAutoSetNames]];
7030    [aa addObjectsFromArray: [namedSelDict allKeys]];
7031    return aa;
7032
7033}
7034
7035-(NSArray *) allAutoSetNames
7036{
7037    NSMutableArray *aa;
7038
7039    aa = [NSMutableArray array];
7040    if(gWorkBench != nil)
7041    {
7042        [aa addObjectsFromArray: [gWorkBench allAutoSetNames]];
7043    }
7044    [aa addObjectsFromArray: [autoSets allKeys]];
7045    return aa;
7046}
7047
7048-(BOOL) validSetName: (NSString *) who
7049{
7050    if(who == nil) return NO;
7051    if([who isEqualToString: @""] == YES) return NO;
7052    if([self validAutoSetName: who] && [namedSelDict objectForKey: who] == nil)
7053        return YES;
7054    else
7055        return NO;
7056}
7057-(NSMutableArray *) autoHistory{return autoHistory;}
7058
7059-(NSMutableString *) autoHistoryStart {return autoHistoryStart;}
7060
7061-(BOOL) isAutoSet: (NSString *) who
7062{
7063    if([self autoSetForName: who] != nil) return YES;
7064    if(gWorkBench != nil)
7065        if([gWorkBench autoSetForName: who] != nil) return YES;
7066    return NO;
7067}
7068-(BOOL) validAutoSetName: (NSString *) who
7069{
7070    if(who == nil) return NO;
7071    if([who isEqualToString: @""] == YES) return NO;
7072
7073    if([self autoSetForName: who] == nil && [gWorkBench autoSetForName: who] == nil &&
7074       [who isEqualToString: @"All"] == NO && [who isEqualToString: @"Visible"] == NO)
7075        return YES;
7076    else
7077        return NO;
7078}
7079-(void) addAutoSet: (NSMutableDictionary *) what withName: (NSString *) who
7080{
7081    if([[what objectForKey: @"global"] intValue] == 0)
7082    {
7083        [autoSets setObject: what forKey: who];
7084        UPDATERECCOUNT;
7085    }
7086    else if (gWorkBench != nil)
7087    {[gWorkBench addAutoSet: what withName: who];}
7088    else NSWARNING(@"Cannot save macro: not connected to a project");
7089}
7090-(NSMutableDictionary *) myAutoSetForName: (NSString *) who
7091{
7092    return [autoSets objectForKey: who];
7093}
7094
7095-(NSMutableDictionary *) autoSetForName: (NSString *) who
7096{
7097    NSMutableDictionary *ans;
7098    if(gWorkBench != nil)
7099        ans = [gWorkBench autoSetForName: who];
7100    else
7101        ans = nil;
7102    if(ans == nil)
7103        return [autoSets objectForKey: who];
7104    else
7105        return ans;
7106}
7107-(void) removeAutoSetForName: (NSString *) who
7108{
7109    if([self myAutoSetForName: who] != nil)
7110    {
7111        [autoSets removeObjectForKey: who];
7112        UPDATERECCOUNT;
7113    }
7114    else
7115        if(gWorkBench != nil) [gWorkBench removeAutoSetForName: who];
7116}
7117
7118-(NSArray *) columns
7119{
7120    return colList;
7121}
7122
7123-(IBAction) doToggleReanalysisMode: (id) sender
7124{
7125    if(gWorkBench)
7126    {
7127        [gWorkBench doToggleReanalysisMode: sender];
7128    }
7129}
7130/*-----------------------------------------------*/
7131/* summary data routines */
7132-(NSMutableArray *) hotData
7133{return myData;}
7134
7135-(IBAction) runSummaryReport: (id) sender
7136{
7137    [summWatcher doSummary];
7138}
7139
7140-(void) codeLevelDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
7141{
7142
7143    if(returnCode)
7144    {
7145        aCodeLevel = [codeLevelField intValue];
7146    }
7147
7148}
7149
7150-(IBAction) cancelCodeLevel: (id) Sender
7151{
7152    [codeLevelPane orderOut: Sender];
7153    [NSApp endSheet: codeLevelPane returnCode: 0];
7154
7155}
7156
7157-(IBAction) okCodeLevel: (id) Sender
7158{
7159    [codeLevelPane orderOut: Sender];
7160    [NSApp endSheet: codeLevelPane returnCode: 1];
7161
7162}
7163-(IBAction) doCodeLevel: (id) Sender
7164{
7165    NSWindow *who;
7166    [codeLevelField setIntValue: aCodeLevel];
7167    if([gPrefBoss detachedSheetValue])
7168        who = nil;
7169    else
7170        who = myWindow;
7171    [NSApp beginSheet: codeLevelPane
7172       modalForWindow: who
7173	modalDelegate: self
7174       didEndSelector: @selector(codeLevelDidEnd:returnCode:contextInfo:)
7175          contextInfo: nil];
7176
7177}
7178-(BOOL) isMySummReport: (NSString *) who
7179{
7180    NSArray *a;
7181    a = [self mySummReports];
7182    FORALL(a)
7183    {
7184        if([temp isEqualToString: who]) return YES;
7185    }
7186    ENDFORALL;
7187    return NO;
7188}
7189
7190-(int) reportScope: (NSString *) who
7191{
7192    if([self isMySummReport: who]) return 1;
7193    if([self isSummReport: who]) return 2;
7194    return 0;
7195}
7196
7197-(NSMutableString *) dateFormat{return dfString;}
7198-(BOOL) isSummReport: (NSString *) who
7199{
7200    NSArray *a;
7201    a = [self allSummReports];
7202    FORALL(a)
7203    {
7204        if([temp isEqualToString: who]) return YES;
7205    }
7206    ENDFORALL;
7207    return NO;
7208}
7209-(void) addSummReport:(NSString *) who report: (NSDictionary *) r global: (BOOL) g
7210{
7211    if(g ==NO)
7212    {
7213        [summReports setObject:r forKey: who];
7214        [self rebuildSummReportMenu];
7215        MAKEDIRTY;
7216    }
7217    else
7218    {
7219        [gWorkBench addSummReport: who report: r global: g];
7220        [self rebuildSummReportMenu];
7221    }
7222}
7223-(void) delSummReport:(NSString *) who
7224{
7225    if([self isMySummReport: who])
7226    {
7227        [summReports removeObjectForKey: who];
7228        [self rebuildSummReportMenu];
7229        MAKEDIRTY;
7230    }
7231    else
7232    {
7233        [gWorkBench delSummReport: who];
7234    }
7235}
7236
7237-(NSArray *) mySummReports
7238{
7239    return [summReports allKeys];
7240}
7241-(NSArray *) allSummReports
7242{
7243    NSMutableArray *ar = [NSMutableArray array];
7244
7245    [ar addObjectsFromArray: [self mySummReports]];
7246    [ar addObjectsFromArray: [gWorkBench mySummReports]];
7247    return ar;
7248}
7249
7250-(NSDictionary *) summReport: (NSString *) who
7251{
7252    NSDictionary *ans;
7253    ans = [summReports objectForKey: who];
7254    if(ans == nil) return [gWorkBench summReport: who];
7255    else return ans;
7256}
7257-(void) doRunSummRep: (id) sender
7258{
7259    NSDictionary *r;
7260    r = [self summReport: [sender title]];
7261    if(r != nil)
7262        [summWatcher runSummReport: r];
7263}
7264-(void) rebuildSummReportMenu
7265{
7266    int i, n, m;
7267    NSMenu *asmn;
7268    NSMutableArray *w1, *w2;
7269
7270    asmn = [[[NSApp delegate] summReportMenu] submenu];
7271    m = [asmn numberOfItems];
7272
7273    if(m > SUMMREPORTBASE)
7274        for(i = SUMMREPORTBASE; i < m; i++)
7275        {
7276            [asmn removeItemAtIndex: SUMMREPORTBASE];
7277        }
7278
7279            w1 = [NSMutableArray arrayWithArray: [self mySummReports]];
7280    w2 = [NSMutableArray arrayWithArray: [gWorkBench mySummReports]];
7281
7282    [w1 sortUsingFunction: nsStringComp  context: nil];
7283    [w2 sortUsingFunction: nsStringComp  context: nil];
7284
7285    //who = [self allSetNames];
7286    [asmn addItem: [NSMenuItem separatorItem]];
7287    if((m = [w1 count]) > 0)
7288    {
7289        for(i=0; i< m; i++)
7290        {
7291            [asmn addItemWithTitle: [w1 objectAtIndex: i]
7292                            action: @selector(doRunSummRep:)
7293                     keyEquivalent: @""];
7294        }
7295    }
7296    n = [w2 count];
7297    if(m > 0 && n > 0)
7298        [asmn addItem: [NSMenuItem separatorItem]];
7299
7300    if(n > 0)
7301    {
7302        for(i=0; i< n; i++)
7303        {
7304            [asmn addItemWithTitle: [w2 objectAtIndex: i]
7305                            action: @selector(doRunSummRep:)
7306                     keyEquivalent: @""];
7307        }
7308    }
7309
7310}
7311/******** dotGraph rountines ********/
7312-(NSArray *) tableColumns
7313{
7314    return [theResults tableColumns];
7315}
7316
7317-(int) fieldType: (NSString *) name
7318{
7319    if([self isUniversal: name] == YES) return 1;
7320    if([self isRepeat: name] == YES) return 2;
7321    else return 0;
7322}
7323
7324-(int) codeLevel
7325{
7326    return aCodeLevel;
7327}
7328-(IBAction) doDotGraph: (id) sender
7329{
7330    [dotGraphWatcher doDotGraph];
7331}
7332/******** stack routines ********/
7333-(NSMutableDictionary *) getStackElem
7334{
7335    NSMutableDictionary *stackElem;
7336    NSString *ss;
7337    NSMutableArray *myHistory = [[NSMutableArray alloc] init];
7338    stackElem = [NSMutableDictionary dictionary];
7339    ss = [limitField stringValue];
7340    [stackElem setObject: [NSArray arrayWithArray: myData] forKey: @"data"];
7341    [stackElem setObject: [[ss copy] autorelease] forKey: @"limit"];
7342    [myHistory addObjectsFromArray: [self autoHistory]];
7343    [myHistory autorelease];
7344    [stackElem setObject: myHistory forKey: @"history"];
7345    return stackElem;
7346}
7347
7348-(void) pushSetStack
7349{
7350    NSMutableDictionary *stackElem;
7351    if([gPrefBoss enableBack] == 0)
7352    {
7353        [self zeroSetStack];
7354        return;
7355    }
7356    stackElem = [self getStackElem];
7357    [setStack addObject: stackElem];
7358    [fwdSetStack removeAllObjects];
7359    [fwdButton setEnabled: NO];
7360    [backButton setEnabled: YES];
7361
7362}
7363-(IBAction) popSetStack: (id) sender
7364{
7365    int nnn;
7366    if([gPrefBoss enableBack] == 0)
7367    {
7368        [self zeroSetStack];
7369        return;
7370    }
7371    nnn = [setStack count];
7372    if(nnn >0)
7373    {
7374        NSDictionary *dd;
7375        NSString *ss;
7376        NSArray *ah;
7377        //first save what we have
7378        [fwdSetStack addObject: [self getStackElem]];
7379        [fwdButton setEnabled: YES];
7380
7381
7382        //Now pop what we have
7383        dd = [setStack objectAtIndex: nnn - 1];
7384        [myData setArray: [dd objectForKey: @"data"]];
7385        ss = [dd objectForKey: @"limit"];
7386        [limitField setStringValue: ss];
7387        ah = [dd objectForKey: @"history"];
7388        if(ah != nil)
7389            [autoHistory setArray: ah];
7390        else
7391            [autoHistory removeAllObjects];
7392        [setStack removeLastObject];
7393        UPDATERECCOUNT;
7394        [theResults reloadData];
7395        if([setStack count] == 0) [backButton setEnabled: NO];
7396    }
7397    else
7398        [self zeroSetStack];
7399}
7400-(IBAction) popFwdSetStack: (id) sender
7401{
7402    if([gPrefBoss enableBack] == 0)
7403    {
7404        [self zeroSetStack];
7405        return;
7406    }
7407    if([fwdSetStack count] >0)
7408    {
7409        NSDictionary *dd;
7410        NSString *ss;
7411        NSArray *ah;
7412        //first save what we have
7413        [setStack addObject: [self getStackElem]];
7414        [backButton setEnabled: YES];
7415
7416
7417        //Now pop what we have
7418        dd = [fwdSetStack lastObject];
7419        [myData setArray: [dd objectForKey: @"data"]];
7420        ss = [dd objectForKey: @"limit"];
7421        [limitField setStringValue: ss];
7422        ah = [dd objectForKey: @"history"];
7423        if(ah != nil)
7424            [autoHistory setArray: ah];
7425        else
7426            [autoHistory removeAllObjects];
7427        [fwdSetStack removeLastObject];
7428        UPDATERECCOUNT;
7429        [theResults reloadData];
7430        if([fwdSetStack count] == 0) [fwdButton setEnabled: NO];
7431    }
7432    else
7433        [self zeroSetStack];
7434}
7435-(IBAction) zeroSetStack: (id) sender
7436{
7437    [self zeroSetStack];
7438}
7439-(void) zeroSetStack
7440{
7441    [fwdButton setEnabled: NO];
7442    [backButton setEnabled: NO];
7443    [setStack removeAllObjects];
7444    [fwdSetStack removeAllObjects];
7445}
7446-(IBAction) exportData: (id) sender
7447{
7448    [exportWatcher doExport];
7449}
7450-(IBAction) toggleExactCodeSet: (id) sender
7451{
7452    if(exactCodeSetFlag)
7453    {
7454        exactCodeSetFlag = NO;
7455        [sender setState: NSOffState];
7456    }
7457    else
7458    {
7459        exactCodeSetFlag = YES;
7460        [sender setState: NSOnState];
7461    }
7462}
7463
7464-(BOOL) selectDataFrom: (NSArray *) fromArray to: (NSMutableArray *) toArray forCodeSet: (NSString *) who type: (int) tp exact: (BOOL) ex
7465{
7466
7467    int i,n;
7468    BOOL test;
7469    NSArray *codes;
7470    NSMutableArray *removeList;
7471
7472    codes = [gWorkBench codesInCodeSet: who];
7473    if(codes == nil) return NO;
7474    switch(tp)
7475    {
7476        case SELECT:
7477            n = [fromArray count];
7478            for(i = 0; i < n; i++)
7479            {
7480                NSString *mycode;
7481                test = NO;
7482                mycode = [[fromArray objectAtIndex: i] objectForKey: @"_code"];
7483                if(ex)
7484                {
7485                    FORALL(codes)
7486                {
7487                        if([mycode isEqualToString: temp])
7488                        {
7489                            test = YES;
7490                            break;
7491                        }
7492                } ENDFORALL;
7493                }
7494                else
7495                {
7496                    FORALL(codes)
7497                {
7498                        if(isParentOf(temp, mycode))
7499                        {
7500                            test = YES;
7501                            break;
7502                        }
7503                } ENDFORALL;
7504                }
7505                if(test)[toArray addObject: [myData objectAtIndex: i]];
7506            }
7507                if([toArray count] <= 0)
7508                {
7509                    return NO;
7510                }
7511                return YES;
7512            break;
7513        case SELECTFEWER:
7514            n = [fromArray count];
7515            removeList = [NSMutableArray array];
7516            for(i = 0; i < n; i++)
7517            {
7518                NSString *mycode;
7519                test = NO;
7520                mycode = [[fromArray objectAtIndex: i] objectForKey: @"_code"];
7521                if(ex)
7522                {
7523                    FORALL(codes)
7524                {
7525                        if([mycode isEqualToString: temp])
7526                        {
7527                            test = YES;
7528                            break;
7529                        }
7530                } ENDFORALL;
7531                }
7532                else
7533                {
7534                    FORALL(codes)
7535                {
7536                        if(isParentOf(temp, mycode))
7537                        {
7538                            test = YES;
7539                            break;
7540                        }
7541                } ENDFORALL;
7542                }
7543                if(test)[removeList addObject: [myData objectAtIndex: i]];
7544            }
7545                if([removeList count] <= 0)
7546                {
7547                    return NO;
7548                }
7549                [toArray setArray: fromArray];
7550            [toArray removeObjectsInArray: removeList];
7551
7552            return YES;
7553            break;
7554        case SELECTADDITIONAL:
7555            n = [backData count];
7556            removeList = [NSMutableArray array];
7557            for(i = 0; i < n; i++)
7558            {
7559                NSString *mycode;
7560                test = NO;
7561                mycode = [[backData objectAtIndex: i] objectForKey: @"_code"];
7562                if(ex)
7563                {
7564                    FORALL(codes)
7565                {
7566                        if([mycode isEqualToString: temp])
7567                        {
7568                            test = YES;
7569                            break;
7570                        }
7571                } ENDFORALL;
7572                }
7573                else
7574                {
7575                    FORALL(codes)
7576                {
7577                        if(isParentOf(temp, mycode))
7578                        {
7579                            test = YES;
7580                            break;
7581                        }
7582                } ENDFORALL;
7583                }
7584                if(test)
7585                {
7586                    if([fromArray indexOfObject: [backData objectAtIndex: i]] == NSNotFound)
7587                        [removeList addObject: [backData objectAtIndex: i]];
7588                }
7589            }
7590                if([removeList count] <= 0)
7591                {
7592                    return NO;
7593                }
7594                [toArray setArray: fromArray];
7595            [toArray addObjectsFromArray: removeList];
7596
7597            return YES;
7598            break;
7599    };
7600}
7601
7602-(BOOL) selectCodeSetWithName:(NSString *) who withWarnings: (BOOL) w pushStack: (BOOL) ps exact: (BOOL) ex
7603{
7604    return [self selectCodeSetWithName: who withWarnings: w pushStack: ps type: SELECT exact: ex];
7605}
7606
7607-(BOOL) selectCodeSetWithName:(NSString *) who withWarnings: (BOOL) w pushStack: (BOOL) ps type: (int) tp exact: (BOOL) ex
7608{
7609    BOOL test;
7610    NSMutableArray *findData;
7611
7612    if([self global: @"simpleflag"] == 0) return NO;
7613
7614
7615    findData = [[NSMutableArray alloc] init];
7616    test = [self selectDataFrom: myData to: findData forCodeSet: who type: tp exact: ex];
7617    if(test == NO)
7618    {
7619	if(w) {NSWARNING(@"No data found.");}
7620	return NO;
7621    }
7622    //this block is for autohistory
7623    if(ps) [self pushSetStack];
7624
7625    [myData removeAllObjects];
7626    [myData addObjectsFromArray: findData];
7627    [findData release];
7628    return YES;
7629
7630}
7631-(IBAction) selectCodeSet: (id) sender
7632{
7633    NSMutableDictionary *ahd = [NSMutableDictionary dictionary];
7634    if([self global: @"simpleflag"] == 0)
7635    {
7636    {NSWARNING(@"Selecting code sets requires a simple style search");}
7637        return;
7638    }
7639    if([self selectCodeSetWithName: [sender title] withWarnings: YES pushStack: YES exact: exactCodeSetFlag])
7640    {
7641        [ahd setObject: @"sel" forKey: @"stepType"];
7642        [ahd setObject: [NSNumber numberWithInt: SELECTCODESET] forKey: @"mode"];
7643        [ahd setObject: [[[sender title] copy] autorelease] forKey: @"name"];
7644        [ahd setObject: [NSNumber numberWithBool: exactCodeSetFlag] forKey: @"exact"];
7645        [autoHistory addObject: ahd];
7646        UPDATERECCOUNT;
7647        [theResults reloadData];
7648        [self addStateString: [NSString stringWithFormat: @"code set: %@", [sender title]]];
7649    }
7650}
7651
7652-(void) sel2CodeSetDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
7653{
7654
7655    if(returnCode)
7656    {
7657        NSMutableArray *myCodeList;
7658        NSString *codeName;
7659        codeName = [sel2CodeSetName stringValue];
7660        if([gWorkBench codeSetExists: codeName])
7661        {
7662            if(NSYESNOQUESTION(@"Code set already exists with that name. Replace it?") == NO)
7663                return;
7664        }
7665        myCodeList = [NSMutableArray array];
7666        FORALL(myData)
7667        {
7668            addUniqueToArray(myCodeList, [[[temp objectForKey: @"_code"] copy] autorelease]);
7669        }
7670        ENDFORALL;
7671        [myCodeList sortUsingFunction: nsStringComp context: nil];
7672        [gWorkBench registerCodeSet: codeName withCodes:  myCodeList force: YES];
7673    }
7674
7675}
7676
7677-(IBAction) cancelSel2CodeSet: (id) Sender
7678{
7679    [sel2CodeSetSheet orderOut: Sender];
7680    [NSApp endSheet: sel2CodeSetSheet returnCode: 0];
7681
7682}
7683
7684-(IBAction) okSel2CodeSet: (id) Sender
7685{
7686    [sel2CodeSetSheet orderOut: Sender];
7687    [NSApp endSheet: sel2CodeSetSheet returnCode: 1];
7688
7689}
7690
7691-(IBAction) turnSelectionIntoCodeSet: (id) sender
7692{
7693    NSWindow *who;
7694    if([self global: @"simpleflag"] == 0)
7695    {
7696        NSWARNING(@"Must use a simple search to convert selections into code sets.");
7697        return;
7698    }
7699    if([gPrefBoss detachedSheetValue])
7700        who = nil;
7701    else
7702        who = myWindow;
7703
7704    [sel2CodeSetName setStringValue: @""];
7705    [NSApp beginSheet: sel2CodeSetSheet
7706       modalForWindow: who
7707	modalDelegate: self
7708       didEndSelector: @selector(sel2CodeSetDidEnd:returnCode:contextInfo:)
7709          contextInfo: nil];
7710
7711}
7712
7713-(void) selCSDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
7714{
7715    NSString *csName;
7716    BOOL csExact;
7717    NSString *stString;
7718
7719    if(returnCode>0)
7720    {
7721        csName = [selCSMenu titleOfSelectedItem];
7722        if([selCSExactSwitch state] == NSOnState) exactCodeSetFlag=csExact = YES;
7723        else exactCodeSetFlag=csExact = NO;
7724        NSMutableDictionary *ahd = [NSMutableDictionary dictionary];
7725        if([self global: @"simpleflag"] == 0)
7726        {
7727        {NSWARNING(@"Selecting code sets requires a simple style search");}
7728            return;
7729        }
7730        if([self selectCodeSetWithName: csName withWarnings: YES pushStack: YES type: returnCode exact: csExact])
7731        {
7732            [ahd setObject: @"sel" forKey: @"stepType"];
7733            [ahd setObject: [NSNumber numberWithInt: SELECTCODESET] forKey: @"mode"];
7734            [ahd setObject: [NSNumber numberWithInt: returnCode] forKey: @"type"];
7735            [ahd setObject: [[csName copy] autorelease] forKey: @"name"];
7736            [ahd setObject: [NSNumber numberWithBool: csExact] forKey: @"exact"];
7737
7738            [autoHistory addObject: ahd];
7739            UPDATERECCOUNT;
7740            [theResults reloadData];
7741            switch(returnCode)
7742            {
7743                case SELECT:
7744                    stString = [NSString stringWithFormat: @"code set: %@", csName];
7745                    break;
7746                case SELECTFEWER:
7747                    stString = [NSString stringWithFormat: @"-code set: %@", csName];
7748                    break;
7749                case SELECTADDITIONAL:
7750                    stString = [NSString stringWithFormat: @"+code set: %@", csName];
7751                    break;
7752            };
7753            if(csExact) [self addStateString: [NSString stringWithFormat: @"%@ (x)", stString]];
7754            else
7755                [self addStateString: stString];
7756
7757        }
7758    }
7759
7760}
7761-(IBAction) selCSCancel: (id) Sender
7762{
7763    [selCSSheet orderOut: Sender];
7764    [NSApp endSheet: selCSSheet returnCode: 0];
7765
7766}
7767-(IBAction) selCSSelectLess: (id) Sender
7768{
7769    [selCSSheet orderOut: Sender];
7770    [NSApp endSheet: selCSSheet returnCode: SELECTFEWER];
7771
7772}
7773-(IBAction) selCSSelectMore: (id) Sender
7774{
7775    [selCSSheet orderOut: Sender];
7776    [NSApp endSheet: selCSSheet returnCode: SELECTADDITIONAL];
7777
7778}
7779
7780-(IBAction) selCSSelect: (id) Sender
7781{
7782    [selCSSheet orderOut: Sender];
7783    [NSApp endSheet: selCSSheet returnCode: SELECT];
7784
7785}
7786-(IBAction) doSelectCodeSetDialogue: (id) Sender
7787{
7788    NSWindow *who;
7789    if([self global: @"simpleflag"] == 0)
7790    {
7791        NSWARNING(@"Must use a simple search to convert selections into code sets.");
7792        return;
7793    }
7794    [selCSMenu removeAllItems];
7795    [selCSMenu addItemsWithTitles: [gWorkBench allCodeSetNames]];
7796    if([selCSMenu numberOfItems] >= 1) [selCSMenu selectItemAtIndex: 0];
7797    if(exactCodeSetFlag)
7798        [selCSExactSwitch setState: NSOnState];
7799    else
7800        [selCSExactSwitch setState: NSOffState];
7801
7802    if([gPrefBoss detachedSheetValue])
7803        who = nil;
7804    else
7805        who = myWindow;
7806    [NSApp beginSheet: selCSSheet
7807       modalForWindow: who
7808	modalDelegate: self
7809       didEndSelector: @selector(selCSDidEnd:returnCode:contextInfo:)
7810          contextInfo: nil];
7811
7812}
7813-(IBAction) requestCodeDefinition: (id) sender
7814{
7815    int who;
7816    NSString *theCode;
7817    NSMutableString *theDef;
7818    //get the string
7819    if(gWorkBench == nil) return;
7820    if([self global: @"simpleflag"] == 0)
7821    {
7822        NSWARNING(@"Definitions are only available in simple searches");
7823        return;
7824    }
7825    who = [theResults selectedRow];
7826    if(who >= 0)
7827    {
7828        theCode = [[myData objectAtIndex: who] objectForKey: @"_code"];
7829    }
7830    else return;
7831
7832
7833    //ask for definition
7834    theDef = [gWorkBench getDefinition: theCode];
7835    if(!theDef) {
7836        NSString *warning;
7837        warning = [NSString stringWithFormat: @"Cannot find definition for string: %@", theCode];
7838        NSWARNING(warning);
7839        return;
7840    }
7841    //if it exists retain and display it
7842    [theDef retain];
7843    NSRunAlertPanel(theCode, theDef, @"Ok", nil, nil);
7844    //release it
7845    [theDef release];
7846}
7847-(IBAction) requestCodeDefinitionOfSelection: (id) sender
7848{
7849    NSRange who;
7850    NSString *theCode, *theSel;
7851    NSMutableString *theDef;
7852    NSString *warning;
7853    //get the string
7854    if(gWorkBench == nil) return;
7855
7856    who = [thisCell selectedRange];
7857    if(who.length == 0) return;
7858
7859
7860    theSel = [[thisCell string] substringWithRange: who];
7861    theCode = extractFirstCode(theSel);
7862    if(theCode == nil) {NSWARNING(@"Cannot find code in selection."); return;}
7863
7864    //ask for definition
7865    theDef = [gWorkBench getDefinition: theCode];
7866    if(!theDef) {
7867        warning = [NSString stringWithFormat: @"Cannot find definition for string: %@", theCode];
7868        NSWARNING(warning);
7869        return;
7870    }
7871    //if it exists retain and display it
7872    [theDef retain];
7873    NSRunAlertPanel(theCode, theDef, @"Ok", nil, nil);
7874    //release it
7875    [theDef release];
7876}
7877-(BOOL) isReal {return YES;}
7878-(void) appendComment: (NSString *) what
7879{
7880    NSMutableString *hh;
7881    if(what == nil)
7882    {
7883        return;
7884    }
7885    if([what isEqualToString: @""])
7886    {
7887        return;
7888    }
7889    hh = [NSMutableString stringWithString: what];
7890    trimCharNSS(hh,'\"');
7891    [commentArray addObject: hh];
7892    [extraComment appendString: hh];
7893}
7894-(void) endComment: (NSString *) what
7895{
7896    NSMutableString *hh;
7897
7898    if(what == nil)
7899    {
7900        [self clearComments];
7901        return;
7902    }
7903    if([what isEqualToString: @""])
7904    {
7905        [self clearComments];
7906        return;
7907    }
7908    hh = [NSMutableString stringWithString: what];
7909    trimCharNSS(hh,'\"');
7910    FORALL(commentArray)
7911    {
7912        if([temp isEqualToString: hh])
7913        {
7914            [commentArray removeObjectAtIndex: __i];
7915            break;
7916        }
7917    }
7918    ENDFORALL;
7919    [extraComment setString: [commentArray componentsJoinedByString: @""]];
7920
7921}
7922
7923-(void) endLastComment
7924{
7925    if([commentArray count] > 0)
7926        [commentArray removeLastObject];
7927    if([commentArray count] == 0)
7928    {
7929        [self clearComments];
7930        return;
7931    }
7932    else
7933        [extraComment setString: [commentArray componentsJoinedByString: @""]];
7934
7935}
7936
7937-(void) clearComments
7938{
7939    [commentArray removeAllObjects];
7940    [extraComment setString: @""];
7941}
7942-(NSMutableString *) getComment
7943{
7944    return extraComment;
7945}
7946-(void) setComment: (NSString *) what;
7947{
7948    NSMutableString *hh;
7949    if(what == nil)
7950    {
7951        [self clearComments];
7952        return;
7953    }
7954    if([what isEqualToString: @""])
7955    {
7956        [self clearComments];
7957        return;
7958    }
7959    [self clearComments];
7960    hh = [NSMutableString stringWithString: what];
7961    trimCharNSS(hh,'\"');
7962    [extraComment setString: hh];
7963}
7964#ifdef MULTIMEDIA
7965-(void) loadMediaFile: (NSString *) what
7966{
7967    NSString *path;
7968    if([[NSFileManager defaultManager] fileExistsAtPath: what] == YES)
7969    {
7970        if (myMovie != nil) [myMovie release];
7971        myMovie = [[NSMovie alloc] initWithURL: [NSURL fileURLWithPath: what] byReference: YES];
7972        if(myMovie != nil)
7973        {
7974            [myMovieView showController: YES adjustingSize: YES];
7975            //duration = GetMovieDuration([myMovie QTMovie]);
7976            [mediaFileName setStringValue: [what lastPathComponent]];
7977            [myMovieView setMovie: myMovie];
7978            return;
7979        }
7980
7981    }
7982    else
7983    {
7984        if((path = [self fileName]) != nil)
7985        {
7986            NSMutableArray *cmp = [NSMutableArray arrayWithArray: [path pathComponents]];
7987            NSString *newPath;
7988            [cmp removeLastObject];
7989            [cmp addObject: [what lastPathComponent]];
7990            newPath = [cmp componentsJoinedByString: @"/"];
7991            if([[NSFileManager defaultManager] fileExistsAtPath: newPath] == YES)
7992            {
7993                if(myMovie != nil) [myMovie release];
7994                myMovie = [[NSMovie alloc] initWithURL: [NSURL fileURLWithPath: newPath] byReference: YES];
7995                if(myMovie != nil)
7996                {
7997                    [myMovieView showController: YES adjustingSize: YES];
7998
7999                    //duration = GetMovieDuration([myMovie QTMovie]);
8000                    [mediaFileName setStringValue: [newPath lastPathComponent]];
8001                    [myMovieView setMovie: myMovie];
8002                    return;
8003                }
8004            }
8005        }
8006    }
8007    NSWARNING(@"Unable to find or open media file. Remove !mediafile metatag and relocate the file");
8008
8009}
8010
8011-(void) mediaPlayerDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
8012{
8013
8014    [myMovieView stop: nil];
8015    [myTimer invalidate];
8016    [myTimer release];
8017
8018    [myMovie release];
8019    myMovie = nil;
8020    myTimer = nil;
8021}
8022-(IBAction) exitMediaPlayer: (id) Sender
8023{
8024    [mediaSheet orderOut: Sender];
8025    [NSApp endSheet: mediaSheet returnCode: 1];
8026
8027}
8028-(IBAction) setMovieTime: (NSString *) tt;
8029{
8030    long tmValue, scale;
8031    double tm;
8032    if(myMovie == nil ) return;
8033    scale = (long) GetMovieTimeScale( [myMovie QTMovie]);
8034    if(isHHMMSS(tt))
8035    {
8036        tmValue = hhmmss2sec(tt) * scale;
8037    }
8038    else
8039    {
8040        tm = [tt doubleValue];
8041        tmValue = tm * scale;
8042    }
8043    SetMovieTimeValue([myMovie QTMovie], tmValue);
8044    /*
8045        tm = [tt doubleValue];
8046    tmValue = tm * scale;
8047    SetMovieTimeValue([myMovie QTMovie], tmValue);*/
8048}
8049
8050-(IBAction) restartMedia: (id) sender
8051{
8052    int r1;
8053    NSString  *tc;
8054
8055    //if I'm at the end exit
8056    r1 = [theResults selectedRow];
8057    {
8058        //then jump to the new time
8059        tc = [[myData objectAtIndex: r1] objectForKey: [gPrefBoss getAVCode]];
8060        if(tc == nil) return;
8061        if([tc isEqualToString: @""] != YES)
8062        {
8063            [mediaTimeCode setStringValue: tc];
8064            [self setMovieTime: tc];
8065        }
8066    }
8067}
8068
8069-(void) jumpMediaRow: (int) row
8070{
8071    int r1, r2, n;
8072    BOOL p;
8073    NSString *p1, *p2, *tc, *mf;
8074
8075    //if I'm at the end exit
8076    r1 = mediaRow;
8077    r2 = row;
8078    n = [myData count];
8079    if(r2 >= n || r2 <= 0) return;
8080    p = [myMovieView isPlaying];
8081    //what is my file?
8082    p1 = [[[myData objectAtIndex: r1] objectForKey: @"_doc"] path];
8083    //What is the next file?
8084    p2 = [[[myData objectAtIndex: r2] objectForKey: @"_doc"] path];
8085    //are they the same
8086    if([p1 isEqualToString: p2])
8087    {
8088        //then jump to the new time
8089        tc = [[myData objectAtIndex: r2] objectForKey: [gPrefBoss getAVCode]];
8090        if(tc == nil) return;
8091        if([tc isEqualToString: @""] != YES)
8092        {
8093            [mediaTimeCode setStringValue: tc];
8094            [self setMovieTime: tc];
8095        }
8096    }
8097    else
8098    {
8099        [myMovieView stop: nil];
8100        //get file
8101        mf = [mediaDict objectForKey: p2];
8102        if(mf == nil) return;
8103        tc = [[myData objectAtIndex: r2] objectForKey: [gPrefBoss getAVCode]];
8104        if(tc == nil) return;
8105        [myMovie release];
8106        myMovie = nil;
8107        [self loadMediaFile: mf];
8108        {
8109            if([tc isEqualToString: @""] != YES)
8110            {
8111                [mediaTimeCode setStringValue: tc];
8112                [self setMovieTime: tc];
8113            }
8114        }
8115
8116        if(p) [myMovieView start: nil];
8117    }
8118	if([theResults numberOfRows] > 0 && [theResults numberOfRows] > r2)
8119    [theResults selectRow: r2 byExtendingSelection: NO];
8120    mediaRow = r2;
8121
8122    //else stop
8123    //load
8124    //jump to time
8125}
8126
8127
8128-(IBAction) jumpMediaBack: (id) sender
8129{
8130    int r1, r2, n;
8131
8132    //if I'm at the end exit
8133    r1 = [theResults selectedRow];
8134    r2 = r1 - 1;
8135    n = [myData count];
8136    if(r1 == 0) return;
8137    [self jumpMediaRow: r2];
8138}
8139
8140-(IBAction) jumpMediaForward: (id) sender
8141{
8142    int r1,r2, n;
8143
8144    //if I'm at the end exit
8145    r1 = [theResults selectedRow];
8146    r2 = r1 + 1;
8147    n = [myData count];
8148    if(r1 >= n-1) return;
8149    [self jumpMediaRow: r2];
8150}
8151
8152-(void) idleTimer:(id)sender
8153{
8154    long scale, ct;
8155    float time;
8156    if(myMovie == nil) return;
8157    scale = GetMovieTimeScale( [myMovie QTMovie]);
8158    ct =  GetMovieTime([myMovie QTMovie], nil);
8159    time = (float) ct/ (float) scale;
8160    if([gPrefBoss timeFormatHHMMSS] == 1)
8161        [mediaTimeCode setStringValue: sec2hhmmss((unsigned) time)];
8162    else
8163        [mediaTimeCode setStringValue: [NSString stringWithFormat: @"%.2fs", (float) ct/ (float) scale]];
8164    if(jagFlag)
8165        MoviesTask([myMovie QTMovie],0);
8166}
8167
8168-(void) XidleTimer:(id)sender
8169{
8170    long scale, ct;
8171    double time;
8172    if(myMovie == nil) return;
8173    scale = GetMovieTimeScale( [myMovie QTMovie]);
8174    ct =  GetMovieTime([myMovie QTMovie], nil);
8175    time = (double) ct/ (double) scale;
8176    if([gPrefBoss timeFormatHHMMSS] == 1)
8177        [mediaTimeCode setStringValue: sec2hhmmss((unsigned) time)];
8178    else
8179        [mediaTimeCode setStringValue: [NSString stringWithFormat: @"%.2fs", time]];
8180
8181    //[mediaTimeCode setStringValue: [NSString stringWithFormat: @"%.2fs", time];
8182    if(jagFlag)
8183        MoviesTask([myMovie QTMovie],0);
8184}
8185
8186
8187-(IBAction) doMediaPlayer: (id) sender
8188{
8189    int r;
8190    NSDictionary *dd;
8191    NSString *df, *mf;
8192    NSString *tc;
8193    r = [theResults selectedRow];
8194    if([mediaSheet isVisible])
8195    {
8196        [self jumpMediaRow: r];
8197        return;
8198    }
8199    //get row
8200    dd = [myData objectAtIndex: r];
8201    //get file
8202    df = [[dd objectForKey: @"_doc"] path];
8203    mf = [mediaDict objectForKey: df];
8204    if(mf == nil) return;
8205    tc = [dd objectForKey: [gPrefBoss getAVCode]];
8206    if(tc == nil) return;
8207    //does file have a media file
8208    //set the name of the media file
8209    //set the nsmovieview
8210    //jump to the location in the media file
8211    //run
8212    mediaRow = r;
8213    [NSApp beginSheet: mediaSheet
8214       modalForWindow: nil
8215	modalDelegate: self
8216       didEndSelector: @selector(mediaPlayerDidEnd:returnCode:contextInfo:)
8217          contextInfo: nil];
8218    if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_2)
8219        jagFlag = YES;
8220    else
8221        jagFlag = FALSE;
8222
8223    if(myTimer == nil)
8224        myTimer = [[NSTimer scheduledTimerWithTimeInterval:0.1		// interval, 0.1 seconds
8225                                                    target:self
8226                                                  selector:@selector(idleTimer:)		// call this method
8227                                                  userInfo:nil
8228                                                   repeats:YES] retain];
8229
8230    [self loadMediaFile: mf];
8231    {
8232        if([tc isEqualToString: @""] != YES)
8233        {
8234
8235            [mediaTimeCode setStringValue: tc];
8236
8237            [self setMovieTime: tc];
8238        }
8239    }
8240
8241}
8242#else
8243-(void) idleTimer:(id)sender
8244{
8245}
8246#endif
8247@end
8248