//
//  myProject.m
//  TA2 hot
//
//  Created by matthew on Sat Apr 05 2003.
//  Copyright (c) 2003 __MyCompanyName__. All rights reserved.
//
#import "MWFile.h"
#import "myProject.h"
#import "MyDocument.h"
#import "tams.h"
#import "utils.h"
#import "myResults.h"
//#import "ctReadChar.h"
#import "tableBrowser.h"
#import "prefBoss.h"
#import "TAMSCharEngine.h"
#import "appDelegate.h"
#import "MWPath.h"
#import "ctTagInfo.h"
#import "tamsutils.h"
#import "MWKappa.h"
#import "AGRegex.h"
#import "myProject.h"

#define FILEMODE 0
#define RESULTMODE 1
#define SIMPLEINDEX 0
#define NONSIMPLEINDEX 1
#define SECTIONSEARCHINDEX 2
#define NONREGEXCHARINDEX 3
#define REGEXCHARINDEX 4
#define CODESETBASE 2
#define CODESETBASE2 3
#define FILESETBASE 2
#define CODESETBASE3 2
#define FILESETBASE2 3
//#define FIXRESULTS
//#define UNTITLEDBLOCK 1
#define MAKEDIRTY     [self handleMakeDirty];
//Old makedirty[self updateChangeCount: NSChangeDone];
#define MAKECLEAN     [self updateChangeCount: NSChangeCleared];




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

@implementation myProject

-(void) setDirty {MAKEDIRTY;}
-(BOOL) hasFile
{
    if([self fileName] == nil) return NO; else return YES;
}
- (NSString *)windowNibName
{
    // Override returning the nib file name of the document
    // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
    return @"myProject";
}

-(BOOL) codeListDirty {return codeListDirty;}
-(void) setCodeListDirty {codeListDirty = YES; [self broadcastCodeChange: NO];}
-(void) setCodeListClean {codeListDirty = NO;}
-(void) handleMakeDirty
{
    [self setCodeListDirty];
    if([self fileName] != nil && [self shouldSave])
        [self saveDocument: nil];
    else
        [self updateChangeCount: NSChangeDone];
    [self updateCodeCount];
    //[searchCountView setIntValue: [[self searchList] count]];
}
//make sure everyone has a file path
-(BOOL) shouldSave
{
    FORALL(openFiles)
    {
        if([temp hasFile] == NO) return NO;
    
    }
    ENDFORALL;
#ifdef UNTITLEDBLOCK
    FORALL(resultFiles)
    {
        if([temp hasFile] == NO) return NO;
    
    }
    ENDFORALL;
#endif
    return YES;
}

- (IBAction)saveDocument:(id)sender
{
    if([self shouldSave] == NO)
    {
            NSWARNING(@"You must save or close all files (including search results) in this project before saving the project itself.");
            return;
    }
    if([self hasFile] == NO)
    {
    
   	if([self shouldSave] == NO  ) 
        {
            NSWARNING(@"You must save all files in this project before saving the project itself.");
            return;
        }
        if(absPathMode != ABSPATHMODE)
        {
            NSWARNING(@"Saving with absolute paths. Reselect path option and save again other path modes.");
            absPathMode = ABSPATHMODE;
        }
    }
    else
        [savingFileName setString: [self fileName]];
    [super saveDocument: sender];

        
 #ifdef attempt2       
    if([self windowShouldClose: nil] == NO ) return;
        NSSavePanel *mysp = [NSSavePanel savePanel];
    //do we need to save
    if([self fileName] == nil && absPathMode != ABSPATHMODE)
    {
       for(;;)
       {
            n = [mysp runModal];
            if(n ==  NSFileHandlingPanelOKButton || n == NSFileHandlingPanelCancelButton) break;
        }
    }
    else
    {
        if([self fileName] != nil) [savingFileName setString: [self fileName]];
        [super saveDocument: sender];
        return;
    }
    if(n == NSFileHandlingPanelCancelButton) return;
    [savingFileName setString: [mysp filename]];
    
    [[self dataRepresentationOfType: [[NSDocumentController sharedDocumentController] typeFromFileExtension: [mysp requiredFileType]]] writeToFile: savingFileName atomically: YES];
    [self setFileName: savingFileName];
    
#endif
#ifdef attempt1
    BOOL doubleSave;
    NSString *fn;
    fn = nil;
    fn = [self fileName];
    doubleSave = NO;
    if(fn != nil)
        [super saveDocument: sender];
    else
    {
        if(absPathMode != ABSPATHMODE) 
            doubleSave = YES;
        if(doubleSave)
        {
            absPathMode = ABSPATHMODE;
            [super saveDocument: sender];
        }
        else
        {
            [super saveDocument: sender];
            return;
        }
        
        if(doubleSave && [self fileName] != nil)
        {
            absPathMode = RELPATHMODE;
            [super saveDocument: sender];
        }
    }
#endif
}
- (IBAction)saveDocumentTo:(id)sender
{
    

    if([self shouldSave] == NO)
    {
            NSWARNING(@"You must save or close all files (including search results) in this project before saving the project itself.");
            return;
    }
        
    if([self hasFile] == NO)
    {
    
   	if([self shouldSave] == NO  ) 
        {
            NSWARNING(@"You must save all files in this project before saving the project itself.");
            return;
        }
        if(absPathMode != ABSPATHMODE)
        {
            NSWARNING(@"Saving with absolute paths. Reselect path option in \"Preferences\" and save again for relative paths.");
            absPathMode = ABSPATHMODE;
        }
    }
    if(absPathMode != ABSPATHMODE)
    {
        NSWARNING(@"Saving with absolute paths. Reselect path option and save again for relative paths.");
        absPathMode = ABSPATHMODE;
    }
    [super saveDocumentTo: sender];
}
- (IBAction)saveDocumentAs:(id)sender
{
    int pm;
    pm = absPathMode;
    if([self shouldSave] == NO)
    {
            NSWARNING(@"You must save or close all files (including search results) in this project before saving the project itself.");
            return;
    }

    if([self hasFile] == NO)
    {
    
   	if([self shouldSave] == NO  ) 
        {
            NSWARNING(@"You must save all files in this project before saving the project itself.");
            return;
        }
        if(absPathMode != ABSPATHMODE)
        {
            NSWARNING(@"Saving with absolute paths. Reselect path option in \"Preferences\" and save again for relative paths.");
            absPathMode = ABSPATHMODE;
        }
    }
    if(absPathMode != ABSPATHMODE)
    {
        NSWARNING(@"Saving with absolute paths. Reselect path option and save again for relative paths.");
        absPathMode = ABSPATHMODE;
    }
    [super saveDocumentAs: sender];

#ifdef attempt1
    BOOL doubleSave;
    doubleSave = NO;
    if(absPathMode != ABSPATHMODE) doubleSave = YES;
    if(doubleSave)
    {
        absPathMode = ABSPATHMODE;
        [super saveDocumentAs: sender];
    }
    else
    {
        [super saveDocumentAs: sender];
        return;
    }
    
    if(doubleSave)
    {
        absPathMode = pm;
        [self saveDocument: sender]; //this is the 2nd save, now that we have a path
    }
#endif
}


-(NSMutableArray *) name2MWFileArray: (NSArray *) who
{
    NSMutableArray *mm;
    MWFile *mf;
    mm = [NSMutableArray array];
    FORALL(who)
    {
        mf = [self fileForName: temp];
        if(mf != nil)
            [mm addObject: mf];
    }
    ENDFORALL;
    return mm;
}
-(NSMutableArray *) MWFile2NameArray: (NSArray *) who
{
    NSMutableArray *mm;
    mm = [NSMutableArray array];
    FORALL(who)
    {
        [mm addObject: [[[temp name] copy] autorelease]];
    }ENDFORALL;
    return mm;
}

-(NSMutableArray *) MWFile2NameArrayRedux: (NSArray *) who
{
    NSMutableArray *mm;
    mm = [NSMutableArray array];
    FORALL(who)
    {
        if([temp hasFile])
            [mm addObject: [[[temp name] copy] autorelease]];
    }ENDFORALL;
    return mm;
}
-(NSDictionary *) fileSetsForSaving
{
    NSMutableDictionary *ans = [NSMutableDictionary dictionary];
    NSArray *nn = [self allFileSetNames];
    NSArray *old, *nw;
    
    FORALL(nn)
    {
        old = [fileSets objectForKey: temp];
        nw = [self MWFile2NameArrayRedux: old];
        [ans setObject: nw forKey: temp];
    }
    ENDFORALL;
    return ans;
}

-(void) loadFileSets: (NSDictionary *) savedFS
{
    NSArray *nn = [savedFS allKeys];
    NSArray *old, *nw;
    
    FORALL(nn)
    {
#ifdef FIXRESULTS
        if([temp isEqualToString: @"Results"]) continue;
#endif
        old = [savedFS objectForKey: temp];
        nw = [self name2MWFileArray: old];
        if(nw != nil)
            [fileSets setObject:nw forKey: temp];
    }
    ENDFORALL;
}

-(NSMutableDictionary *) convertedNSL: (NSDictionary *) who
{
    NSMutableDictionary *tt;
    tt = [[NSMutableDictionary alloc]init];
    if([who objectForKey: @"init"] != nil)
    {
        [tt setObject: [[who objectForKey: @"init"] name] forKey: @"init"];
    }
    [tt setObject: [self MWFile2NameArray: [who objectForKey: @"searchList"]]
        forKey: @"searchList"];
    return tt;
}

-(NSMutableDictionary *) reconvertedNSL: (NSDictionary *) who
{
    NSMutableDictionary *tt;
    tt = [[NSMutableDictionary alloc] init];
    if([who objectForKey: @"init"] != nil)
    {
        [tt setObject: [self fileForName: [who objectForKey: @"init"]] forKey: @"init"];
    }
    [tt setObject: [self name2MWFileArray: [who objectForKey: @"searchList"]]
        forKey: @"searchList"];
    return tt;
}


-(NSDictionary*) getSaveableNamedSearchList
{
    NSArray *ak;
    NSMutableDictionary *convDict;
    convDict = [[NSMutableDictionary alloc] init];
    ak = [namedSearchList allKeys];
    FORALL(ak)
    {
        [convDict setObject: [self convertedNSL: [namedSearchList objectForKey: temp]]
            forKey: temp];
    }
    ENDFORALL;
    return convDict;

}

- (NSData *)dataRepresentationOfType:(NSString *)aType
{
    NSMutableArray *masterArray = [NSMutableArray array];
    NSMutableArray *fileArray = [NSMutableArray array];
    NSMutableArray *resultArray = [NSMutableArray array];
    NSMutableArray *searchArray = [NSMutableArray array];
    NSString *pPath, *tPath;
    // Insert code here to write your document from the given data.  You can also choose to override -fileWrapperRepresentationOfType: or -writeToFile:ofType: instead.
    //construct my path
#ifdef USESXML
    if([aType isEqualToString:  @"XML TAMS Project"] == YES)
        return [self keyedDataRepresentation];
#endif
    tPath = [self fileName];
    pPath = [savingFileName stringByDeletingLastPathComponent];
    //make an array
    //add to it a version #
    [masterArray addObject: @"9"];
    //add to it the search file list
    FORALL(openFiles)
    {
        switch(absPathMode)
        {
            case ABSPATHMODE:
            [fileArray addObject: [[temp path] stringByStandardizingPath]];
            break;
            
            case RELPATHMODE:
            [fileArray addObject: abs2rel(pPath, [temp path])];
            break;
            
            case LOCPATHMODE:
            [fileArray addObject: [(MWFile *)temp name]];
            break;
        };
    }
    ENDFORALL;
    [masterArray addObject: fileArray];
    FORALL(searchFiles)
    {
       switch(absPathMode)
        {
            case ABSPATHMODE:
             [searchArray addObject: [[temp path] stringByStandardizingPath]];
             break;
             
          case RELPATHMODE:
             [searchArray addObject: abs2rel(pPath, [temp path])];
             break;
             
            case LOCPATHMODE:
          [searchArray addObject:  [(MWFile *)temp name]];
             break;
        };
               
    }
    ENDFORALL;
    [masterArray addObject: searchArray];
    //add to it the init file
    if (initFile)
    {
        switch(absPathMode)
        {
             case ABSPATHMODE:
                [masterArray addObject: [[initFile path] stringByStandardizingPath]];
                break;
          case RELPATHMODE:
            [masterArray addObject: abs2rel(pPath, [initFile path])];
            break;
            
            case LOCPATHMODE:
              [masterArray addObject: [initFile name]];
            break;
     
        };
     }
    else
        [masterArray addObject: @""];
        
    //add to it the code dictionary
    [masterArray addObject: codeList];
    //save the path mode
    switch(absPathMode)
    {
            case ABSPATHMODE:
                [masterArray addObject: @"A"];
                break;
          case RELPATHMODE:
            [masterArray addObject: @"R"];
            break;
            
            case LOCPATHMODE:
              [masterArray addObject: @"F"];
            break;
    
    };
    [masterArray addObject: [autoSetDict copy]];
    FORALL(resultFiles)
    {
#ifdef UNTITLEDBLOCK
#else
        if([temp hasFile] == NO) continue;
#endif
        switch(absPathMode)
        {
            case ABSPATHMODE:
            [resultArray addObject: [[temp path] stringByStandardizingPath]]; break;
            case RELPATHMODE:
            [resultArray addObject: abs2rel(pPath, [temp path])]; break;
            case LOCPATHMODE:
            [resultArray addObject: [(MWFile *)temp name]]; break;
        };
            
    }
    ENDFORALL;
    [masterArray addObject: resultArray];
    [masterArray addObject: [self getSaveableNamedSearchList]];
    if([searchListMenu numberOfItems] > 0)
        [masterArray addObject: [[[searchListMenu selectedItem] title] copy]];
    else
        [masterArray addObject: @""];
    [masterArray addObject: namedSrch];
    [masterArray addObject: [codeSets copy]];
    [masterArray addObject: [self fileSetsForSaving]];
    [masterArray addObject: [[fileSetCurrName copy] autorelease]];
    if(tempCodeSet)
        [masterArray addObject: [NSString stringWithString: @""]];
    else
        [masterArray addObject: [[codeSetCurrName copy] autorelease]];
    [masterArray addObject: summReports];
    //serialize it
    
    return [NSArchiver archivedDataWithRootObject: masterArray];
}

-(MWFile *) fileForPath: (NSString *) where
{
    FORALL(openFiles)
    {
        if([where isEqualToString: [temp path]])
            return temp;
    }
    ENDFORALL;
    FORALL(resultFiles)
    {
        if([where isEqualToString: [temp path]])
            return temp;
    }
    ENDFORALL;
    return nil;
}

-(MWFile *) fileForName: (NSString *) where
{
    FORALL(openFiles)
    {
        if([where isEqualToString: [temp name]])
            return temp;
    }
    ENDFORALL;
    FORALL(resultFiles)
    {
        if([where isEqualToString: [temp name]])
            return temp;
    }
    ENDFORALL;
    return nil;
}
-(void) setUseableNamedSearchList: (NSDictionary *) who
{
    NSArray *ak;
    NSMutableDictionary *convDict;
    convDict = [[NSMutableDictionary alloc] init];
    ak = [who allKeys];
    FORALL(ak)
    {
        [namedSearchList setObject: [self reconvertedNSL: [who objectForKey: temp]]
            forKey: temp];
    }
    ENDFORALL;


}
-(NSMutableDictionary *) getReports{return reportDictionary;}

- (BOOL)loadDataRepresentation:(NSData *)data ofType:(NSString *)aType
{
    // Insert code here to read your document from the given data.  You can also choose to override -loadFileWrapperRepresentation:ofType: or -readFromFile:ofType: instead.
    NSMutableArray * masterArray;
    NSArray *fileList;
    MWFile *sfile;
    int vers;
    NSString *tPath;//= [self fileName];
     NSString    *pPath = [[self fileName] stringByDeletingLastPathComponent];
 
#ifdef USESXML  
     if([aType isEqualToString: @"XML TAMS Project"] == YES)
         return [self loadKeyedData: data];
#endif
 
    masterArray = [NSUnarchiver unarchiveObjectWithData: data];
    tPath = [self fileName];
    vers = [[masterArray objectAtIndex: 0] intValue];
    if([[masterArray objectAtIndex: 0] isEqualToString: @"2.0c"] || vers >= 3)
    {
        [autoSetDict addEntriesFromDictionary: [masterArray objectAtIndex: 6]];
    }
    if([[masterArray objectAtIndex: 0] isEqualToString: @"2.0b"]||
        [[masterArray objectAtIndex: 0] isEqualToString: @"2.0c"]||
        vers >= 3)
    {
        if([[masterArray objectAtIndex: 5] isEqualToString: @"A"])
            absPathMode = ABSPATHMODE;
        else if([[masterArray objectAtIndex: 5] isEqualToString: @"R"])
            absPathMode = RELPATHMODE;
        else  if([[masterArray objectAtIndex: 5] isEqualToString: @"L"])
             absPathMode = LOCPATHMODE;
       
        else  if([[masterArray objectAtIndex: 5] isEqualToString: @"F"])
             absPathMode = LOCPATHMODE;
        
        if([[masterArray objectAtIndex: 0] isEqualToString: @"2.0c"] || vers >= 3)
        {
         fileList = [masterArray objectAtIndex: 7];
           FORALL(fileList)
            {
                if(isAbsPath(temp))
                {
                    MWFile *mwf =[[MWFile alloc] initWithPath: [temp stringByStandardizingPath]];
                    [resultFiles addObject: mwf];
#ifdef FIXRESULTS
                    [self addFile: mwf toSet: @"Results"];
#endif
                }
                else
                {
                    MWFile *mwf = [[MWFile alloc] initWithPath: rel2abs(pPath, temp)];
                    [resultFiles addObject: mwf];
#ifdef FIXRESULTS
                    [self addFile: mwf toSet: @"Results"];
#endif
                }
            }
            ENDFORALL;
        }
    }
    else
        absPathMode = ABSPATHMODE;
    
    if([[masterArray objectAtIndex: 0] isEqualToString: @"2.0a"] ||
        [[masterArray objectAtIndex: 0] isEqualToString: @"2.0b"]||
        [[masterArray objectAtIndex: 0] isEqualToString: @"2.0c"] ||
        vers >= 3)
    {
        fileList = [masterArray objectAtIndex: 1];
        FORALL(fileList)
        {
            if(isAbsPath(temp))
            {
                MWFile *mwf = [[MWFile alloc] initWithPath: [temp stringByStandardizingPath]];
                [openFiles addObject: mwf];
                [allFiles addObject: mwf];
            }
            else
            {
                MWFile *mwf =[[MWFile alloc] initWithPath: rel2abs(pPath, temp)];
    
                 [openFiles addObject: mwf];
                 [allFiles addObject: mwf];
            }
        }
        ENDFORALL;
        fileList = [masterArray objectAtIndex: 2];
        FORALL(fileList)
        {
            if(isAbsPath(temp))
                sfile = [self fileForPath: [temp stringByStandardizingPath]];
            else
                sfile = [self fileForPath: rel2abs(pPath,temp)];
            if(sfile)
            {
                    [searchFiles addObject: sfile];
            }
        }
        ENDFORALL;
        
        //[openFiles addObjectsFromArray: [masterArray objectAtIndex: 1]];
        if([[masterArray objectAtIndex: 3] isEqualToString: @""]) initFile = nil;
        else
        {
            NSString *iiFile;
            iiFile = [masterArray objectAtIndex: 3];
            if(isAbsPath(iiFile))
                initFile = [self fileForPath: [iiFile stringByStandardizingPath]];
            else
                 initFile = [self fileForPath: rel2abs(pPath, iiFile)];
            [initFileName setStringValue: [initFile name]];
            [searchFiles removeObject: initFile];
            [searchListView reloadData];
        }
        [codeList addEntriesFromDictionary: [masterArray objectAtIndex: 4]];
        if(vers >= 3)
        {
            
            [self setUseableNamedSearchList: [masterArray objectAtIndex: 8]];
        }
        if(vers >= 4)
        {
            if([[masterArray objectAtIndex: 9] isEqualToString: @""] == NO)
                [searchListMenu selectItemWithTitle: [masterArray objectAtIndex: 9]];
        }
        if(vers >= 5)
        {
            [namedSrch addEntriesFromDictionary: [masterArray objectAtIndex: 10]];
        }
        if(vers >= 6) 
        {
            [codeSets addEntriesFromDictionary: [masterArray objectAtIndex: 11]];
        }
        if(vers >= 7)
        {
            [self loadFileSets: [masterArray objectAtIndex: 12]];
            //[self loadFileSetWithName: [masterArray objectAtIndex: 13]];
            [fileSetCurrName setString: [masterArray objectAtIndex: 13]];
         }
         else
         {
            [[fileSets objectForKey: @"Results"] addObjectsFromArray: resultFiles];
        }
         if(vers >=8)
         {
            [codeSetCurrName setString: [masterArray objectAtIndex: 14]];
         }
         if (vers >= 9)
         {
            [summReports addEntriesFromDictionary: [masterArray objectAtIndex: 15]];
            [self rebuildSummReportMenu];
        }
        [self setCodeListDirty];
        return YES;
    
    }
    else return NO;
}

-(id) init
{
    [super init];
    
    //globals
    
    //multiFileFlag = 0;
    tempCodeSet = NO;
    reanalysisMode = NO;
    uniqueNumber = 0;
    absPathMode = ABSPATHMODE;
    fileViewMode = FILEMODE;
    [self setCodeListDirty];
    fList = openFiles = [[NSMutableArray alloc] init];
    allFiles =  [[NSMutableArray alloc] init];
    tempCodeList =  [[NSMutableArray alloc] init];
    tempCodeStack =  [[NSMutableArray alloc] init];
    searchFiles = [[NSMutableArray alloc] init];
    resultFiles = [[NSMutableArray alloc] init];
    codeList = [[NSMutableDictionary alloc] init];
    reportDictionary = [[NSMutableDictionary alloc] init];
    autoSetDict = [[NSMutableDictionary alloc] init];
    namedSrch = [[NSMutableDictionary alloc] init];
    namedSearchList = [[NSMutableDictionary alloc] init];
    savingFileName = [[NSMutableString alloc] init];
    codeSetCurrName = [[NSMutableString alloc] init];
    fileSetCurrName = [[NSMutableString alloc] init];
    codeSets = [[NSMutableDictionary alloc] init];
    fileSets = [[NSMutableDictionary alloc] init];
    [fileSets setObject: [NSMutableArray array] forKey: @"Results"]; //done so there is always access
    codeSetButtons = [[NSMutableArray alloc] init];
    summReports = [[NSMutableDictionary alloc] init];
    theHotCodeList = [[NSMutableArray alloc] init];
    
    //locals
    return self;
}
-(void) dealloc
{
    [fileSetCurrName release];
    [allFiles release];
    [fileSets release];
    [tempCodeList release];
    [tempCodeStack release];
    [codeSets release];
    [openFiles release];
    [codeSetCurrName release];
    [codeSetButtons release];
    [searchFiles release];
    [resultFiles release];
    [codeList release];
    [savingFileName release];
    [reportDictionary release];
    [namedSearchList release];
    [namedSrch release];
    [autoSetDict release];
    [summReports release];
    [theHotCodeList release];
    [super dealloc];
}
- (void) shoveWindow
{
    [self openSelectedFile: nil];
}

-(void) openMWFile: (MWFile *) who type: (int) what
{
    id myfile;
    NSDocumentController *myDC;
    NSString *myPath;
    myDC = [NSDocumentController sharedDocumentController];

    if([who open] == YES)
    {
        [[who filePointer] moveForward];
        //[[openFiles objectAtIndex: row] moveForward];
    }
    else
    {
        NSString *myfp;
        NSMutableArray *myfpc;
        
        [myDC setShouldCreateUI: YES];
        //if filemode is folder
        //get my path
        //get the path
        //use only the name
        //otherwise the old way
        myPath = [who path] ;
        if(absPathMode == LOCPATHMODE)
        {
            myfp = [self fileName];
            if(myfp != nil)
            {
                myfpc =[NSMutableArray arrayWithArray: [myfp pathComponents]];
                [myfpc removeLastObject];
                if([[NSFileManager defaultManager] changeCurrentDirectoryPath: [NSString pathWithComponents: myfpc]] == YES)
		{
                    myfile = [myDC openDocumentWithContentsOfFile: [[myPath lastPathComponent] stringByStandardizingPath]  display:YES];
			if(myfile) [myfile setFileName: myPath];
		} 
               else NSWARNING(@"Could not switch directory path.");
            }
            else NSWARNING(@"Project is not saved, cannot use folder path mode");
        }
        else
	{
            myfile = [myDC openDocumentWithContentsOfFile: myPath  display:YES];
		if(myfile){[myfile setFileName: myPath]; NSLog(@"opening: %@\n",myPath);}
		
	}
        //myfile = [myDC makeDocumentWithContentsOfFile: myPath ofType: @"RTFD"];
        if(!myfile)
        {
            NSWARNING(@"File not found.");
            return;
        }
        [myfile retain];
        [who setOpenFile: myfile];
        [myfile setMWFile: who];
        [myfile setGWorkBench: self];
        [myfile setTitleFromFile];
        if(what == SOURCETYPE) {
            [myfile scanForMetas];
            [myfile moveForward];
            [myfile scrollToTop];
            [myfile setReanalysisState: [self reanalysisMode]];
        [[NSNotificationCenter defaultCenter] addObserver: myfile
            selector: @selector(goReanalysisMode:)
            name: @"TAGoReanalysisMode"
            object: self];
        }
        else if (what == RESULTFILETYPE)
        {
            [myfile moveForward];
            [myfile loadSavedData];
		[myfile setFileName: myPath];
        }
    }

}
-(IBAction) openSelectedFile: (id) Sender
{
    int row;
    NSDocumentController *myDC;
    
    myDC = [NSDocumentController sharedDocumentController];
    row = [fileListView selectedRow];
    if(row < 0) return;
    [self openMWFile: [fList objectAtIndex: row] type: fileViewMode];

}

-(BOOL) mwFileExists: (MWFile *) who
{
    FORALL(openFiles)
    {
        if(who == temp) return YES;
    }
    ENDFORALL;

    FORALL(resultFiles)
    {
        if(who == temp) return YES;
    }
    ENDFORALL;

    return NO;
}
-(IBAction) doCloseWindowAction: (id) Sender
{
    if([self windowShouldClose: self])
    {
        [closeButtonTarget performSelector: (SEL) closeButtonSel withObject: self afterDelay: 0.0];
        //[myWindow performClose: self];
    }
}
- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
    id cButton;
    NSArray *myMenuItems;
    NSMenuItem *myItem;
    [codeListView setTarget: self];
    [codeListView setDoubleAction: @selector(displaySelData)];
    [fileListView setTarget: self];
    [fileListView setDoubleAction: @selector(shoveWindow)];
    //get old
#ifdef PANTHERVERSION
    cButton = [myWindow standardWindowButton:NSWindowCloseButton ];
    closeButtonTarget = [cButton target];
    closeButtonSel = [cButton action];
    
    //switch to the new
    [cButton setTarget: self];
    [cButton setAction: @selector(doCloseWindowAction:)];
#endif
    if(initFile) 
        [initFileName setStringValue: [initFile name]];
    [searchListMenu removeAllItems];
    myMenuItems = [namedSearchList allKeys];
    FORALL(myMenuItems)
    {
        [searchListMenu addItemWithTitle: temp];
        myItem = [searchListMenu lastItem];
    [myItem setTarget: self];
    [myItem setAction: @selector(loadSL:)];

    }
    ENDFORALL;
    [searchNameMenu removeAllItems];
    myMenuItems = [namedSrch allKeys];
    FORALL(myMenuItems)
    {
        [searchNameMenu addItemWithTitle: temp];
        myItem = [searchNameMenu lastItem];
        [myItem setTarget: self];
        [myItem setAction: @selector(doNamedSrch:)];

    }
    ENDFORALL;
    [self rebuildSummReportMenu];
    [self reloadFileSet];
    [self loadCurrCodeSet];
    [self updateCodeCount];
}
- (void)windowDidLoad
{

}
- (id)initWithWindowNibName:(NSString *)windowNibName
{
    [super init];
     //globals
    //multiFileFlag = 0;
    //gSearchList = [[NSMutableArray alloc] init];
    uniqueNumber = 0;

    fList = openFiles = [[NSMutableArray alloc] init];
    searchFiles = [[NSMutableArray alloc] init];
    resultFiles = [[NSMutableArray alloc] init];
    reportDictionary = [[NSMutableDictionary alloc] init];
    codeList = [[NSMutableDictionary alloc] init];
    savingFileName = [[NSMutableString alloc] init];
    //locals
    return self;
}

-(int) emptyF{ return emptyF;}
-(int) exactF {return exactF;}
-(int) rawF {return rawF;}
-(int) simpleF {return simpleF;}
-(int) sectionF {return sectionF;}
-(int) regexCharF {return regexCharF;}
-(int) nonRegexCharF {return nonRegexCharF;}

-(MWFile *) getMWFile
{
    MWFile *who;
    int row;
    row = [fileListView selectedRow];
    who= [[self hotFileSet] objectAtIndex: row];
    return who;
}

-(MWFile *) searchFileName
{
    int row;
    row = [searchListView selectedRow];
    return [searchFiles objectAtIndex: row];
}

/*
-(void) registerWindow: (MyDocument *) who
{
    [openFiles addObject: who];
    [self updateFileView];
}
*/
- (void) removeFileFromSets: (MWFile *) who
{
    NSArray *w;
    w = [fileSets allKeys];
    FORALL(w)
    {
        [[fileSets objectForKey: temp] removeObject: who];
    }
    ENDFORALL;
    
}
- (void) unregisterWindow: (MyDocument *) who
{
    FORALL(openFiles)
    {
        if(who == [temp filePointer])
        {
            [(MWFile *)temp setPath: [who fileName]];
            [temp setOpenFile: nil];
        }
    }
    ENDFORALL;
}
-(MWFile *) getInitFile {return initFile;}
//may need to change
- (BOOL) isInitFile: (MWFile *) who
{
    if(who == initFile) return YES;
    else return NO;
}

-(NSString *) uniqueString;
{
	return [NSString stringWithFormat: @"TAMSSTRING %d", uniqueNumber++];
}
- (NSMutableArray *) fileList
{

    return fList;
        
}
- (NSMutableArray *) searchList
{
    return searchFiles;
}

-(void) registerResult: (myResults *) what
{
    MWFile *who;
        who = [[MWFile alloc] init];
        [who setOpenFile: what];
        [who setHasFile: NO];

    [resultFiles addObject: who];
    [self addFile: who toSet: @"Results"];
    [what setMWFile: who];
    MAKEDIRTY;
    //[self setDirty];
}

-(void) unregisterResult: (MWFile *) who
{
    [resultFiles removeObject: who];
    [self removeFile: who fromSet: @"Results"];
    if([who hasFile]) [self setDirty];
}

-(void) broadcastCodeChange: (BOOL) colorize
{
    FORALL(openFiles)
    {
        if([(MWFile *)temp open])
        {
            [(MyDocument *)[(MWFile *)temp filePointer] updateCodeWindow];
            if([gPrefBoss autoColorValue] && colorize)
                [(MyDocument *)[(MWFile *)temp filePointer] doColorize: nil];
                
        }
    }
    ENDFORALL;
    if([self isCodeSet] == YES)
    {
        NSString *css = [NSString stringWithFormat: @"Codes: %@", [self currCodeSet]];
        NSSETHEADER(codeListView, @"Codes",css);
    }
    else
    {
        NSSETHEADER(codeListView, @"Codes",@"Codes");
    }
    [codeListView reloadData];
}

-(BOOL) isCodeActive: (NSString*) who
{
    NSDictionary *myDef;
    
    myDef = [codeList objectForKey: who];
    if(myDef)
    {
        if([[myDef objectForKey: @"active"] isEqualToString: @"YES"])
            return YES;
    }
    
    return NO;


}
-(void) addCode: (NSString *) what definition: (NSString *) info active: (BOOL) act append: (BOOL) app
{
   NSMutableDictionary *myEntry;
    NSMutableString *myDef, *oldDef;
    myEntry = [codeList objectForKey: what];
    if(myEntry)
    {
    }
    else
    {
        myEntry = [[NSMutableDictionary alloc] init];
        [codeList setObject: myEntry forKey: what];
    }
    
    if(app)
    {
        oldDef = [myEntry objectForKey: @"definition"];
        myDef = [NSMutableString string];
        if([gPrefBoss dateTimeValue]) {[myDef appendString: [[NSDate date] description]];
            [myDef appendString: @": "];
            }
        if(oldDef)
        {
            [myDef appendString: oldDef];
            [myDef appendString: @" "];
        }
        [myDef appendString: info];
            
        
    }
    else
    {
        if([gPrefBoss dateTimeValue]) {[myDef appendString: [[NSDate date] description]];
            [myDef appendString: @": "];
            }

        [myDef appendString: info];
    }
    [myDef ADDCHAR('\n')];
    
    [myEntry setObject: myDef forKey: @"definition"];
    if(act)
        [myEntry setObject: @"YES" forKey: @"active"];
    else
        [myEntry setObject: @"NO" forKey: @"active"];
    [self addCodeToCurrSet: what];
    MAKEDIRTY;	
        
}


    
- (void) newCode: (NSString *) what definition: (NSString *) info active: (BOOL) act
{
    NSMutableDictionary *myEntry;
    NSMutableString *myDef = [[NSMutableString alloc] init];
    
    myEntry = [codeList objectForKey: what];
    if(myEntry)
    {
        if([gPrefBoss dateTimeValue]) {[myDef appendString: [[NSDate date] description]];
            [myDef appendString: @": "];
            }


        [myDef appendString: [myEntry objectForKey: @"definition"]];
        [myDef appendString: @" "];
        [myDef appendString: info];    
        [myDef ADDCHAR('\n')];

        [myEntry setObject: myDef forKey: what];
        if(act)
            [myEntry setObject: @"YES" forKey: @"active"];
        else
            [myEntry setObject: @"NO" forKey: @"active"];
        [self addCodeToCurrSet: what];
    }
    else
    {
        myEntry = [[NSMutableDictionary alloc] init];
        if([gPrefBoss dateTimeValue]) {[myDef appendString: [[NSDate date] description]];
            [myDef appendString: @": "];
            }

        [myDef appendString: info];
        [myDef ADDCHAR('\n')];
        [myEntry setObject: myDef forKey: @"definition"];
        if(act)
            [myEntry setObject: @"YES" forKey: @"active"];
        else
            [myEntry setObject: @"NO" forKey: @"active"];
        
        [codeList setObject: myEntry forKey: what];
        [self addCodeToCurrSet: what];
    }
    MAKEDIRTY;
    [myDef release];
}

- (void) newCode: (NSString *) what definition: (NSString *) info realColor: (NSColor *) whatColor
{
    NSMutableDictionary *myEntry;
    NSMutableString *myDef = [[NSMutableString alloc] init];
    
    myEntry = [codeList objectForKey: what];
    if(myEntry)
    {
        if([gPrefBoss dateTimeValue]) {[myDef appendString: [[NSDate date] description]];
            [myDef appendString: @": "];
        }
        [myDef setString: [myEntry objectForKey: @"definition"]];
        [myDef appendString: @" "];
        [myDef appendString: info];
        [self addCodeToCurrSet: what];
        [myEntry setObject: myDef forKey: what];
    }
    else
    {
        myEntry = [[NSMutableDictionary alloc] init];
        if([gPrefBoss dateTimeValue]) {[myDef appendString: [[NSDate date] description]];
            [myDef appendString: @": "];
        }
        
        [myDef appendString: info];
        [myDef ADDCHAR('\n')];
        [myEntry setObject: myDef forKey: @"definition"];
        [myEntry setObject: @"YES" forKey: @"active"];
        [myEntry setObject: [NSNumber numberWithInt: otherColor] forKey: @"color"];
        [myEntry setObject: whatColor forKey: @"realColor"];
        [self addCodeToCurrSet: what];
        
        [codeList setObject: myEntry forKey: what];
    }
    MAKEDIRTY;
    [myDef release];
    
}

- (void) newCode: (NSString *) what definition: (NSString *) info color: (int) whatColor
{
    NSMutableDictionary *myEntry;
    NSMutableString *myDef = [[NSMutableString alloc] init];
    
    myEntry = [codeList objectForKey: what];
    if(myEntry)
    {
        if([gPrefBoss dateTimeValue]) {[myDef appendString: [[NSDate date] description]];
            [myDef appendString: @": "];
            }
        [myDef setString: [myEntry objectForKey: @"definition"]];
        [myDef appendString: @" "];
        [myDef appendString: info];
        [self addCodeToCurrSet: what];
        [myEntry setObject: myDef forKey: what];
    }
    else
    {
        myEntry = [[NSMutableDictionary alloc] init];
        if([gPrefBoss dateTimeValue]) {[myDef appendString: [[NSDate date] description]];
            [myDef appendString: @": "];
            }
        
        [myDef appendString: info];
        [myDef ADDCHAR('\n')];
        [myEntry setObject: myDef forKey: @"definition"];
        [myEntry setObject: @"YES" forKey: @"active"];
        [myEntry setObject: [NSNumber numberWithInt: whatColor] forKey: @"color"];
        [self addCodeToCurrSet: what];

        [codeList setObject: myEntry forKey: what];
    }
    MAKEDIRTY;
    [myDef release];

}

-(void) setInitMWFile: (MWFile *) who
{
    if (initFile == who || who == nil)
    {
	[initFileName setStringValue: @""];
	initFile = nil;
    }
    else
    {
	initFile = who;
	[initFileName setStringValue: [who name]];
	[searchFiles removeObject: who];
	[searchListView reloadData];
    }
       MAKEDIRTY;


}

- (IBAction)clearSearch:(id)sender
{
    [searchStringView setStringValue: @""];
}

-(BOOL) isInSearchList: (MWFile *) who
{
    FORALL(searchFiles)
    {
        if(temp == who) return YES;
    }ENDFORALL;
    return NO;
}
- (IBAction) doAdd:(id)sender
{
int n;
    BOOL m;
    //don't add the init file
	if([fList count] == 0) return;
   n = [fileListView selectedRow];
	//NSLog(@"Selected row = %d\n", n);
   if(n < 0 && [fList count] > 0)
	[fileListView selectRow: 0 byExtendingSelection: NO];
     if(fileViewMode == RESULTMODE) 
    {
        NSWARNING(@"Can only modify search list from a source set.");
        return;
    }
    if([self isInitFile: [self getMWFile]] == YES) return;
    m = [self isInSearchList: [self getMWFile]];
    if( m == YES)
        return;
   [searchFiles addObject: [self getMWFile]]; 
  if(n < [fList count]-1)
   {
        [fileListView selectRow: n+1 byExtendingSelection: NO];
        [fileListView reloadData];
    }
   [searchListView reloadData];
   MAKEDIRTY;
}

- (IBAction)doAddAll:(id)sender
{
    if(fileViewMode == RESULTMODE) 
    {
        NSWARNING(@"Can only modify search list from data source file set.");
        return;
    }
    [self doRemoveAll: self];
//NSLog(@"removed all\n");
    [searchFiles addObjectsFromArray: [self hotFileSet]];
//NSLog(@"Added from array\n");
    if(initFile)
    {
	int loc;
	loc = -1;
	FORALL(searchFiles)
	{
		if(temp == initFile)
		{
			loc = __i;
			break;
		}
	}ENDFORALL;
	if(loc >= 0)
		[searchFiles removeObjectAtIndex: loc];
	
	//[searchFiles removeObject: initFile];
//NSLog(@"removed init file. %d left\n", [searchFiles count]);
    }
       MAKEDIRTY;


   [searchListView reloadData];
//NSLog(@"reloaded\n");
}

- (IBAction)doRefresh:(id)sender
{
}

- (IBAction)doRemove:(id)sender
{
	int n;
	if([searchFiles count] == 0) return;
   n = [searchListView selectedRow];
	//NSLog(@"Selected row = %d\n", n);
   if(n < 0 && [searchFiles count] > 0)
	[searchListView selectRow: 0 byExtendingSelection: NO];

    if(fileViewMode == RESULTMODE) 
    {
        NSWARNING(@"Can only modify search list from data file set.");
        return;
    }
    [searchFiles removeObject: [self searchFileName]];
    [searchListView reloadData];
       MAKEDIRTY;

}

- (IBAction)doRemoveAll:(id)sender
{
    if(fileViewMode == RESULTMODE) 
    {
        NSWARNING(@"Can only modify search list from a data file set.");
        return;
    }
    [searchFiles removeAllObjects];
    [searchListView reloadData];
       MAKEDIRTY;

}
- (IBAction) forceInitFile: (MWFile *) who
{
    if (who  == nil)
    {
	[initFileName setStringValue: @""];
	initFile = nil;
    }
    else
    {
	initFile = who;
	[initFileName setStringValue: [who name]];
	[searchFiles removeObject: who];
	[searchListView reloadData];
    }
       MAKEDIRTY;


}

- (IBAction) setInitFile: (id) sender
{
    MWFile *who;
    who = [self getMWFile];
    if (initFile == who)
    {
	[initFileName setStringValue: @""];
	initFile = nil;
    }
    else
    {
	initFile = who;
	[initFileName setStringValue: [who name]];
	[searchFiles removeObject: who];
	[searchListView reloadData];
    }
       MAKEDIRTY;


}

-(NSMutableString *) getDefinition: (NSString *) what
{
    NSMutableDictionary *myWord;
    
    myWord = [codeList objectForKey: what];
    if(myWord)
        return [myWord objectForKey: @"definition"];
    else
        return [NSMutableString string];
}

-(IBAction) generateCount: (id) Sender
{
    NSMutableArray *hc;
     NSMutableArray *sl;
   tableBrowser *mt;
    TAMSCharEngine *tce;
    sl = [[NSMutableArray alloc] init];
    hc = [NSMutableArray arrayWithArray: [self getHotCodeList]];
   // [gCentralCodeFile refreshCodeList: nil];
   // gCurrentDataSource = self;
     //is there anyone to search?
    if(initFile) [sl addObject: initFile];
    [sl addObjectsFromArray: searchFiles];
    if([sl count] == 0) return;
    tce = [[TAMSCharEngine alloc] initWithArrayAndStart: searchFiles] ;
    //make me the current data source
    mt = [[[tableBrowser alloc] init] autorelease];
#ifdef OLDNIBLOADER
    [mt setHotCodeList: hc];
    [mt setDataType: @"count"];
    [mt setCharEngine: tce];
    [NSBundle loadNibNamed: @"FreqCount" owner: mt];
    [mt windowControllerDidLoadNib: nil];

    [[mt window] makeKeyAndOrderFront: self];
#else
    [mt setHotCodeList: hc];
    [mt setDataType: @"count"];
    [mt setCharEngine: tce];
        [mt makeWindowControllers];
        [[NSDocumentController sharedDocumentController] addDocument:mt];
        [mt showWindows];
    //[mt windowControllerDidLoadNib: nil];
       //[doc updateChangeCount:NSChangeDone];	// mark as dirty
        //[document showWindows];
        [[mt window] makeKeyAndOrderFront: self];

#endif
    [sl release];
    
}
-(IBAction) generateCrossReference: (id) Sender
{
    NSMutableArray *hc;
    tableBrowser *mt;
    NSMutableArray *sl;
     TAMSCharEngine *tce;
    sl = [[NSMutableArray alloc] init];
      
   // gCurrentDataSource = self;
    hc = [NSMutableArray arrayWithArray: [self getHotCodeList]];
    //is there anyone to search?
    if(initFile) [sl addObject: initFile];
    [sl addObjectsFromArray: searchFiles];
    if([sl count] == 0) return;
    
    //make me the current data source
    tce = [[TAMSCharEngine alloc] initWithArrayAndStart: sl];

    [tce setGCurrentDataSource: self];
     mt = [[[tableBrowser alloc] init] autorelease];
     [mt setCharEngine: tce];
    [mt setHotCodeList: hc];
    [mt setDataType: @"xref"];
#ifdef OLDNIBLOADER
    [NSBundle loadNibNamed: @"FreqCount" owner: mt];
    [mt windowControllerDidLoadNib: nil];
#else
        [mt makeWindowControllers];
        [[NSDocumentController sharedDocumentController] addDocument:mt];
        [mt showWindows];
        //[mt windowControllerDidLoadNib: nil];

#endif
    [[mt window] makeKeyAndOrderFront: self];
    
}
-(IBAction) generateKappa: (id) Sender
{
    NSMutableArray *hc;
    MWKappa *mt;
    NSMutableArray *sl;
     TAMSCharEngine *tce;
    sl = [[NSMutableArray alloc] init];
      
   // gCurrentDataSource = self;
    hc = [NSMutableArray arrayWithArray: [self getHotCodeList]];
    //is there anyone to search?
    //if(initFile) [sl addObject: initFile];
    if([searchFiles count] != 2)
    {
        NSWARNING(@"To generate Kappa, the search list should consist of 2 \"identical\" files.");
        return;
    }
    [sl addObjectsFromArray: searchFiles];
    if([sl count] == 0) return;
    
    //make me the current data source
    tce = [[TAMSCharEngine alloc] initWithArrayAndStart: sl];

    [tce setGCurrentDataSource: self];
     mt = [[[MWKappa alloc] init] autorelease];
     [mt setCharEngine: tce];
    [mt setHotCodeList: hc];
    [mt setDataType: @"kappa"];
#ifdef OLDNIBLOADER
    [NSBundle loadNibNamed: @"kappa" owner: mt];
    [mt windowControllerDidLoadNib: nil];
#else
         [mt makeWindowControllers];
        [[NSDocumentController sharedDocumentController] addDocument:mt];
        [mt showWindows];
        //[mt windowControllerDidLoadNib: nil];
       //[doc updateChangeCount:NSChangeDone];	// mark as dirty
        //[document showWindows];


#endif
    [mt buildKappa];
    [[mt window] makeKeyAndOrderFront: self];
    
}

- (IBAction)doSearch:(id)sender
{
    myResults *aa;
    NSDocumentController *who;
    NSMutableArray *sl;
int st;
    NSMutableString *myLimStr = [[NSMutableString alloc] init];
     
    sl = [[NSMutableArray alloc] init];
    
    //set the flags
	st = [searchTypeMenu tagOfSelectedItem];
    if([rawButton state] == NSOnState) rawF = 1; else rawF = 0;
    if([exactButton state] == NSOnState) exactF = 1; else exactF = 0;
    if([emptyButton state] == NSOnState) emptyF = 1; else emptyF = 0;
    if(st == SECTIONSEARCHINDEX) sectionF = 1; else sectionF = 0;
    if(st == REGEXCHARINDEX) regexCharF = 1; else regexCharF = 0;
    if(st == NONREGEXCHARINDEX)
        nonRegexCharF = 1; else nonRegexCharF = 0;
    if(st == SIMPLEINDEX)
    {
	int i,ln;
	int sflg;
	unichar c;
	
	sflg = 1;
	[myLimStr setString: [searchStringView stringValue]];
	trimNSS(myLimStr);
	if([myLimStr isEqualToString: @""])
	    simpleF = sflg;
	else
	{
	    ln = [myLimStr length];
	    for(i = 0; i < ln; i++)
	    {
		c = [myLimStr characterAtIndex: i];
		//if(c == '*' || c == '+' || c == ',')
		if( c == '+')// || c == ',')
		{
		    sflg = 0;
		    break;
		}
	    }
	    simpleF = sflg;
	}
    }
    else if ([searchTypeMenu indexOfSelectedItem] == NONSIMPLEINDEX)
    {
	simpleF = 0;
	[myLimStr setString: [searchStringView stringValue]];
	trimNSS(myLimStr);
//if we get a nonsimple unlimited search this will have to go:
	//if([myLimStr isEqualToString: @""])
	//    simpleF = 1;
    }
  [myLimStr release];
    
    //is there anyone to search?
    if(initFile) [sl addObject: initFile];
    [sl addObjectsFromArray: searchFiles];
    if([searchFiles count] == 0) 
    {
	NSWARNING(@"Search list is empty");
	return;
    }
    
    //make me the current data source
 
    //find the controller
    who = [NSDocumentController sharedDocumentController];
    //make the window
    //[who setShouldCreateUI: YES];
    //ans = [[myResults alloc] init];
    //[who addDocument: ans];
#ifdef USESXML
    aa = [who openUntitledDocumentOfType: @"XML TAMS Result" display: YES];
#else
     aa = [who openUntitledDocumentOfType: @"TAMS Result" display: YES];
#endif
    [aa setGWorkBench: self];
    [aa  setCharEngineWithSource: self andFileList: sl];
    
    [self registerResult: aa];
    [aa executeTAMS];
    [aa retain];

}
- (BOOL) fileExists: (MWFile *) who
{
    FORALL(openFiles)
    {
        if(who  == temp) return YES;
    }
    ENDFORALL;
    return NO;
    
#ifdef TAVER1
    if([openFiles indexOfObject: who] == NSNotFound)
	return NO;
    else
	return YES;
#endif
}

- (IBAction)myAction:(id)sender
{
}

-(void) back
{
    [myWindow orderBack: self];
}
-(void) front
{
    [myWindow makeKeyAndOrderFront: self];
}
#ifdef TAVER1
- (IBAction)setCodeSource:(id)sender
{
   codeSource =  gCentralCodeFile =[self fileName];
   [codeSourceView setStringValue: [gCentralCodeFile getTitle]];
    [codeSourceBox setState: NSOnState];
//   [gCentralCodeFile remakeCodeList];
   FORALL(openFiles)
   {
	[temp updateCodeWindow];
    }
    ENDFORALL;
    
}
-(void) setCodeSourceWithName: (NSString *) name
{
    int i, cnt;
    FORALL(openFiles)
    {
	if([name isEqualToString: [temp fileName]] == YES)
	{
	    codeSource = gCentralCodeFile = temp;
	    [codeSourceView setStringValue: [gCentralCodeFile getTitle]];
	    [codeSourceBox setState: NSOnState];
	    cnt = [openFiles count];
	    for(i = 0; i < cnt; i++)
	    {
		[[openFiles objectAtIndex: i] updateCodeWindow];
	    }
	    return;
	}
    }
    ENDFORALL;
}
#endif

- (IBAction) setInitFileWithName: (NSString *) fname
{
    FORALL(openFiles)
    {
	if([fname isEqualToString: [temp fileName]] == YES)
	{
	    if(temp == initFile)
	    {
		[initFileName setStringValue: @""];
		initFile = nil;
		return;
	    }
	    initFile = temp;
	    [initFileName setStringValue: [temp getTitle]];
	    [searchFiles removeObject: temp];
	    [searchListView reloadData];
	    return;
	}
    }
    ENDFORALL;

}
/*
	    
- (MyDocument *) codeSource
{
    return codeSource;
}
*/
-(NSString *) theLimitString
{
    return [searchStringView stringValue];
}
-(void) displaySelData
{
    int row;
    NSMutableString *ss, *tt;

    ss = [[NSMutableString alloc] init];
    tt = [[NSMutableString alloc] init];
    [ss setString: [searchStringView stringValue]];
    row = [codeListView selectedRow];
    
    [tt setString: [[[self getHotCodeList] objectAtIndex: row] copy]];
    
    [ss appendString: tt];
    [searchStringView setStringValue: ss];
    [ss release];
    [tt release];
    
}

-(BOOL) isMyCode: (NSString *) ss
{
    NSDictionary *test;
    
    test = [codeList objectForKey: ss];
    if(test) return YES;
    else return NO;

}
-(NSArray *) allCodeList
{
    NSMutableArray *hc;
    hc = [NSMutableArray arrayWithArray: [codeList allKeys]];
    [hc sortUsingFunction: menuStringComp context: nil];
    return hc;
}

-(NSArray *) hotCodeList
{
    NSMutableArray *hc, *hc2;
    if(tempCodeSet) return tempCodeList;
    if([self codeListDirty] == NO) return theHotCodeList;
    if([codeSetCurrName isEqualToString: @""] == NO)
    {
        hc = [codeSets objectForKey: codeSetCurrName];
        [hc sortUsingFunction: menuStringComp context: nil];
        [theHotCodeList removeAllObjects];
        [theHotCodeList addObjectsFromArray: hc];
        [self setCodeListClean];
        return theHotCodeList;
    }
    hc2 = [codeList allKeys];
    hc = [NSMutableArray array];
    FORALL(hc2)
    {
        if([self isCodeActive: temp] == YES)
            [hc addObject: temp];
    }
    ENDFORALL;
    [hc sortUsingFunction: menuStringComp context: nil];
    [theHotCodeList removeAllObjects];
    [theHotCodeList addObjectsFromArray: hc];
    [self setCodeListClean];
    //[hc retain];
    return theHotCodeList;
}

/* kept for legacy functions*/
-(NSArray *) getHotCodeList
{

   return [self hotCodeList];

}


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


-(BOOL) windowShouldClose: (NSNotification *)aNotification
{
    int n, i;
    n = [openFiles count];
    for(i = 0; i < n; i++)
    {
        if([(MWFile *)[openFiles objectAtIndex: i] open] == YES)
        {
            NSWARNING(@"Close open source files before closing the project.");
            return NO;
        }
    }

    n = [resultFiles count];
    for(i = 0; i < n; i++)
    {
        if([(MWFile *)[resultFiles objectAtIndex: i] open] == YES)
        {
            NSWARNING(@"Close open result files before closing the project.");
            return NO;
        }
    }
    return YES;

}
- (void)windowWillClose:(NSNotification *)aNotification
{
    /* need to do some serious workhere with notifying the other windows */
    //gCentralCodeFile = nil;
    //gWorkBench = nil;
    FORALL(resultFiles)
    {
        if([(MWFile *)temp open]) [[temp filePointer] setGWorkBench: nil];
    }
    ENDFORALL;

}
- (void)windowDidUpdate:(NSNotification *)aNotification
{
    [self updateFileView];
    [codeListView reloadData];
    [searchListView reloadData];
    [codeListView setTarget: self];
    [codeListView setDoubleAction: @selector(displaySelData)];
    [fileListView setTarget: self];
    [fileListView setDoubleAction: @selector(shoveWindow)];
    //[[NSApplication sharedApplication] addWindowsItem: myWindow title: @"*Work Bench" filename: NO];

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

    who = [codeListView selectedRow];
    if(who >= 0)
    {
        theCode = [[self getHotCodeList] objectAtIndex: who];
    }
    else return;


    //ask for definition
    theDef = [self getDefinition: theCode];
    if(!theDef) {NSWARNING(@"Need to establish a central code file"); return;}
    //if it exists retain and display it
    [theDef retain];
    NSRunAlertPanel(theCode, theDef, @"Ok", nil, nil);
    //release it
    [theDef release];
}
-(void) dropMWFile: (MWFile *) who
{
    [openFiles removeObject: who];
    [allFiles removeObject: who];
    [searchFiles removeObject: who];
    [self removeFileFromSets: who];
    [self updateFileView];
    [searchListView reloadData];
    [fileListView reloadData];
    MAKEDIRTY;
}
-(NSString *) codersList
{
    return [coderIDView stringValue];
}

-(IBAction) doFileShuffleDown: (id) sender
{
    int n;

//    if([fList count] == 0) return;
    n = [fileListView selectedRow];
	if(n < 0) return;

    if(n< [fList count]-1)
    {
        //[fList exchangeObjectAtIndex:n withObjectAtIndex: n+1];
        if([fileSetCurrName isEqualToString: @""] == YES)
            [openFiles exchangeObjectAtIndex:n withObjectAtIndex: n+1];
//        else
            [[self hotFileSet] exchangeObjectAtIndex:n withObjectAtIndex: n+1];
        [fileListView selectRow: n+1 byExtendingSelection: NO];
        [self updateFileView];
        MAKEDIRTY;
    }


}


-(IBAction) doFileShuffleUp: (id) sender
{
    int n;

    if([fList count] == 0) return;
    n = [fileListView selectedRow];
    if(n > 0)
    {
        if([fileSetCurrName isEqualToString: @""] == YES)
            [openFiles   exchangeObjectAtIndex:n withObjectAtIndex: n-1];
//        else
        [[self hotFileSet]  exchangeObjectAtIndex:n withObjectAtIndex: n-1];
        //[fList exchangeObjectAtIndex:n withObjectAtIndex: n-1];
        [fileListView selectRow: n-1 byExtendingSelection: NO];
        [self updateFileView];
        MAKEDIRTY;
    }


}

-(IBAction) doSearchShuffleDown: (id) sender
{
    int n;

    n = [searchListView selectedRow];
    if(n< [searchFiles count])
    {
        [searchFiles exchangeObjectAtIndex:n withObjectAtIndex: n+1];
        [searchListView selectRow: n+1 byExtendingSelection: NO];
        [searchListView reloadData];
        MAKEDIRTY;
    }


}


-(IBAction) doSearchShuffleUp: (id) sender
{
    int n;

    n = [searchListView selectedRow];
    if(n > 0)
    {
        [searchFiles exchangeObjectAtIndex:n withObjectAtIndex: n-1];
        [searchListView selectRow: n-1 byExtendingSelection: NO];
        [searchListView reloadData];
        MAKEDIRTY;
    }


}


- (void) openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void  *)contextInfo
{
    NSArray *theFiles;
    int i, n;
    MWFile *mwf;
    
    if(returnCode)
    {
        theFiles = [sheet filenames];
        n = [theFiles count];
        for(i = 0; i < n; i++)
        {
            mwf =  [[MWFile alloc] initWithPath: [theFiles objectAtIndex: i]];
            if(fileViewMode == FILEMODE) {
                [openFiles addObject: mwf];
                [allFiles addObject: mwf];
                if([fileSetCurrName isEqualToString:@""] == NO)
                    if([fileSetCurrName isEqualToString: @"Results"] == NO)
                        [self addFileToCurrSet: mwf];
                [mwf setHasFile: YES];
            }
            else
            {
                [resultFiles addObject: mwf];
                [self addFile: mwf toSet: @"Results"];
                [mwf setHasFile: YES];
            
            }
        }
        if (n) {
            [self updateFileView];
            MAKEDIRTY;
            }
    }
    
}

-(MyDocument *) newFile
{
    MyDocument *newFile;
    NSDocumentController *dc;
    MWFile *who;
    
    dc = [NSDocumentController sharedDocumentController];
    newFile = [dc openUntitledDocumentOfType: @"Rich text file" display: YES];

    if(newFile)
    {
        who = [[MWFile alloc] init];
        [who setOpenFile: newFile];
        [who setHasFile: NO];
        if([fileSetCurrName isEqualToString:@""] == NO)
            if([fileSetCurrName isEqualToString: @"Results"] == NO)
                [self addFileToCurrSet: who];
        [openFiles addObject: who];
        [allFiles addObject: who];
        [newFile setMWFile: who];
        [newFile setGWorkBench: self];
        [newFile retain];
        [newFile moveForward];

        if([gPrefBoss scanInitValue]) [newFile scanForMetas];

        [newFile setReanalysisState: [self reanalysisMode]];
        [[NSNotificationCenter defaultCenter] addObserver: newFile
            selector: @selector(goReanalysisMode:)
            name: @"TAGoReanalysisMode"
            object: self];
        [self updateFileView];
        MAKEDIRTY;


        
    }

    return newFile;

}
-(IBAction) newFileToProj: (id) Sender
{
    [self newFile];
}

-(void) newFileWithText: (NSString *) what
{
    MyDocument *who;
    
    who = [self newFile];
    [who appendString: what];
}
-(IBAction) newTextFileToProj: (id) Sender
{
    MyDocument *newFile;
    NSDocumentController *dc;
    MWFile *who;
    if(fileViewMode == RESULTMODE)
    {
        NSWARNING(@"Can only add files from data file set.");
        return;
    }
    dc = [NSDocumentController sharedDocumentController];
    newFile = [dc openUntitledDocumentOfType: @"Text" display: YES];
    if(newFile)
    {
        who = [[MWFile alloc] init];
        [who setOpenFile: newFile];
        [openFiles addObject: who];
        [allFiles addObject: who];
        [newFile setMWFile: who];
        [newFile setGWorkBench: self];
        [who setHasFile: NO];
        [newFile retain];
        [newFile moveForward];
        [self updateFileView];
        MAKEDIRTY;
        
    }
}
-(IBAction) addFileToProj: (id) Sender
{
    NSOpenPanel *myOP;

 /*   NSString *ss;
    ss = abs2rel(@"/a/b/c/d/e", @"/a/b/c/d/e/foo.txt");
*/
    NSMutableArray *mytype;

    if(fileViewMode == FILEMODE)
        mytype = [NSMutableArray arrayWithObjects: @"txt", @"rtf", @"rtfd", @"RTFD", @"RTF", @"TXT", nil];
    else
        mytype = [NSMutableArray arrayWithObjects: @"xtrs", @"trs",@"TRS", nil];

    //[mytype removeLastObject];
    myOP = [NSOpenPanel openPanel];
	NSLog(@"Types = %@\n",mytype);
    [myOP setAllowsMultipleSelection: YES];

    [myOP beginSheetForDirectory: nil file: nil types: mytype
        modalForWindow: myWindow modalDelegate:self 	didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:) 
        contextInfo: nil];
        
/*
    result = [[NSOpenPanel openPanel] runModalForDirectory: NSHomeDirectory()
                    file:nil types: mytype];//[NSArray arrayWithObjects: @"txt", @"rtf", @"RTF", @"TXT", nil]];
*/
}
-(IBAction) niceClose: (id) Sender
{
    if([self windowShouldClose: nil])
        [myWindow performClose: self];
}
-(IBAction) closeAllFiles: (id) Sender
{
    if(fileViewMode == RESULTMODE)
    {
        FORALL(resultFiles)
        {
            if([(MWFile *)temp open] == NO) continue;
            [[temp filePointer] niceClose: self];
        }
        ENDFORALL;
    
    }
    else
    {
        FORALL(openFiles)
        {
            if([(MWFile *)temp open] == NO) continue;
            [[temp filePointer] niceClose: self];
        }
        ENDFORALL;
    
    }

}
-(IBAction) closeProjFile: (id) Sender
{
    int n;
    MWFile *who;

    n = [fileListView selectedRow];
    if(n >= 0)
    {
        who = [openFiles objectAtIndex: n];
        if([who open])
        {
            [self shoveWindow];
            [[who filePointer] performClose];
        }
    }
        
}
-(void) expungeFileFromSearchList: (MWFile *) who
{
    NSArray *fs;
    NSMutableArray *cfs;
    
    fs = [namedSearchList allKeys];
    
    FORALL(fs)
    {
        cfs = [[namedSearchList objectForKey: temp] objectForKey: @"searchList"];
        [cfs removeObject: who];
    }
    ENDFORALL;
    //[openFiles removeObject: who];
}
-(void) expungeFileFromProj: (MWFile *) who
{
    NSArray *fs;
    NSMutableArray *cfs;
    
    fs = [self allFileSetNames];
    
    FORALL(fs)
    {
        cfs = [fileSets objectForKey: temp];
        [cfs removeObject: who];
    }
    ENDFORALL;
    [openFiles removeObject: who];
}
-(IBAction) removeFileFromProj: (id) Sender
{
    MWFile *who;
    int n;
    n = [fileListView selectedRow];
    who = [fList objectAtIndex: n];
    if([who open] == YES)
        {NSWARNING(@"Cannot remove open files.");}
    else
    {
        [fList removeObject: who];
        if([fileSetCurrName isEqualToString: @""])
        {
             [self expungeFileFromProj: who];
            [self expungeFileFromSearchList: who];
             [searchFiles removeObject: who];
      }
        [self updateFileView];
        [searchListView reloadData];
        MAKEDIRTY;
    }
        
}
-(IBAction) importCodesAndDefs: (id) Sender
{
    MWFile *who;
    int n;
           ctQChar *q;
      NSMutableString *ss;
      int inZoneFlag;
      NSRange rrr;
      who = [self getMWFile];
      
     TAMSCharEngine *tce = [[TAMSCharEngine alloc] initWithFileAndStart: who];
     BOOL active;
      
    n = [fileListView selectedRow];
    who = [openFiles objectAtIndex: n];

   q = [[ctQChar alloc] init];
    
    //gCurrentDataSource = gCentralCodeFile;
    //clearSearchList();
    //addFileToSearchList(gCentralCodeFile);
    //startSearch();
    inZoneFlag = 0;
    ss = [[NSMutableString alloc] init];
    while([tce scanNext: q] != ENDOFFILE)
    {
        if([q tokentype] == TOKEN)
            inZoneFlag = 1;
	if([q tokentype] == CHAR && inZoneFlag)
	{
	    [ss appendString: [q buff]];
	}
	if([q tokentype] == ENDTOKEN)
	{
	    
            //is it retired
                rrr =[[q extra] rangeOfString: @"retired" options: NSCaseInsensitiveSearch];
                if(rrr.location != NSNotFound) active = NO;
                else active = YES;
            //send the definition
            [self addCode: [q buff] definition: [ss copy] active: active append: YES];
            //zap the string
            [ss setString: @""];
            inZoneFlag = 0;
	}
    }
    [ss autorelease];
    [tce release];
    [self broadcastCodeChange: NO];
    MAKEDIRTY;
}

-(IBAction) importCodes: (id) Sender
{
    MWFile *who;
    int n;
           ctQChar *q;
      NSRange rrr;
      BOOL active;
      who = [self getMWFile];
    TAMSCharEngine *tce = [[TAMSCharEngine alloc] initWithFileAndStart: who];
    
    n = [fileListView selectedRow];
    who = [openFiles objectAtIndex: n];

     q = [[ctQChar alloc] init];
    
    //gCurrentDataSource = gCentralCodeFile;
    //clearSearchList();
    //addFileToSearchList(gCentralCodeFile);
    //startSearch();
    while([tce scanNext: q] != ENDOFFILE)
    {
	if([q tokentype] == ENDTOKEN)
	{
	    
            //is it retired
                rrr =[[q extra] rangeOfString: @"retired" options: NSCaseInsensitiveSearch];
                if(rrr.location != NSNotFound) active = NO;
                else active = YES;
            //send the definition
            [self addCode: [q buff] definition: @"" active: active append: YES];
            //zap the string
	}
    }
    [tce release];
    [self broadcastCodeChange: NO];
    MAKEDIRTY;
}

-(IBAction) exportCodesAndDefs: (id) Sender
{

    NSMutableString *ss;
    NSMutableArray *cl;
    MyDocument *md;
    
    ss = [NSMutableString string];
    cl = [self allCodeList];
    [cl retain];
    FORALL(cl)
    {
        [ss appendString: @"{"];
        [ss appendString: temp];
        [ss appendString: @"}"];
        [ss appendString: [self getDefinition: temp]];
        [ss appendString: @"{/"];
        [ss appendString: temp];
        if([self isCodeActive: temp] == NO)
        {
            [ss appendString: @": retired"];
        }
        [ss appendString: @"}"];
        [ss ADDCHAR('\n')];
    }
    ENDFORALL;
    //make an untitled document
    md = [self newFile];
    //set the string to it
    if(md)
    {
        //[ss retain];
        [md appendString: ss];
    }
    
}

-(IBAction) emptyCodeBook: (id) Sender
{
    if(NSYESNOQUESTION(@"This will erase all of your codes. Procede?") == NO) return;
    [codeList removeAllObjects];
    [self broadcastCodeChange: YES];
    MAKEDIRTY;
}
-(IBAction) showCodeBrowser: (id) Sender
{
    MAKEDIRTY;
    [[NSApp delegate] doCodeDictionary: codeList from: self];
}

/* basic files for saving v. 1 projects */
-(void) writeFileWithInit: (NSString *) myInit andFiles: (NSArray *) s1 andSearch: (NSArray *) s2
    andDict: (NSDictionary *) d1 withName: (NSString *) myName
{
    NSMutableString *myPath;
    NSMutableArray *myDataArray;
    NSArray *a1, *a2;
    NSDictionary *d3;
    NSString *w;
    //deal with nulls
    a1 = a2 = nil;
    if(!s1) 
    {
        a1 = [[NSArray alloc] init];
    }
    else a1 = s1;
    if(!s2) 
    {
        a2 = [[NSArray alloc] init];
    }
    else a1 = s2;
    if(!d1) 
    {
        d3 = [[NSDictionary alloc] init];
    }
    else d3 = d1;
    myPath = [NSString stringWithFormat: @"%@/Desktop/%@.tprj",NSHomeDirectory(), myName];//~/Desktop/%@.tprj", myName ];
//    myPath = [NSString stringWithFormat: @"~/%@.tprj", myName ];
    myDataArray = [[NSMutableArray alloc] init];
    [myDataArray addObject: @"2.0a"];
    //add to it the search file list
    [myDataArray addObject: a1];
    [myDataArray addObject: a2];
    //add to it the init file
    if (myInit) [myDataArray addObject: myInit];
    else
        [myDataArray addObject: @""];
        
    //add to it the code dictionary
    [myDataArray addObject: d3];
    //serialize it
    if([[NSFileManager defaultManager] createFileAtPath: myPath 
        contents: [NSArchiver archivedDataWithRootObject: myDataArray] attributes: nil])
    {

        w = [NSString stringWithFormat: @"Writing file %@ to desktop directory", myName];
        NSWARNING(w);
    }
    else
    {
        w = [NSString stringWithFormat: @"Problems writing file %@ to desktop directory", myName];
        NSWARNING(w);
     }   
}
-(IBAction) exportVersionOneProjects: (id) Sender
{
    NSArray *theState, *theSet;
    NSMutableDictionary *allSets;
    NSArray  *theMenuItems;
    NSString *currItem;
    int n, i;
    
    theState = [gPrefBoss savedState];
    if([[theState objectAtIndex: 0] isEqualToString: @"1"] == YES)
    {
        NSWARNING(@"Can't convert this version's file information.");
	return;
    }
    theMenuItems = [[theState objectAtIndex: 1] allKeys];
    if(!(n = [theMenuItems count])) return;
    for(i = 0; i < n; i++)
    {
        currItem = [theMenuItems objectAtIndex: i];

        if ([[theState objectAtIndex: 0] isEqualToString: @"2"] == YES)
	{
	    allSets = [theState objectAtIndex: 1];
	    theSet = [allSets objectForKey: currItem];
            [self writeFileWithInit: [theSet objectAtIndex: 1] andFiles: [theSet objectAtIndex: 2]
                andSearch: nil andDict: nil withName: currItem];
	}    
    
    }

}
-(void) localizePathForArray: (NSArray *) myArray
{
        NSString *pPath, *tPath;
    // Insert code here to write your document from the given data.  You can also choose to override -fileWrapperRepresentationOfType: or -writeToFile:ofType: instead.
    //construct my path
    
    tPath = [self fileName];
    pPath = [savingFileName stringByDeletingLastPathComponent];
    FORALL(myArray)
    {
        [(MWFile *)temp setPath: rel2abs(pPath, [(MWFile *)temp name])];
        [(MWFile *)temp setHasFile: YES];
    }
    ENDFORALL;

}


- (void) projPrefDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void  *)contextInfo
{
    
    if(returnCode)
    {
        BOOL oldPM;
        oldPM = absPathMode;
        absPathMode = [absPathSwitch indexOfSelectedItem];
        [self updateFileView];
        if(oldPM != absPathMode)
        {
            MAKEDIRTY;
        }
        else if (absPathMode == LOCPATHMODE)
        {
            [self localizePathForArray: openFiles];
            [self localizePathForArray: resultFiles];
        }
    }
    
}

-(IBAction) cancelPrefPanel: (id) Sender
{
    [projPrefPanel orderOut: Sender];
    [NSApp endSheet: projPrefPanel returnCode: 0];

}

-(IBAction) okPrefPanel: (id) Sender
{
    [projPrefPanel orderOut: Sender];
    [NSApp endSheet: projPrefPanel returnCode: 1];

}
-(IBAction) doProjPrefPanel: (id) Sender
{
    if(absPathMode != ABSPATHMODE && [self fileName] == nil)
    {
        NSWARNING(@"Must save file using absolute paths before you can change project to relative paths")
        return;
    }
     [absPathSwitch selectItemAtIndex: absPathMode];
    
     [NSApp beginSheet: projPrefPanel
	modalForWindow: myWindow
	modalDelegate: self
	didEndSelector: @selector(projPrefDidEnd:returnCode:contextInfo:)
	contextInfo: nil];

}
-(IBAction) goFileMode: (id) sender
{
    [resultModeButton setState: NSOffState];
    fList = openFiles;
    fileViewMode = FILEMODE;
    [self updateFileView];
}

-(IBAction) goResultMode: (id) sender
{
    [fileModeButton setState: NSOffState];
    fList = resultFiles;
    fileViewMode = RESULTMODE;
    [self updateFileView];
}

-(void) updateFileView
{

    [fileCountView setStringValue: [NSString stringWithFormat: @"%d",[self hotFileCount]]];
    [fileListView reloadData];
    switch(absPathMode) {
        case ABSPATHMODE: [pathModeView setStringValue: @"A"]; break;

        case RELPATHMODE: [pathModeView setStringValue: @"R"]; break;
        
        case LOCPATHMODE: [pathModeView setStringValue: @"F"]; break;
    };
}

-(int) absPath {return absPathMode;}
-(IBAction) removeAllFiles: (id) sender
{
    if(fileViewMode == RESULTMODE)
    {
        FORALL(resultFiles)
        {
            if([(MWFile *)temp open])
            {
                [[temp filePointer] setGWorkBench: nil];
            
            }
        }
        ENDFORALL;
        [resultFiles removeAllObjects];
        MAKEDIRTY;
        [self updateFileView];
    }
    else
        NSWARNING(@"At present this only works in \"Reports\" mode");


}
-(IBAction) checkForPairs: (id) sender
{
    NSMutableArray *codeHolder;
    NSTextView *theDoc;
    MWFile *theMWFile;
    ctQChar *q;
    ctTagInfo *ti;
    int myloc;
    //TAMSCharEngine *tc = [[TAMSCharEngine alloc] initWithFileAndStart: [self getMyMWFile]];
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];//initWithFileAndStart: [self getMyMWFile]];
    [tc addArrayToSearchList: openFiles];
    [tc startSearch];
    q = [[ctQChar alloc] init];
    [q retain];
    
    codeHolder = [[NSMutableArray alloc] init];
    myloc = [tc getCharLocation];
    while([tc scanNext: q] != ENDOFALLFILES)
    {
    //until eof
    //if it's a tag

	if([q tokentype] == TOKEN)
	{
	    [codeHolder addObject: [[[ctTagInfo alloc] initWithName: [q buff] location: [q where] coder: [q coder] doc: [tc hotSearchDocument]] autorelease]];
	}
	else if([q tokentype] == ENDTOKEN)
	{
	    FORALL(codeHolder)
	    {
		ti = nil;
		if([[(ctTagInfo *)temp name] isEqualToString: [q buff]] == YES 
                    && [[temp coder] isEqualToString: [q coder]] == YES 
                    && [temp document] == [tc hotSearchDocument])
		{
		    ti = temp;
		    break;
		}
	    }ENDFORALL;
	    if(ti)
		[codeHolder removeObject: ti];
	    else
	    {
                theMWFile = [tc hotSearchDocument];
                [self openMWFile: theMWFile type:SOURCETYPE ];
                theDoc = [[theMWFile filePointer] myTextView];
		[theDoc setSelectedRange: NSMakeRange(myloc, [tc getCharLocation] - myloc)];
		
		//scroll range
		[theDoc scrollRangeToVisible: NSMakeRange(myloc, [tc getCharLocation] - myloc)];
		[q release];
		[codeHolder release];
		[tc release];
		return;
	    
	    }
	}
	myloc = [tc getCharLocation];
    }
    if([codeHolder count])
    {
	    //select range
	ti = [codeHolder objectAtIndex: 0];
                theMWFile = [ti document];
                [self openMWFile: theMWFile type:SOURCETYPE ];
                theDoc = [[theMWFile filePointer] myTextView];
	[theDoc setSelectedRange: NSMakeRange([ti location]+1, [[ti name] length])];
	
	//scroll range
	[theDoc scrollRangeToVisible: NSMakeRange([ti location]+1, [[ti name] length])];
  
    }
    else
    {
        NSMESSAGE(@"All code pairs matched");
    }
    [q release];
    [codeHolder release];
    [tc release];
		

}
-(IBAction) checkForNested: (id) sender
{
    NSMutableArray *codeHolder;
    NSTextView *theDoc;
    MWFile *theMWFile;
    ctQChar *q;
    int errFlg;
    ctTagInfo *ti;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];//initWithFileAndStart: [self getMyMWFile]];
    [tc addArrayToSearchList: openFiles];
    [tc startSearch];
  
    errFlg = 0;
    q = [[ctQChar alloc] init];
    [q retain];
    
     codeHolder = [[NSMutableArray alloc] init];

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

	if([q tokentype] == TOKEN)
	{
	    if([codeHolder count])
	    {
		FORALL(codeHolder)
		{
		    if([[(ctTagInfo *)temp name] isEqualToString: [q buff]] == YES &&
                    [temp document] == [tc hotSearchDocument])
		    {
                        theMWFile = [temp document];
                    [self openMWFile: theMWFile type:SOURCETYPE ];
                        theDoc = [[theMWFile filePointer] myTextView];
			[theDoc setSelectedRange: NSMakeRange([q where]+1, [[q buff] length])];
			[theDoc scrollRangeToVisible: NSMakeRange([q where]+1, [[q buff] length])];
			[q release];
			[codeHolder release];
			return;
		    }
		}ENDFORALL;
		[codeHolder addObject: [[[ctTagInfo alloc]  initWithName: [q buff] location: [q where] coder: [q coder] doc: [tc hotSearchDocument]]autorelease]];
	    }
	    else
		[codeHolder addObject: [[[ctTagInfo alloc]  initWithName: [q buff] location: [q where] coder: [q coder] doc: [tc hotSearchDocument]]autorelease]];
	}
	else if([q tokentype] == ENDTOKEN)
	{
	    FORALL(codeHolder)
	    {
		ti = nil;
		if([(NSString *)[(ctTagInfo *)temp name] isEqualToString: [q buff]] == YES 
			&& [[temp coder] isEqualToString: [q coder]] == YES)
		{
		    ti = temp;
		    break;
		}
	    }ENDFORALL;
	    if(ti)
		[codeHolder removeObject: ti];
	}

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

}
-(IBAction) removeNSL: (id) sender
{
    NSMutableString *who;

    if([searchListMenu numberOfItems] <= 0) return;
    who = [[NSMutableString alloc] init];
    [who setString: [[searchListMenu selectedItem] title]];
    [searchListMenu removeItemWithTitle: who];
    [namedSearchList removeObjectForKey: who];
    [who release];
    MAKEDIRTY;
}
-(IBAction) removeAllNSL: (id) sender
{
    [searchListMenu removeAllItems];
    [namedSearchList removeAllObjects];
    MAKEDIRTY;
}
-(IBAction) loadSL: (id) sender
{
    NSMutableDictionary *mystuff;
    
    mystuff = [namedSearchList objectForKey: [[searchListMenu selectedItem] title]];
    //set the init
    if([mystuff objectForKey: @"init"] != nil)
        [self forceInitFile: [mystuff objectForKey: @"init"]];
    else
        [self forceInitFile: nil];
    [searchFiles removeAllObjects];
    [searchFiles addObjectsFromArray: 
        [mystuff objectForKey: @"searchList"]];
        MAKEDIRTY;
}
-(void) namedSLDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    NSMutableArray *mm;
    NSMutableDictionary *md;
    NSMenuItem *myItem;
    
    if(returnCode)
    {
            if([namedSearchList objectForKey: [searchListNameField stringValue]] != nil)
            {
                NSWARNING(@"Name already exists; use unique name");
                return;
            }
            mm = [[NSMutableArray alloc] init];
            md = [[NSMutableDictionary alloc] init];
            [mm autorelease];
            [md autorelease];
            if([self getInitFile])
                [md setObject: [self getInitFile] forKey: @"init"];
            [mm addObjectsFromArray: searchFiles];
            [md setObject: mm forKey: @"searchList"];
            [namedSearchList setObject: md forKey: [searchListNameField stringValue]];
            [searchListMenu addItemWithTitle: [searchListNameField stringValue]];
            myItem = [searchListMenu lastItem];
            [myItem setTarget: self];
            [myItem setAction: @selector(loadSL:)];
            [searchListMenu selectItem: myItem];
            MAKEDIRTY;
    }

}

-(IBAction) cancelNamedSL: (id) Sender
{
    [searchListSheet orderOut: Sender];
    [NSApp endSheet: searchListSheet returnCode: 0];

}

-(IBAction) okNamedSL: (id) Sender
{
    [searchListSheet orderOut: Sender];
    [NSApp endSheet: searchListSheet returnCode: 1];

}
-(IBAction) addNamedSL: (id) Sender
{
    NSWindow *who;
    [searchListNameField setStringValue: @""];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
     [NSApp beginSheet: searchListSheet
	modalForWindow: myWindow
	modalDelegate: self
	didEndSelector: @selector(namedSLDidEnd:returnCode:contextInfo:)
	contextInfo: nil];

}
-(NSColor *) colorForCode: (NSString *) myCode
{
    NSMutableString *currentCode;
    NSArray *codeArray, *tarray;
    NSMutableDictionary *who;
    int n, i, j;
    int colorCode;
    NSRange r;
    NSNumber *nsColorNumber;
    if(myCode == nil) return [gPrefBoss realColor];
    if([myCode isEqualToString: @""]) return [gPrefBoss realColor];
    codeArray = [myCode componentsSeparatedByString: @">"];
    n = [codeArray count];
    currentCode = [NSMutableString string];
    r.location = 0;
    for (i = n - 1; i >= 0; i--)
    {
        //put together the string up to this point
        [currentCode setString: @""];
        r.length = i + 1;
        tarray = [codeArray subarrayWithRange: r];
        [currentCode setString: [tarray componentsJoinedByString: @">"]];
        who = [codeList objectForKey: currentCode];
        if(who == nil)
        { 
            if (i == 0)//do the gprefboss thing
            break;
            else continue;
        }
        nsColorNumber = [who objectForKey: @"color"];
        if(nsColorNumber == nil) 
        {
            if(i == 0)break;
            else continue;
        }
        colorCode = [nsColorNumber intValue];
        if(colorCode == otherColor)
        {
            NSColor *ccc = [who objectForKey: @"realColor"];
            if(ccc != nil) return ccc;
            else continue;
        }
        if(colorCode == inheritedColor) continue;
        else
        {
            return getColorForInt(colorCode);
        }
        
    }
        
    return [gPrefBoss realColor];//getColorForInt([gPrefBoss tagColorValue]);

}
-(void) namedSrchDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    NSMutableArray *mm;
    NSMutableDictionary *md;
    NSMenuItem *myItem;
    
    if(returnCode)
    {
            if([namedSrch objectForKey: [searchNameSheetField stringValue]] != nil)
            {
                NSWARNING(@"Name already exists; use unique name");
                return;
            }
            mm = [[NSMutableArray alloc] init];
            md = [[NSMutableDictionary alloc] init];
            [mm autorelease];
            [md autorelease];
            //[mm addObject: [[[searchStringView stringValue] copy] autorelease]];
            //[mm addObject: [[[coderIDView stringValue] copy] autorelease]];
            [md setObject: [NSNumber numberWithInt: 1] forKey: @"version"];
            [md setObject: [[[searchStringView stringValue] copy] autorelease] forKey: @"limit"];
            [md setObject: [[[coderIDView stringValue] copy] autorelease] forKey: @"coder"];
            [md setObject: [NSNumber numberWithInt: [rawButton intValue]] forKey: @"raw"];
            [md setObject: [NSNumber numberWithInt: [emptyButton intValue]] forKey: @"empty"];
            [md setObject: [NSNumber numberWithInt: [exactButton intValue]] forKey: @"exact"];
            [md setObject: [NSNumber numberWithInt: [searchTypeMenu indexOfSelectedItem]] 
                forKey: @"searchType"];
            [namedSrch setObject: md forKey: [searchNameSheetField stringValue]];
            
            
            [searchNameMenu addItemWithTitle: [searchNameSheetField stringValue]];
            myItem = [searchNameMenu lastItem];
            [myItem setTarget: self];
            [myItem setAction: @selector(doNamedSrch:)];
            [searchNameMenu selectItem: myItem];
            MAKEDIRTY;
    }

}

-(IBAction) cancelNamedSrch: (id) Sender
{
    [searchNameSheet orderOut: Sender];
    [NSApp endSheet: searchNameSheet returnCode: 0];

}

-(IBAction) okNamedSrch: (id) Sender
{
    [searchNameSheet orderOut: Sender];
    [NSApp endSheet: searchNameSheet returnCode: 1];

}
-(IBAction) addNamedSrch: (id) Sender
{
    NSWindow *who;
    [searchNameSheetField setStringValue: @""];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
     [NSApp beginSheet: searchNameSheet
	modalForWindow: myWindow
	modalDelegate: self
	didEndSelector: @selector(namedSrchDidEnd:returnCode:contextInfo:)
	contextInfo: nil];

}

-(IBAction) delNamedSrch: (id) Sender
{
    NSMutableString *who;

    if([searchNameMenu numberOfItems] <= 0) return;
    if(NSYESNOQUESTION(@"This will delete the selected \"named search.\" Continue?") == NO) return;
    who = [[NSMutableString alloc] init];
    [who setString: [[searchNameMenu selectedItem] title]];
    [searchNameMenu removeItemWithTitle: who];
    [namedSrch removeObjectForKey: who];
    [who release];
    MAKEDIRTY;


}
-(IBAction) delAllNamedSearch: (id) Sender
{
    if(NSYESNOQUESTION(@"This will delete all \"named searches.\" Continue?") == NO) return;
    [searchNameMenu removeAllItems];
    [namedSrch removeAllObjects];
    MAKEDIRTY;

}
-(IBAction) doNamedSrch: (id) Sender
{
    NSDictionary *who;
    int n;
    if([searchNameMenu numberOfItems] <= 0) return;
    
    who = [namedSrch objectForKey: [[searchNameMenu selectedItem] title]];
    if(who == nil) return;
    if([[who objectForKey: @"version"] intValue] >= 1)
    {
        int st;
        st = [[who objectForKey: @"searchType"] intValue];
        [self setupSearchMode: st];
        [searchStringView setStringValue: [who objectForKey: @"limit"]];
        [coderIDView setStringValue: [who objectForKey: @"coder"]];
        [rawButton setIntValue: [[who objectForKey: @"raw"] intValue]];
        [emptyButton setIntValue: [[who objectForKey: @"empty"] intValue]];
        [exactButton setIntValue: [[who objectForKey: @"exact"] intValue]];
        n = [[who objectForKey: @"searchType"] intValue];
        [searchTypeMenu selectItemAtIndex: st];
    
    
    }
    
    //if([who count] != 2) return;
    //[searchStringView setStringValue: [who objectAtIndex: 0]];
    //[coderIDView setStringValue: [who objectAtIndex: 1]];
    
}

-(void) addAutoSet: (NSMutableDictionary *) what withName: (NSString *) who
{
    [autoSetDict setObject: what forKey: who];
    MAKEDIRTY;
}
-(NSMutableDictionary *) autoSetForName: (NSString *) who
{
    return [autoSetDict objectForKey: who];
}
-(void) removeAutoSetForName: (NSString *) who
{
    [autoSetDict removeObjectForKey: who];
    MAKEDIRTY;
}
-(NSArray *) allAutoSetNames
{
    return [autoSetDict allKeys];
}
-(IBAction) removeAllAutoSets: (id) sender
{
    if(NSYESNOQUESTION(@"This will delete all project wide auto sets. Procede?") == YES)
        [autoSetDict removeAllObjects];
    [self rebuildAutoSetMenu];
}
-(BOOL) reanalysisMode{return reanalysisMode;}
-(void) setReanalysisMode: (BOOL) value {reanalysisMode = value;}
    
-(IBAction) doToggleReanalysisMode: (id) sender
{
    NSMutableDictionary *aa = [NSMutableDictionary dictionary];
    
    if(reanalysisMode == YES)
    {
        [aa setObject: @"OFF" forKey: @"state"];
        reanalysisMode = NO;
        [sender setState: NSOffState];
        [[NSNotificationCenter defaultCenter] postNotificationName: @"TAGoReanalysisMode"
            object: self
            userInfo: aa];
    }
    else
    {
        [aa setObject: @"ON" forKey: @"state"];
        reanalysisMode = YES;
        [sender setState: NSOnState];
        [[NSNotificationCenter defaultCenter] postNotificationName: @"TAGoReanalysisMode"
            object: self
            userInfo: aa];
    }
        
}
-(void) dummy:(id) sender{}
-(void) rebuildAutoSetMenu
{
    int i, n, m;
    NSMenu *asmn;
    NSMutableArray  *w2;
    
    asmn = [[[NSApp delegate] autoSetMenu] submenu];
    m = [asmn numberOfItems];
    
    if(m > AUTOSETBASE)
        for(i = AUTOSETBASE; i < m; i++)
        {
            [asmn removeItemAtIndex: AUTOSETBASE];
        }

    w2 = [NSMutableArray arrayWithArray: [self allAutoSetNames]];
    
    [w2 sortUsingFunction: menuStringComp  context: nil];

    n = [w2 count];
    
    if(n > 0)
    {
        for(i=0; i< n; i++)
        {
            [asmn addItemWithTitle: [w2 objectAtIndex: i]
                action: @selector(dummy:)
                keyEquivalent: @""];
        }
    }
        
}


- (void) windowDidBecomeKey:(NSNotification *)aNotification
{
    //[self renewNamedSelMenu];
    [self rebuildAutoSetMenu];
    {
        if([self reanalysisMode] == YES)
        {
            [[[NSApp delegate] reanalysisMenu] setState: NSOnState];
        }
        else
        {
            [[[NSApp delegate] reanalysisMenu] setState: NSOffState];
        }
    }
    [self rebuildCodeSetMenu];
    [self rebuildFileSetMenu];
    [self rebuildSummReportMenu];
    [self updateCodeCount];

}
- (void)updateCodeCount
{
    /*
    if ([codeSetCurrName isEqualToString:@""] == YES)
        [codeCountView setIntValue: [[self allCodeList] count]];
    else
        [codeCountView setIntValue: [codeSets objectForKey: codeSetCurrName]];
    */
    [codeCountView setIntValue: [[self hotCodeList] count]];
    [searchCountView setIntValue: [[self searchList] count]];

}
- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
    if(aTableView == codeSetTable)
        return [[self allCodeList] count];
    if(aTableView == fileSetTable)
        return [[self allFileList] count];
    if(aTableView == fileListView)
    {


	if(allFiles != nil)
	 return [[self getHotFileList] count];
	else return 0;
    }

}  

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    if(aTableView == codeSetTable)
        return [[self allCodeList] objectAtIndex: rowIndex];
    if(aTableView == fileSetTable)
        return [[[self allFileList] objectAtIndex: rowIndex] name];
    if(aTableView == fileListView)
    {
	
   	return [[[self getHotFileList] objectAtIndex: rowIndex] name];
    }
}
- (BOOL)tableView:(NSTableView *)aTableView shouldEditTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    if(aTableView == fileListView)
    	return NO;
}
- (void) codeSetDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void  *)contextInfo
{
    [self rebuildCodeSetMenu];
    MAKEDIRTY;
}

-(IBAction) codeSetSelAll:(id) sender
{
    [codeSetTable selectAll: nil];
}
-(IBAction) codeSetSelNone:(id) sender
{
    [codeSetTable deselectAll: nil];
}
-(void) rebuildCodeSetPopMenu
{
    [codeSetPopMenu removeAllItems];
    FORALL([self allCodeSetNames])
    {
    
        [[codeSetPopMenu menu] addItemWithTitle: temp
            action: @selector(showCodeSet:) keyEquivalent: @""];
    
    }
    ENDFORALL;
}
-(IBAction) codeSetDelAll: (id) sender
{
    if(NSYESNOQUESTION(@"Delete all code sets?") == YES)
    {
        [codeSetCurrName setString: @""];
        [self rebuildCodeSetMenu];
        [self broadcastCodeChange: NO];
        [codeSets removeAllObjects];
        [self rebuildCodeSetPopMenu];
    }
}

-(IBAction) codeSetDel: (id) sender
{
    if(NSYESNOQUESTION(@"Delete selected code set?") == YES)
    {
        if([codeSetCurrName isEqualToString: [[codeSetPopMenu selectedItem] title]] == YES)
        {
            [codeSetCurrName setString: @""];
            [self rebuildCodeSetMenu];
            [self broadcastCodeChange: NO];
        }
        
        [codeSets removeObjectForKey: [[codeSetPopMenu selectedItem] title]];
        [self rebuildCodeSetPopMenu];
    }
}

-(void) loadAllCodes: (id) sender
{
    
    if(tempCodeSet == YES)
    {
        [tempCodeList removeAllObjects];
    }
    [codeSetCurrName setString: @""];
    tempCodeSet = NO;
    [self rebuildCodeSetMenu];
    [self broadcastCodeChange: NO];
    MAKEDIRTY;
}
-(void) loadCodeSet: (id) sender
{
    if(tempCodeSet == YES)
    {
        [tempCodeList removeAllObjects];
    }
    [codeSetCurrName setString: [sender title]];
    tempCodeSet = NO;
    [self rebuildCodeSetMenu];
    [self broadcastCodeChange: NO];
    MAKEDIRTY;

}

-(void) loadCurrCodeSet
{
    [self rebuildCodeSetMenu];
    [self broadcastCodeChange: NO];
}
-(IBAction) showCodeSet: (id) sender
{
     int i, j, m, n;
   NSArray *hc = [self allCodeList];
    NSArray *tc;
    NSString *who;
    if([codeSetPopMenu selectedItem] == nil )return;
    [self codeSetSelNone: nil];
    tc = [codeSets objectForKey: [[codeSetPopMenu selectedItem] title]];
    [codeSetName setStringValue: [[codeSetPopMenu selectedItem] title]];
    m = [hc count];
    n = [tc count];
    
    for(j = 0; j < n; j++)
    {
        who = [tc objectAtIndex: j];
        for(i = 0; i < m; i++)
        {
            if([who isEqualToString: [hc objectAtIndex: i]] == YES)
            {
                [codeSetTable selectRow: i byExtendingSelection: YES];
            }
        }
    }
    
}


-(IBAction) codeSetSel: (id) sender
{
    [self codeSetSelNone: sender];
    [self codeSetSelMore: sender];
}


-(IBAction) codeSetSelLess: (id) sender
{
    NSEnumerator *oe = [codeSetTable selectedRowEnumerator];
    NSNumber *sr;
    NSArray *hc = [self allCodeList];
    NSString *fs = [codeSetSelString stringValue];
    AGRegex *regex;
    AGRegexMatch *match;
    
    if([codeSetSelRegex state] == NSOnState)
        regex =  [[AGRegex alloc] initWithPattern: fs options:  (AGRegexCaseInsensitive|AGRegexMultiline)];

    while((sr = [oe nextObject]) != nil)
    {
        if([codeSetSelRegex state] == NSOffState)
        {
            if([codeSetSelExact state] == NSOnState)
            {
                if([[hc objectAtIndex: [sr intValue]] isEqualToString: fs] == YES)
                {
                    [codeSetTable deselectRow: [sr intValue]];
                }
                
            }
            else
            {
                if(([[hc objectAtIndex: [sr intValue]] rangeOfString: fs].location) != NSNotFound)
                {
                    [codeSetTable deselectRow: [sr intValue]];
                }
                
            
            }
        }
        else
        {
            match = [regex findInString: [hc objectAtIndex: [sr intValue]]];
            if([match count])
                    [codeSetTable deselectRow: [sr intValue]];
        }
    }

    if([codeSetSelRegex state] == NSOnState)

        [regex release];
}
-(IBAction) codeSetSelMore: (id) sender
{
    NSArray *hc = [self allCodeList];
    NSString *fs = [codeSetSelString stringValue];
    AGRegex *regex;
    AGRegexMatch *match;
    
    if([codeSetSelRegex state] == NSOnState)
        regex =  [[AGRegex alloc] initWithPattern: fs options:  (AGRegexCaseInsensitive|AGRegexMultiline)];
    
    FORALL(hc)
    {
        if([codeSetSelRegex state] == NSOffState)
        {
            if([codeSetSelExact state] == NSOnState)
            {
                if([temp isEqualToString: fs] == YES)
                {
                    [codeSetTable selectRow: __i byExtendingSelection: YES];
                }
                
            }
            else
            {
                if(([temp rangeOfString: fs].location) != NSNotFound)
                {
                    [codeSetTable selectRow: __i byExtendingSelection: YES];
                }
                
            
            }
        }
        else
        {
            match = [regex findInString: temp];
            if([match count])
                    [codeSetTable selectRow: __i byExtendingSelection: YES];
        }
    }
    ENDFORALL;
    if([codeSetSelRegex state] == NSOnState)
        [regex release];
}

-(NSString *) currCodeSet
{
    return codeSetCurrName;
}

-(BOOL) isCodeSet
{
    if([codeSetCurrName isEqualToString: @""] == YES) return NO;
    return YES;
}
-(NSArray *) codesInCodeSet: (NSString *) who
{
    return [codeSets objectForKey: who];
}
-(BOOL) codeSetExists: (NSString *) who
{
    if([codeSets objectForKey: who] == nil)
        return NO;
            else
    return YES;
}
-(void) registerCodeSet: (NSString *) who withCodes: (NSMutableArray *) what force: (BOOL) ff
{
    if([self codeSetExists: who] == NO || ff)
    {
        [codeSets setObject: what forKey: who];
        [self rebuildCodeSetMenu];
        MAKEDIRTY;
    }
}
-(IBAction) addHotListToSearch: (id) sender
{
    NSMutableString   *currStr = [NSMutableString string];
    NSArray *hcl;
    
    [currStr setString: [searchStringView stringValue]];
    hcl = [self getHotCodeList];
    if([hcl count] > 0)
    {
        if([currStr length] > 0)
            [currStr appendString: @", "];
        [currStr appendString: [hcl componentsJoinedByString: @", "]];
        [searchStringView setStringValue: currStr];
    }
    
        
    
}

-(void) clearTempCodeStack
{
    [tempCodeStack removeAllObjects];
}

-(NSString *) popTempCodeStack
{
    NSDictionary *who;
    NSString *ss;
    //NSLog(@"stack size = %d\n", [tempCodeStack count]);
    if([tempCodeStack count] == 0) return nil;
    who = [tempCodeStack lastObject];
    ss = [who objectForKey: @"name"];
    [ss retain];
    //NSLog(@"name = %@\n", ss);
    [codeSetCurrName setString: [who objectForKey: @"prompt"]];
    [tempCodeList removeAllObjects];
    [tempCodeList addObjectsFromArray: [who objectForKey: @"codes"]];
    [self broadcastCodeChange: NO];
    [tempCodeStack removeLastObject];
    [ss autorelease];
    //NSLog(@"last name = %@\n", ss);
    return ss;
}
-(void) convertTempToRealCodeSet: (NSString *) who
{
    if(tempCodeSet == NO) 
    {
        NSWARNING(@"Current code set is not a quick selection.");
        return ;
    }
    if([codeSets objectForKey: who] != nil)
    {
       if( NSYESNOQUESTION(@"Write over existing code set with this name?") == NO)
           return ;
    }
    [codeSets setObject: [NSMutableArray arrayWithArray: tempCodeList] forKey: [[who copy] autorelease]];
    [codeSetCurrName setString: who];
    tempCodeSet = NO;
    [tempCodeList removeAllObjects];
    [self broadcastCodeChange: NO];
    MAKEDIRTY;
}
-(void) selectTempCodeSetWithin: (NSString *) who
{
    AGRegex *regex;
    AGRegexMatch *match;
    
    NSMutableArray *hcl;
    if(who == nil) return;
    if([who isEqualToString: @""]) return;
    hcl = [NSMutableArray array];
    regex =  [[AGRegex alloc] initWithPattern: who options:  (AGRegexCaseInsensitive|AGRegexMultiline)];
    //erase the current set
    if(tempCodeSet == NO)
    {
        [tempCodeList removeAllObjects];
        [tempCodeList addObjectsFromArray: [self getHotCodeList]];
    }
    FORALL(tempCodeList)
    {
        match = [regex findInString: temp];
        if([match count]) 
        {
            [hcl addObject: temp];
        }
        else
        {
            if([gPrefBoss checkCodeDef])
            {
                NSString *myDef;
                myDef = [self getDefinition: temp];
                if([myDef isEqualToString: @""] == NO)
                {
                    match = [regex findInString: myDef];
                    if([match count])
                        [hcl addObject: temp];
                }
                //look it up and check it
            }
        }
    }
    ENDFORALL;
    //add the current set
    {
        [tempCodeList removeAllObjects];
    }
    [tempCodeList addObjectsFromArray: hcl];
    [tempCodeList sortUsingFunction: nsStringComp  context: nil];
    
    [codeSetCurrName appendString: [NSString stringWithFormat: @", %@",who]];;
    tempCodeSet = YES;
    {
        NSMutableDictionary *myEntry;
        myEntry = [NSMutableDictionary dictionary];
        while([tempCodeStack count] >= [gPrefBoss hclStackSize] && [tempCodeStack count] > 0)
            [tempCodeStack removeObjectAtIndex: 0];
        [myEntry setObject: [NSString stringWithString: who] forKey: @"name"];
        [myEntry setObject: [NSArray arrayWithArray: tempCodeList] forKey: @"codes"];
        [myEntry setObject: [NSString stringWithString: codeSetCurrName] forKey: @"prompt"];
        
        [tempCodeStack addObject: myEntry];
    }
    [regex release];
    [self setCodeListDirty];
    [self broadcastCodeChange: NO];
}



-(void) loadTempCodeSet: (NSString *) who
{
    AGRegex *regex;
    AGRegexMatch *match;
    NSArray *hc = [self allCodeList];
    
    NSMutableArray *hcl;
    if(who == nil) return;
    if([who isEqualToString: @""]) return;
    hcl = [NSMutableArray array];
    regex =  [[AGRegex alloc] initWithPattern: who options: (AGRegexCaseInsensitive|AGRegexMultiline)];
    //erase the current set
    if(tempCodeSet == YES)
    {
        [tempCodeList removeAllObjects];
    }
    FORALL(hc)
    {
        match = [regex findInString: temp];
        if([match count]) 
        {
            [hcl addObject: temp];
        }
        else
        {
            if([gPrefBoss checkCodeDef])
            {
                NSString *myDef;
                myDef = [self getDefinition: temp];
                if([myDef isEqualToString: @""] == NO)
                {
                    match = [regex findInString: myDef];
                    if([match count])
                        [hcl addObject: temp];
                }
                //look it up and check it
            }
        }
    }
    ENDFORALL;
    //add the current set
    [tempCodeList addObjectsFromArray: hcl];
    [tempCodeList sortUsingFunction: nsStringComp  context: nil];

    [codeSetCurrName setString: who];
    {
        NSMutableDictionary *myEntry;
        myEntry = [NSMutableDictionary dictionary];
        while([tempCodeStack count] >= [gPrefBoss hclStackSize] && [tempCodeStack count] > 0)
            [tempCodeStack removeObjectAtIndex: 0];
        [myEntry setObject: [NSString stringWithString: who] forKey: @"name"];
        [myEntry setObject: [NSArray arrayWithArray: tempCodeList] forKey: @"codes"];
        [myEntry setObject: [NSString stringWithString: codeSetCurrName] forKey: @"prompt"];
        [tempCodeStack addObject: myEntry];
    }
    tempCodeSet = YES;
    [regex release];
    [self setCodeListDirty];
    [self broadcastCodeChange: NO];
}

-(void) selectTempCodeSetFewer: (NSString *) who
{
    AGRegex *regex;
    AGRegexMatch *match;
    
    NSMutableArray *hcl;
    if(who == nil) return;
    if([who isEqualToString: @""]) return;
    hcl = [NSMutableArray array];
    regex =  [[AGRegex alloc] initWithPattern: who options:  (AGRegexCaseInsensitive|AGRegexMultiline)];
    //erase the current set
    
    FORALL(tempCodeList)
    {
        BOOL found;
        found = NO;
        match = [regex findInString: temp];
        if([match count]) 
        {
            found = YES;
        }
        else
        {
            if([gPrefBoss checkCodeDef])
            {
                NSString *myDef;
                myDef = [self getDefinition: temp];
                if([myDef isEqualToString: @""] == NO)
                {
                    match = [regex findInString: myDef];
                    if([match count]) found = YES;
                 }
                //look it up and check it
            }
        }
        if(found == NO) 
        {
            [hcl addObject: [[temp copy] autorelease]];
        }
   }
    ENDFORALL;
    //add the current set
    [tempCodeList removeAllObjects];
    [tempCodeList addObjectsFromArray: hcl];
    [tempCodeList sortUsingFunction: nsStringComp  context: nil];
    
    [codeSetCurrName appendString: [NSString stringWithFormat: @"-%@",who]];
    tempCodeSet = YES;
    {
        NSMutableDictionary *myEntry;
        myEntry = [NSMutableDictionary dictionary];
        while([tempCodeStack count] >= [gPrefBoss hclStackSize] && [tempCodeStack count] > 0)
            [tempCodeStack removeObjectAtIndex: 0];
        [myEntry setObject: [NSString stringWithString: who] forKey: @"name"];
        [myEntry setObject: [NSArray arrayWithArray: tempCodeList] forKey: @"codes"];
        [myEntry setObject: [NSString stringWithString: codeSetCurrName] forKey: @"prompt"];
        
        [tempCodeStack addObject: myEntry];
    }
    [regex release];
    [self setCodeListDirty];
    [self broadcastCodeChange: NO];
}

-(void) selectTempCodeSetMore: (NSString *) who
{
    AGRegex *regex;
    AGRegexMatch *match;
    NSArray *hc = [self allCodeList];
    
    NSMutableArray *hcl;
    if(who == nil) return;
    if([who isEqualToString: @""]) return;
    hcl = [NSMutableArray array];
    regex =  [[AGRegex alloc] initWithPattern: who options:  (AGRegexCaseInsensitive|AGRegexMultiline)];
    //erase the current set
    if(tempCodeSet == YES)
    {
        [hcl addObjectsFromArray: tempCodeList];
    }
    
    FORALL(hc)
    {
        match = [regex findInString: temp];
        if([match count]) 
        {
            addUniqueToArray(hcl, [[temp copy] autorelease]);
        }
        else
        {
            if([gPrefBoss checkCodeDef])
            {
                NSString *myDef;
                myDef = [self getDefinition: temp];
                if([myDef isEqualToString: @""] == NO)
                {
                    match = [regex findInString: myDef];
                    if([match count])
                        addUniqueToArray(hcl, [[temp copy] autorelease]);
                }
                //look it up and check it
            }
        }
    }
    ENDFORALL;
    //add the current set
    [tempCodeList removeAllObjects];
    [tempCodeList addObjectsFromArray: hcl];
    [tempCodeList sortUsingFunction: nsStringComp  context: nil];
    
    [codeSetCurrName appendString: [NSString stringWithFormat: @"+%@",who]];
    tempCodeSet = YES;
    {
        NSMutableDictionary *myEntry;
        myEntry = [NSMutableDictionary dictionary];
        while([tempCodeStack count] >= [gPrefBoss hclStackSize] && [tempCodeStack count] > 0)
            [tempCodeStack removeObjectAtIndex: 0];
        [myEntry setObject: [NSString stringWithString: who] forKey: @"name"];
        [myEntry setObject: [NSArray arrayWithArray: tempCodeList] forKey: @"codes"];
        [myEntry setObject: [NSString stringWithString: codeSetCurrName] forKey: @"prompt"];
        
        [tempCodeStack addObject: myEntry];
    }
    [regex release];
    [self setCodeListDirty];
    [self broadcastCodeChange: NO];
}

-(void) addCodeToCurrSet: (NSString *) who
{
    NSMutableArray *na = [NSMutableArray array];
    if(tempCodeSet)
    {
        [tempCodeList addObject: [[who copy] autorelease]];
        [tempCodeList sortUsingFunction: nsStringComp  context: nil];
        return;
    }
    if([codeSetCurrName isEqualToString: @""] == YES) return;
    [na addObjectsFromArray: [self getHotCodeList]];
    [na addObject: [[who copy] autorelease]];
    [codeSets setObject: na forKey: codeSetCurrName];
    MAKEDIRTY;
}

-(NSArray *) allCodeSetNames
{
    NSMutableArray *ans =[NSMutableArray array];
    [ans addObjectsFromArray: [codeSets allKeys]];
    [ans sortUsingFunction: menuStringComp  context: nil];
    return ans;
}


-(void) rebuildCodeSetMenu: (NSMenu *) asmn withSel: (SEL) mysel at: (int) start showState: (BOOL) st
{
    int i, n, m;
    NSMutableArray  *w2;
    
    m = [asmn numberOfItems];
    
    if(m > start)
        for(i = start; i < m; i++)
        {
            [asmn removeItemAtIndex: start];
        }

    w2 = [NSMutableArray arrayWithArray: [self allCodeSetNames]];
    
    [w2 sortUsingFunction: menuStringComp  context: nil];

    n = [w2 count];
    
    if(n > 0)
    {
        [asmn addItem: [NSMenuItem separatorItem]];
        for(i=0; i< n; i++)
        {
            [asmn addItemWithTitle: [w2 objectAtIndex: i]
                action: mysel
                keyEquivalent: @""];
        }
        if([codeSetCurrName isEqualToString: @""] == NO && st)
        {
            [[asmn itemWithTitle: codeSetCurrName] setState: NSOnState];
        }
    }
        
}
-(void) rebuildCodeSetMenu: (NSMenu *) asmn  at: (int) start
{
    [self rebuildCodeSetMenu: asmn withSel: @selector(loadCodeSet:) at: start showState: YES];
}
-(void) rebuildCodeSetMenu 
{
    [self rebuildCodeSetMenu: [[[NSApp delegate] codeSetMenu] submenu] at: CODESETBASE];
    [self rebuildCodeSetMenu: [codeSetPopMenu2 menu] at: CODESETBASE2];
    /*
    [self rebuildCodeSetMenu: [[[NSApp delegate] rsltCodeSetMenu] submenu] 
                     withSel: @selector(selectCodeSet:) at: CODESETBASE3 showState: NO];
     */
    
}
-(IBAction) codeSetAdd: (id) sender
{
    NSMutableArray *csa, *hc;
    NSEnumerator *oe = [codeSetTable selectedRowEnumerator];
    NSNumber *sr;
    
    
    csa = [NSMutableArray array];
    hc = [self allCodeList];
    while((sr = [oe nextObject]) != nil)
    {
        [csa addObject: [[[hc objectAtIndex: [sr intValue]] copy] autorelease]];
    }

    
    if([[codeSetName stringValue] isEqualToString: @""] == YES)
        {
        NSWARNING(@"You must name the current set");
        }
    else if([csa count] == 0)
        {
        NSWARNING(@"You must select the codes you want in the set before saving");
        }
    else
    {
        [codeSets setObject: csa forKey: [codeSetName stringValue]];
        [self rebuildCodeSetPopMenu];
        [codeSetPopMenu selectItemWithTitle: [codeSetName stringValue]];

    }
}

-(IBAction) codeSetClose: (id) Sender
{
    [codeSetPane orderOut: Sender];
    [NSApp endSheet: codeSetPane returnCode: 0];

}


-(IBAction) editCodeSet: (id) Sender
{
    NSWindow *who;
    NSArray *hc;
    hc = [self allCodeList];
    
    [codeSetName setStringValue: @""];
    [self rebuildCodeSetPopMenu];
    [codeSetTable reloadData];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
     [NSApp beginSheet: codeSetPane
	modalForWindow: who
	modalDelegate: self
	didEndSelector: @selector(codeSetDidEnd:returnCode:contextInfo:)
	contextInfo: nil];

}

/* -----------------------------------------------------*/
-(IBAction) fileSetSelAll:(id) sender
{
    [fileSetTable selectAll: nil];
}
-(IBAction) fileSetSelNone:(id) sender
{
    [fileSetTable deselectAll: nil];
}
-(IBAction) fileSetDelAll: (id) sender
{
    if(NSYESNOQUESTION(@"Delete all file sets?") == YES)
    {
        [fileSetCurrName setString: @""];
        [self reloadFileSet];
        [fileSets removeAllObjects];
        [self rebuildFileSetPopMenu];
    }
}

-(IBAction) fileSetDel: (id) sender
{
    if(NSYESNOQUESTION(@"Delete selected file set?") == YES)
    {
        if([fileSetCurrName isEqualToString: [[fileSetPopMenu selectedItem] title]] == YES)
        {
            [fileSetCurrName setString: @""];
            [self reloadFileSet];
        }
        [fileSets removeObjectForKey: [[fileSetPopMenu selectedItem] title]];
        [self rebuildFileSetPopMenu];
    }
}

-(IBAction) loadAllFiles: (id) sender
{
    [self loadFileSetWithName: @""];
    MAKEDIRTY;
}


-(void) loadFileSet: (id) sender
{
    [self loadFileSetWithName: [sender title]];
    MAKEDIRTY;
}

-(void) loadFileSetWithName: (NSString *) who
{
   NSString *tmp;
    [fileSetCurrName setString: who];
    [self rebuildFileSetMenu];
    [fileListView reloadData];
    if([who isEqualToString: @"Results"] == YES)
        fileViewMode = RESULTMODE;
    else
        fileViewMode = FILEMODE;
    if([who isEqualToString: @""] == YES)
    {
        NSSETHEADER(fileListView, @"Files",@"Files");
    }
    else
    {
        tmp =[NSString stringWithFormat: @"Files: %@", who];
        NSSETHEADER(fileListView, @"Files", tmp);
    }
    fList = [self hotFileSet];

}

-(void) reloadFileSet
{
    [self loadFileSetWithName: [[fileSetCurrName copy] autorelease]];
}
-(IBAction) showFileSet: (id) sender
{
     int i, j, m, n;
   NSArray *hc = [self allFileList];
    NSArray *tc;
    NSString *who;
    if([fileSetPopMenu selectedItem] == nil )return;
    [self fileSetSelNone: nil];
    tc = [fileSets objectForKey: [[fileSetPopMenu selectedItem] title]];
    [fileSetName setStringValue: [[fileSetPopMenu selectedItem] title]];
    m = [hc count];
    n = [tc count];
    
    for(j = 0; j < n; j++)
    {
        who = [tc objectAtIndex: j];
        for(i = 0; i < m; i++)
        {
            if(who == [hc objectAtIndex: i])
            {
                [fileSetTable selectRow: i byExtendingSelection: YES];
            }
        }
    }
    
}
-(void) rebuildFileSetPopMenu
{
    [fileSetPopMenu removeAllItems];
    FORALL([self dataFileSetNames])
    {
    
        [[fileSetPopMenu menu] addItemWithTitle: temp
            action: @selector(showFileSet:) keyEquivalent: @""];
    
    }
    ENDFORALL;
}


-(IBAction) fileSetSel: (id) sender
{
    [self fileSetSelNone: sender];
    [self fileSetSelMore: sender];
}


-(IBAction) fileSetSelLess: (id) sender
{
    NSEnumerator *oe = [fileSetTable selectedRowEnumerator];
    NSNumber *sr;
    NSArray *hc = [self allFileList];
    NSString *fs = [fileSetSelString stringValue];
    AGRegex *regex;
    AGRegexMatch *match;
    
    if([fileSetSelRegex state] == NSOnState)
        regex =  [[AGRegex alloc] initWithPattern: fs options:  (AGRegexCaseInsensitive|AGRegexMultiline)];

    while((sr = [oe nextObject]) != nil)
    {
        if([fileSetSelRegex state] == NSOffState)
        {
            if([fileSetSelExact state] == NSOnState)
            {
                if([[[hc objectAtIndex: [sr intValue]] name] isEqualToString: fs] == YES)
                {
                    [fileSetTable deselectRow: [sr intValue]];
                }
                
            }
            else
            {
                if(([[[hc objectAtIndex: [sr intValue]] name] rangeOfString: fs].location) != NSNotFound)
                {
                    [fileSetTable deselectRow: [sr intValue]];
                }
                
            
            }
        }
        else
        {
            match = [regex findInString: [[hc objectAtIndex: [sr intValue]] name]];
            if([match count])
                    [fileSetTable deselectRow: [sr intValue]];
        }
    }

    if([fileSetSelRegex state] == NSOnState)

    [regex release];
}

-(NSArray *) allFileList
{
    return allFiles;
}

-(IBAction) fileSetSelMore: (id) sender
{
    NSArray *hc = [self allFileList];
    NSString *fs = [fileSetSelString stringValue];
    AGRegex *regex;
    AGRegexMatch *match;
     
    if([fileSetSelRegex state] == NSOnState)
        regex =  [[AGRegex alloc] initWithPattern: fs options:  (AGRegexCaseInsensitive|AGRegexMultiline)];
    
    FORALL(hc)
    {
        if([fileSetSelRegex state] == NSOffState)
        {
            if([fileSetSelExact state] == NSOnState)
            {
                if([[temp name] isEqualToString: fs] == YES)
                {
                    [fileSetTable selectRow: __i byExtendingSelection: YES];
                }
                
            }
            else
            {
                if(([[temp name] rangeOfString: fs].location) != NSNotFound)
                {
                    [fileSetTable selectRow: __i byExtendingSelection: YES];
                }
                
            
            }
        }
        else
        {
            match = [regex findInString: [temp name]];
            if([match count])
                    [fileSetTable selectRow: __i byExtendingSelection: YES];
        }
    }
    ENDFORALL;

}
-(NSArray *) getHotFileList
{
    return [self hotFileSet];
}
-(int) hotFileCount
{
    if([fileSetCurrName isEqualToString: @""] == YES)
        return [[self allFileList] count];
    return [[fileSets objectForKey: fileSetCurrName] count];

}
-(NSArray *) hotFileSet
{
    if([fileSetCurrName isEqualToString: @""] == YES)
        return [self allFileList];
    return [fileSets objectForKey: fileSetCurrName];
}

-(NSString *) currFileSet
{
    return fileSetCurrName;
}

-(BOOL) isFileSet
{
    if([fileSetCurrName isEqualToString: @""] == YES) return NO;
    return YES;
}
-(void) removeFile: (MWFile *) who fromSet: (NSString *) s
{
    NSMutableArray *na = [NSMutableArray array];
    NSArray *extant;
    
    
    if([s isEqualToString: @""] == YES) return;
    extant = [fileSets objectForKey: s];
    if(extant != nil)
        [na addObjectsFromArray: extant];
    [na removeObject: who];
    [fileSets setObject: na forKey: s];
    if([s isEqualToString: fileSetCurrName] == YES)
        fList = na;
}
-(void) addFile: (MWFile *) who toSet: (NSString *) s
{
    NSMutableArray *na = [NSMutableArray array];
    NSArray *extant;
    

    if([s isEqualToString: @""] == YES) return;
    extant = [fileSets objectForKey: s];
    if(extant != nil)
        [na addObjectsFromArray: extant];
    [na addObject: who];
    [fileSets setObject: na forKey: s];
    if([s isEqualToString: fileSetCurrName] == YES)
        fList = na;
}

-(void) addFileToCurrSet: (MWFile *) who
{
    NSMutableArray *na = [NSMutableArray array];
    if([fileSetCurrName isEqualToString: @""] == YES) return;
    [na addObjectsFromArray: [self getHotFileList]];
    [na addObject: who];
    [fileSets setObject: na forKey: fileSetCurrName];
    fList = na;
}

-(NSArray *) allFileSetNames
{
    NSMutableArray *ans =[NSMutableArray array];
    [ans addObjectsFromArray: [fileSets allKeys]];
    [ans sortUsingFunction: menuStringComp  context: nil];
    return ans;
}

-(NSArray *) dataFileSetNames
{
    NSMutableArray *tmp, *ans = [NSMutableArray array];
    tmp = [self allFileSetNames];
    FORALL(tmp)
    {
        if([temp isEqualToString: @"Results"] == NO)
            [ans addObject: [[temp copy] autorelease]];
    }
    ENDFORALL;
    [ans sortUsingFunction: menuStringComp  context: nil];
   
    return ans;
}
-(void) rebuildFileSetMenuFor: (NSMenu *) asmn at: (int) start 
{
    int i, n, m;
    NSMutableArray  *w2;
    
    m = [asmn numberOfItems];
    
    if(m > start)
        for(i = start; i < m; i++)
        {
            [asmn removeItemAtIndex: start];
        }

    w2 = [NSMutableArray arrayWithArray: [self allFileSetNames]];
    
    [w2 sortUsingFunction: menuStringComp  context: nil];

    n = [w2 count];
    
    if(n > 0)
    {
        [asmn addItem: [NSMenuItem separatorItem]];
        for(i=0; i< n; i++)
        {
            [asmn addItemWithTitle: [w2 objectAtIndex: i]
                action: @selector(loadFileSet:)
                keyEquivalent: @""];
        }
        if([fileSetCurrName isEqualToString: @""] == NO)
        {
            [[asmn itemWithTitle: fileSetCurrName] setState: NSOnState];
        }
    }
        
}

-(void) rebuildFileSetMenu
{
    [self rebuildFileSetMenuFor: [[[NSApp delegate] fileSetMenu] submenu]  at: FILESETBASE];
    [self rebuildFileSetMenuFor: [fileSetPopMenu2 menu] at: FILESETBASE2];
}
-(IBAction) fileSetAdd: (id) sender
{
    NSMutableArray *csa, *hc;
    NSEnumerator *oe = [fileSetTable selectedRowEnumerator];
    NSNumber *sr;
    
    
    csa = [NSMutableArray array];
    hc = [self allFileList];
    while((sr = [oe nextObject]) != nil)
    {
        [csa addObject: [hc objectAtIndex: [sr intValue]]  ];
    }

    
    if([[fileSetName stringValue] isEqualToString: @""] == YES)
        NSWARNING(@"You must name the current set")
    else
    {
        [fileSets setObject: csa forKey: [fileSetName stringValue]];
        [self rebuildFileSetPopMenu];
        [fileSetPopMenu selectItemWithTitle: [fileSetName stringValue]];
    }
}

-(IBAction) fileSetClose: (id) Sender
{
    [fileSetPane orderOut: Sender];
    [NSApp endSheet: fileSetPane returnCode: 0];

}

- (void) fileSetDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void  *)contextInfo
{
    [self rebuildFileSetMenu];
    MAKEDIRTY;
}

-(IBAction) editFileSet: (id) Sender
{
    NSWindow *who;
    
    [fileSetName setStringValue: @""];
    [self rebuildFileSetPopMenu];
    [fileSetTable reloadData];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = myWindow;
     [NSApp beginSheet: fileSetPane
	modalForWindow: who
	modalDelegate: self
	didEndSelector: @selector(fileSetDidEnd:returnCode:contextInfo:)
	contextInfo: nil];

}
/* summary report***************************************** */
-(BOOL) isMySummReport: (NSString *) who
{
    NSArray *a;
    a = [self mySummReports];
    FORALL(a)
    {
        if([temp isEqualToString: who]) return YES;
    }
    ENDFORALL;
    return NO;
}

-(void) addSummReport:(NSString *) who report: (NSDictionary *) r global: (BOOL) g
{
    if(g == YES)
    {
        [summReports setObject:r forKey: who];
        [self rebuildSummReportMenu];
        MAKEDIRTY;
    }
}
-(void) delSummReport:(NSString *) who
{
    if([self isMySummReport: who])
    {
        [summReports removeObjectForKey: who];
        [self rebuildSummReportMenu];
        MAKEDIRTY;
    }
}
-(NSDictionary *) summReport: (NSString *) who
{
    NSDictionary *ans;
    ans = [summReports objectForKey: who];
    if(ans == nil) return nil;
    else return ans;
}
-(NSArray *) mySummReports
{
    return [summReports allKeys];
}

-(void) rebuildSummReportMenu
{
    int i, n, m;
    NSMenu *asmn;
    NSMutableArray *w1, *w2;
    
    asmn = [[[NSApp delegate] summReportMenu] submenu];
    m = [asmn numberOfItems];
    
    if(m > SUMMREPORTBASE)
        for(i = SUMMREPORTBASE; i < m; i++)
        {
            [asmn removeItemAtIndex: SUMMREPORTBASE];
        }

    w1 = [NSMutableArray arrayWithArray: [self mySummReports]];
    
    [w1 sortUsingFunction: nsStringComp  context: nil];
    //who = [self allSetNames];
    if((m = [w1 count]) > 0)
    {
        [asmn addItem: [NSMenuItem separatorItem]];
        for(i=0; i< m; i++)
        {
            [asmn addItemWithTitle: [w1 objectAtIndex: i]
                action: nil
                keyEquivalent: @""];
        }
    }
        
}
-(IBAction) doDotGraph: (id) sender
{
    NSArray *hcl;
    NSString *theName;

    NSString *pp, *ss;
    NSMutableString *ans;
    NSMutableArray *nodeArray;
	NSTask *mytask;
	NSFileHandle *h;
/*
    if([[NSWorkspace sharedWorkspace] fullPathForApplication: @"Graphviz"] == nil)
    {
        NSWARNING(@"You need to install Graphviz to use this function. See the documentation.");
        return;
    }
*/
    ans =[NSMutableString string];
    nodeArray = [NSMutableArray array];
    theName = [NSString stringWithFormat: @"/tmp/tams codetree %@.dot", uniqueFileName()];
    //theName = [NSString stringWithFormat: @"/tmp/tamstemp.dot"];
 
   //get the hot code list
    hcl = [self hotCodeList];
    [ans appendString: @"digraph codetree {\n"];
    //for every code
    FORALL(hcl)
    {
        NSString *theString;
        theString = temp;
        while(theString != nil)
        {
    //create a node with terminus as its label
           ss = [NSString stringWithFormat: @"\"%@\"[label=\"%@\"]\n",
               theString, terminusOf(theString)];
            addUniqueToArray(nodeArray, ss);
            theString = parentOf(theString);
            
        }
    }
    ENDFORALL;
    FORALL(nodeArray)
    {
        [ans appendString: temp];
    }
    ENDFORALL;
    [nodeArray removeAllObjects];
    //for every code 
    FORALL(hcl)
    {
        NSString *whole;
        
        whole = temp;
        while((pp = parentOf(whole)) != nil)
        {
             ss = [NSString stringWithFormat: @"\"%@\"->\"%@\"\n",
                pp, whole];
            addUniqueToArray(nodeArray, ss);
            whole = pp;
        }
    }
    ENDFORALL;
    FORALL(nodeArray)
    {
        [ans appendString: temp];
    }
    ENDFORALL;
    [ans appendString: @"}\n"];
    //does it have a parent?
    //create edge between self and parent
    //make the graph
    [ans writeToFile: theName atomically: YES];
    //if(saveFlag == NO)
  //  [[NSWorkspace sharedWorkspace] openFile:theName withApplication: @"Graphviz.app"];
	mytask = [[NSTask alloc] init];

	[mytask setLaunchPath: [gPrefBoss dotDir]];
	[mytask setArguments: [NSArray arrayWithObjects: @"-Tps", [NSString stringWithFormat: @"-o%@.ps",theName],theName, nil]];
/*
	[[NSFileManager defaultManager] createFileAtPath: [NSString stringWithFormat: @"%@.ps", theName]
		contents: @""
		attributes: [NSDictionary dictionary]];
	[mytask setStandardOutput: [NSFileHandle fileHandleForWritingAtPath: [NSString stringWithFormat: @"%@.ps", theName]]];
*/

	[mytask launch];
    //[mytask waitUntilExit];

	if([gPrefBoss useGV] == 1)
	{
		NSLog(@"Using gv\n");
		[NSTask launchedTaskWithLaunchPath: [gPrefBoss gvDir] arguments: [NSArray arrayWithObjects: [NSString stringWithFormat: @"%@.ps",theName], nil]];
	}
	else
		if([[NSWorkspace sharedWorkspace] openFile: [NSString stringWithFormat: @"%@.ps", theName]] == NO)
		{
			NSString *mywarn, *mygraphfile;
			mygraphfile = [NSString stringWithFormat: @"%@.ps", theName];
			mywarn = [NSString stringWithFormat: @"Could not open application for file \"%@\"", mygraphfile];
			NSWARNING(mywarn);	
		}

}
-(IBAction) addSelfToWorkMenu: (id) sender
{
    NSString *fn = [self fileName];
    if(fn != nil)
    {
        [[NSApp delegate] addWorkItem: fn];
    }
    else
        NSWARNING(@"Project must be saved before being added to work menu.");
}
#ifdef MULTIMEDIA
-(IBAction) convertSec2HHMMSS:(id) sender
{
    if([searchFiles count] == 0)
    {
        NSWARNING(@"You must add files to search list.");
        return;
    }
    FORALL(searchFiles)
    {
        if((MWFile *)[temp open] == NO)
        {
            if([gPrefBoss batchOpenFiles])
                [self openMWFile: temp type: SOURCETYPE];
            else
                [(MWFile *)temp setOpenFakeFileWithWorkBench: self];
        }
        
        [[temp filePointer] ConvertMovieTimeToHHMMSS: YES];
        [temp closeFakeFile];


    }

    ENDFORALL;
    
    
}

-(IBAction) convertHHMMSS2Sec:(id) sender
{
    if([searchFiles count] == 0)
    {
        NSWARNING(@"You must add files to search list.");
        return;
    }
    FORALL(searchFiles)
    {
        if((MWFile *)[temp open] == NO)
        {
            if([gPrefBoss batchOpenFiles])
                [self openMWFile: temp type: SOURCETYPE];
            else
                [(MWFile *)temp setOpenFakeFileWithWorkBench: self];
        }
        
        [[temp filePointer] ConvertMovieTimeToHHMMSS: NO];
        [temp closeFakeFile];
        
        
    }
    
    ENDFORALL;
    
    
}

#endif
-(void) setupSearchMode: (int) smode
{
    switch(smode)
    {
        case REGEXCHARINDEX:
            [coderIDPrompt setStringValue: @"Substring:"];
            [coderIDView setStringValue: @"0"];
            [exactButton setTitle: @"Case sens."];
            [emptyButton setTitle: @"Multiline"];
            break;
            
        
        default:
            [coderIDPrompt setStringValue: @"Coder IDs:"];
            [coderIDView setStringValue: @""];
            [exactButton setTitle: @"Exact"];
            [emptyButton setTitle: @"Empty"];
            break;
    };
}
-(IBAction) initializeSearchMode: (id) sender
{
    [self setupSearchMode: [searchTypeMenu tagOfSelectedItem]];
}
@end
