// FIX RESFORK modBuffer
/*
 *  PeekItMainWind.c
 *  PeekIt
 *
 *  Created by C.K. Haun on Fri Feb 07 2003.
 *  Copyright (c) 2003 Ravenware Software. All rights reserved.
 *
 */
// making the panes HIViews
// tommorrow.....
// all changes are reflected in the file buffer.
// so every time you read in a chunk of file, you have to walk the change list and update
// any changes the user has made.
// NO CHANGES will be made to the file until the user tells me three times
// or two times
// or if they are quitting, dang it
// switching the acsii and hex button positions

#define kNotePUMenuID 876
#include "PeekIt.h"
#define ZapRect(A,B)
extern     IBNibRef 		gNibRef;
extern       UInt16 gSavesPending;
extern Rect gDefaultWindRect;
enum {kDrawingAddyInDec = 0,kDrawingAddyInHex};
// going to bump up the file buffer a little from 10k
enum {kPeekItID='PEEK', kFileBufferSize = 500000,kExportMenuItem = 'EXPT'};
enum{
    kPeekItRawPane = 1000, kPeekItTransPane=1001,
    kPeekPosPane = 1080,kPeekReadOnlyPane = 1087,
    kPeekHexEditBox =1100,kPeekHexEditWords = 1101,
    kPeekApplyEditButt = 1105,
    kPeekEditGroupBox = 1158,kPeekEnterHexOrASCII =1159,kPeekEnterASCIIWords=1165,
    kInfoDiscTriangle= 9878,kInfoDiscWords,
    kInfoPane = 2098,
    kPeekItRawScroll=1010,kPeekItTransScroll=1011,
    
    kPeekScrollTo=    5454,kPeekNextChange = 5460,
    kPeekRawRadio=8000,kPeekModifiableRadio=8001,
    kPeekDataForkRadio = 8600,kPeekResForkRadio,
    
    kPeekText1=9000,kPeekText2,kPeekText3,
    kPeekShowHexCheck=9056,
    kPeekPopup =7050,kPeekRevertButton = 7060,kPeekCommitButton=7061,
    kPeekValDrawerToggle = 7063,
    kPeekCurrentPosPane = 3459,
    /* notes area */    
    kNotesUserPane = 4050,
    kNotesPopUp,
    kNotesDeleteNote,
    kNotesNewNote,
    kEditNote=4055,
    kExportNotes,
    
    
    kForRawData = 0,
    kForTransData=1,
    kNumColumns = 10,
    kPaneSpace = 30,kPosWide = 48,
    kFlagRedraw = 0x1,
    kForceReReadBuffer=0x2,
    kInfoPaneSize = 100,
    kNotModifying=1,kModifying =2,kReadOnly = 3,
    kEditingAsAscii= 1,kEditingAsHex
};
enum {
    kDrawRawData=0,
    kDrawTransData
};



void liveScroller(ControlRef theControl, ControlPartCode partCode);
void liveScroller2(ControlRef theControl, ControlPartCode partCode);
extern WindowRef AddBMarkWind(WindowRef theWindow,FileTrackerPtr theFile);

static  OSStatus PIScrollBarEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
static  OSStatus PIDiscTriEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
static  OSStatus PIDiscHexEventHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
static  OSStatus PIHexBoxEventHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
static  OSStatus PIHexOrAsciiHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
static  OSStatus PIResAndDataRadioHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );

static  OSStatus PIRawPaneEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
static  OSStatus PITransPaneEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
static  void ColDrawRect(Rect * bRect,short forWhat,WindowRef theWindow);
static  OSStatus PIPosPaneEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
// static  OSStatus PIInfoPaneEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
static  OSStatus PIModifiRadioHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
static  OSStatus PINextChangeEventHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
        static  OSStatus PIPIScrollToEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );

static  OSStatus PICurFilePosPaneEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );

void CalcNumColumns(CGContextRef inRef, WindowRef theWindow);
void CalcNumRows(WindowRef theWindow);

static void SizePIMainWINDControls(WindowRef theWindow);

void DrawData(WindowRef theWindow,UInt16 which);

extern        WindowRef AddFindWIND(WindowRef theWindow,FileTrackerPtr theFile);


/*
 *  PIMainWindow.c
 *  MIDIComp
 *
 *  Created by C.K. Haun on Tue Feb 04 2003.
 *  Copyright (c) 2003 Ravenware Software. All rights reserved.
 *
 */

/*
 GenericWindow
 
 */
#define __PIMainWINDOW__
void HitPIMainWIND(WindowRef theWindow, Point *thePoint);

void HexBoxValidator(                    ControlRef control                     );

ControlKeyFilterResult hexerFilter (
                                    ControlRef theControl,
                                    SInt16 * keyCode,
                                    SInt16 * charCode,
                                    EventModifiers * modifiers
                                    );

void PrefsPanelOpening(WindowRef theWindow);
void SetPrefsToStored(WindowRef theWindow);
void HarvestPrefs(WindowRef theWindow);
enum{
    kViewingAsRawHex=0,
    kViewingAsRawASCII,
    kViewingAsFilteredASCII
    
};
struct fileDisplay{
    Ptr fileBuffer;
    SInt64 bufStartInFile;
    SInt64 bufEndInFile; 
    SInt64 offsetInBuffer;
    SInt64 posInFile;  // bufStart + offSetIn
    UInt16 bytesShowing;   // how many bytes fill the current display
};
typedef struct fileDisplay fileDisplay;

struct PIMainWindData {
    FileTrackerPtr theFT;
//---------
    Rect rawTargetRect;
    Rect transTargetRect;
//----------
    WindowRef valueDrawer;
    WindowRef findDrawer;
    WindowRef expNotesDrawer;
    WindowRef bmarkWindow;
    WindowRef exportSheet;
    WindowRef modSheet;
    WindowRef commitSheet;
    WindowRef compDrawer;
//-------
    ControlRef rawPane;
    ControlRef rawScroll;
    ControlRef transPane;
    ControlRef transScroll;
    ControlRef modifiRadio;
    ControlRef editAsRadio;
    ControlRef infoCont;
    ControlRef hexCont;
    ControlRef hexEditBox;
    ControlRef posPane;
    ControlRef curPosThingie;
    ControlRef readOnlyPane;
    ControlRef dataForkRadio;
    ControlRef resForkRadio;
    // ControlRef infoPane;
    Boolean savingChanges;
    short infoShowing;
    Boolean noFile;
    UInt16 infoPanelStarts;
    short scrollWide;
    short posWide;
    UInt16 calcedNewPosWidth;
    UInt16 forkShowing;
    fileDisplay displaying;
    Boolean showingHex;
    Ptr modBuffer;
    UInt32 modifying;
    short charWide;
    short numRows;
    short numColumns; // this is times two for the interpretive column
    short oldNumColumns; // urgle
    short sizeDataInPane;
    short columnWidth;
    short cellHi;
    short ullage; // the gaps & scroll width
    short viewingAs; // interprete
    UInt16 editingAs;  // as hex, as ascii
    Boolean fileDirty;
    short fontSize;
    short fontNum;
    RGBColor offColor;
    WindowRef us;
    WCH theWCH; 	// arrg
    piCell	*startSel;
    piCell      *endSel;    // starting to havce multi-selections for moving/collapsing
    ChangeGenerationPtr changeGenerations;
    UInt32 changeGeneration;
    changedBytePtr changes;
    changedBytePtr lastChangeMovedTo;
    changedBytePtr forkChanges[3];	
    piCell	* selections[3];
    piCell          * endSelections[3];
    SInt64 rangeStart;
    SInt64 rangeEnd;
    CFStringRef * helpStrings;
    CFStringRef * generalStrings;
    SLibSearchParamBlockPtr lastFindPtr;
    Boolean bookMarksDirty;
    BookMarkPtr theFileNotes;
    BookMarkPtr currentNote;
    BookMarkPtr    nextNoteIsBM;
    BookMarkPtr preload;
    SInt64 nextNoteIsAtByte; // an optimization 
    UInt16 drawingPosAs;
    
    FileTrackerPtr comparingWithFile;
    fileDisplay comparing;
    UInt16 comparingWith;
    Boolean diffingActive;
    diffByteRangePtr currentDiffs;
    diffByteRangePtr dataForkDiffs;
    diffByteRangePtr resForkDiffs;
    EventLoopTimerRef theDiffTimer;
    PMPageFormat pageFormat;
};
typedef struct PIMainWindData PIMainWindData;
typedef PIMainWindData *PIMainWDataP /* , **PIMainWDataP */ ;
/* protos */
#pragma mark Protos
BookMarkPtr PIMainWindHaveBMToLoad(WindowRef theWindow);
UInt16 PIWindowGiveMeBytesAtSelection(PIMainWDataP nowCD,Ptr putHere,UInt16 howMany);
static void PIMainCompareFileStart(WindowRef theWindow,PIMainWDataP nowCD,FileTrackerPtr withThis);
static void PIMainGotoNextDiff(WindowRef theWindow,PIMainWDataP nowCD,FileTrackerPtr withThis);

static  void ColDrawRectQuartz(CGContextRef cgContext,short forWhat, PIMainWDataP  nowCD );

changedBytePtr ChangedByteAtPosition(  PIMainWDataP nowCD,SInt64 position);

        static  OSStatus PICommitHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );

        static  OSStatus PIRevertHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );

        static  OSStatus PIPIApplyEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );

void SwitchAddyView(WindowRef theWindow, PIMainWDataP nowCD);
void SnapshotWindowSize(WindowRef theWindow, PIMainWDataP nowCD);

UInt16 PIWindowGiveMeBytes(PIMainWDataP nowCD,Ptr putHere,UInt16 howMany);

SInt64 PIWindowBytesFromSelToEndOfFork(PIMainWDataP nowCD);
void PICopyToClipboard(PIMainWDataP nowCD);

OSStatus PIWWindowConstrainCode(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData);
UInt16 PIWindowGiveMeBytesAtPosition(PIMainWDataP nowCD,Ptr putHere,UInt16 howMany,SInt64 positionToStartFrom);

void PISaveFileChanges(PIMainWDataP nowCD);
void SaveFileAs(PIMainWDataP nowCD);
static Boolean isthereanotherdiff(PIMainWDataP nowCD);


// void PISortChanges(PIMainWDataP nowCD);
void         PIUndoLast(PIMainWDataP nowCD);
// void PICancelSaveModifications(PIMainWDataP nowCD);
// void         PINextStageOfModSave(PIMainWDataP nowCD);
OSStatus ChangeAByteRange( PIMainWDataP nowCD,SInt64 rangeStart, SInt64 rangeEnd,Ptr dataPointer,char toThisByte, UInt32 changeTypeID,UInt32 changeIDNumber);

enum{kPrefsTextColor=0,kPrefsBackColor,kPrefsHiColor};
RGBColor pDefColor[3];
void OuterExportFile(PIMainWDataP nowCD);

// void         ExportFile(PIMainWDataP nowCD);
void ExportFile(WindowRef theWindow,SInt64 start,SInt64 end);
void piwindMoveThisBytePtrToEndOfChangeChain( PIMainWDataP nowCD,changedBytePtr thisOne);

void SizePIMainWIND(WindowRef theWindow, EventRecord *theEvent, short how);
void SetScrollValues(PIMainWDataP nowCD,UInt64 filePos);
OSStatus CouldReadDataChunk(PIMainWDataP nowCD,UInt16 flags);
void DrawFileInfo(PIMainWDataP nowCD,UInt16 flags);
void SetUpPIMainWindowMenus(PIMainWDataP nowCD,UInt32 theID);
void             FillInPendingChanges(PIMainWDataP nowCD);
void PIPushChangesOut(PIMainWDataP nowCD);
void PIClearAllChanges(PIMainWDataP nowCD);
SInt64 PIReturnSelectionRealPosition(WindowRef theWindow);
void PIExecuteSearch(WindowRef theWindow, SLibSearchParamBlockPtr theSearchBlock);
static  OSStatus PIReadOnlyPaneEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );

extern OSStatus UpdateCellPoses(piCell *theCell, PIMainWDataP nowCD);
OSStatus    PIMainWindSwapForks(PIMainWDataP nowCD);
static void pdoscrollto(PIMainWDataP nowCD);
BookMarkPtr bmNoteAtOrAfter(PIMainWDataP nowCD,SInt64 pos);
#define mGetCGContext { GetEventParameter( inEvent, kEventParamCGContextRef, typeCGContextRef,NULL, sizeof( CGContextRef ), NULL, &cgContext );}

void             pimwStoreLastFind(WindowRef theWindow,SLibSearchParamBlockPtr theSearchBlock);
OSStatus PIMainWindowCloseCode(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData);
void pimwMoveToThisByte(WindowRef theWindow, SInt64 theByte);
// INCLUDING the pane files

#include "paneHIView.pi.c" 
#include "pimainview.Quartz.pi.c"
#include "Bookmarklogic.pi.c"
#include "Bookmarkpane.pi.c"
#include "datadraw.pi.c"
#include "expnotes.pi.c"
#include "ValDrawer.pi.c"
#include "exportsheet.pi.c"
#include "ModRange.pi.c"
#include "changessheet.pi.c"
#include "pimainwindhelp.pi.c"
#include "pimainwindowutil.pi.c"
#include "commitsheet.c"
#include "diffdrawer.pi.c"
void piwindMoveThisBytePtrToEndOfChangeChain( PIMainWDataP nowCD,changedBytePtr thisOne)
{
    changedBytePtr otherOne;

    changedBytePtr theChanges=nowCD->changes;

    if(thisOne->previous){
        thisOne->previous->next = thisOne->next;
    }
    if(thisOne->next){
        thisOne->next->previous = thisOne->previous;
    }
    // run to the end
    if(theChanges->next){
    while(theChanges->next)
        theChanges = theChanges->next;
        
        theChanges->next = thisOne;
        thisOne->previous = theChanges;
        thisOne->next = 0;

    }
    
    
}




HICommandExtended theC;

void  PINavEventProc (NavEventCallbackMessage callBackSelector, NavCBRecPtr callBackParms, void *callBackUD)
{
    NavUserAction theAction;
    PIMainWDataP nowCD = (PIMainWDataP)callBackUD;
    theAction =  NavDialogGetUserAction (
                                         callBackParms-> context
                                         );
    
    if(callBackSelector == 12 && theAction == kNavUserActionDontSaveChanges){        theC.attributes=kHICommandFromWindow;
        
        
        WindowRef theWindow = nowCD->us;
        // just close
        docoreclose(nowCD->us);
        // and shut the window
        DisposeWindow(theWindow);
        if(gSavesPending)gSavesPending--;
        if(gSavesPending == 0 &&  gQuitting){
            // all the windows are closed, go away
            ExitToShell();
        }
        
        
    }
    
    
}
Boolean  PIWIndowHasFile(theWindow)
{Boolean retVal = 0;
WCH tempWC = (WCH)GetWRefCon(theWindow);
PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
if(nowCD->theFT )retVal = true;
return(retVal);
}

void DisposeCompareData(PIMainWDataP nowCD)
{diffByteRangePtr temp;
 diffByteRangePtr   nextOne = 0;
    if(nowCD->dataForkDiffs){   
        nextOne = nowCD->dataForkDiffs;
        do{
            temp = nextOne;
            nextOne = nextOne->next;
            free(temp);
        }while(nextOne);
        
    }
    nextOne  = 0;
    if(nowCD->resForkDiffs){   
        nextOne = nowCD->resForkDiffs;
        do{
            temp = nextOne;
            nextOne = nextOne->next;
            free(temp);
        }while(nextOne);
        
    }
    nowCD->resForkDiffs = 0;
    nowCD->dataForkDiffs=0;
    nowCD->currentDiffs=0;
 // see if there is a window
    if(nowCD->compDrawer ){
//  TO DO, get rid of the drawer nowcd;
        WCH ttWC = (WCH)GetWRefCon(nowCD->compDrawer);
        DiffDWDataP nnCD = (DiffDWDataP)(*ttWC)->dataStore;
        free(nnCD);
        DisposeHandle((Handle)ttWC);
        HideWindow(  nowCD->compDrawer);
        DisposeWindow(        nowCD->compDrawer);
    nowCD->compDrawer = 0;
    }

}

void docoreclose(WindowRef theWindow)
{    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    if(nowCD->theFT && nowCD->bookMarksDirty) SaveBookMarksForThisFile( nowCD->theFileNotes,nowCD->theFT);
    
    if(nowCD->theFT && (nowCD->theFT)->dataForkRef)
        FSCloseFork((nowCD->theFT)->dataForkRef);
    // and the res fork
    if(nowCD->theFT && (nowCD->theFT)->resForkRef)
        FSCloseFork((nowCD->theFT)->resForkRef);
    
    // kill off our varius alliickashuns
    if( nowCD->modBuffer)free(    nowCD->modBuffer );
    if( nowCD->startSel)free( nowCD->startSel);
    if(nowCD->displaying.fileBuffer)    free( nowCD->displaying.fileBuffer);
    if(nowCD->comparing.fileBuffer)free(nowCD->comparing.fileBuffer);
    if(nowCD->theFT) DisposeFileTracker(nowCD->theFT);
    DisposeHandle((*tempWC)->undoAction);
    // save off the val drawer divier line position if there is one.
    /****/
    // save the columnrights
    {   
        // save it.  
        // if this returns 0 then the position has not been changed.
        UInt16 hold = 0;
        if(nowCD->valueDrawer)
         hold=xxGiveMeDividerPosition(nowCD->valueDrawer)        ;
        
   if(hold) {
        CFDataRef   colDataRs = CFDataCreate (
                                              0,
                                              &hold,
                                             sizeof(hold)
                                              );
        CFStringRef colsrKey = CFSTR("ValDColRight");
        CFPreferencesSetAppValue(colsrKey, colDataRs,
                                 kCFPreferencesCurrentApplication);
    }
    }
    /*********/
    
    
    // have to dispose of the drawer now
    // ‚Ä¢‚Ä¢‚Ä¢ TO DO these are leaking memory
    // do not dispose this, the window manager is doing it already.  dont know why
    // but we do have to clean up the find window memory
if(nowCD->findDrawer)CleanFindWindowMemory(nowCD->findDrawer);
// need to do the same for the bookmakrwindw
    
    // make sure we clean up any compare stuff
// this is called when a new file to compare is added, also
    DisposeCompareData(nowCD);

    free(nowCD);
    DisposeHandle(tempWC);
    SetWRefCon(theWindow,0);
    
    
}
extern Boolean gStopQuitting;


NavAskSaveChangesResult ppreply;
NavDialogCreationOptions ppoptions;
NavDialogRef  ppoutDialog;

OSStatus PIMainWindowCloseCode(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
{
    OSStatus myStatus = noErr;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    // first see if the Find sheet is showing
    if(IsWindowVisible(nowCD->findDrawer)){
        HideSheetWindow(nowCD->findDrawer);
    }
    // close the file
    
    if( nowCD->changes && (nowCD->forkShowing != kPIMainShowingNoFork)){
        // dirty wannasave
        // eventually
        //        gStopQuitting = true;
        gSavesPending++;
        NavGetDefaultDialogCreationOptions(&ppoptions);
        ppoptions.modality = kWindowModalityNone; // kWindowModalityAppModal; // kWindowModalityWindowModal;
        ppoptions.parentWindow=theWindow;
        NavCreateAskSaveChangesDialog (
                                       &ppoptions,
                                       kNavSaveChangesClosingDocument ,  // NavAskSaveChangesAction inAction,
                                        PINavEventProc, //  NavEventUPP inEventProc,
                                       nowCD,
                                       &ppoutDialog
                                       );
        nowCD->savingChanges = true;
        NavDialogRun(ppoutDialog);
    } else {
        docoreclose(nowCD->us);
        
        if(inHandlerCallRef != nil && inEvent != 0)
            CallNextEventHandler(
                                 inHandlerCallRef,
                                 inEvent);
    }
    return(myStatus);
    
}



OSStatus InstallPIMainWindowHandlers(
                                     WindowRef theWindow,
                                     void * refCon,
                                     ULong flags)

{
    OSStatus myErr = noErr;
    long realRefCon = 0;
    EventHandlerRef windowOutRef;
    EventTypeSpec  windowDrawEventList[1]={{kEventClassWindow,kEventWindowDrawContent}};
    EventTypeSpec  windowConstrainEventList[1]={{kEventClassWindow,kEventWindowBoundsChanging}};
    
    EventTypeSpec  windowStateEventList[1]={{kEventClassWindow,kEventWindowActivated}};
    EventTypeSpec  windowDieStateEventList[1]={{kEventClassWindow,kEventWindowDeactivated}};

    
    
    EventTypeSpec  windowSizeEventList[1]={{kEventClassWindow,kEventWindowBoundsChanged}};
    EventTypeSpec  windowStartSizeEventList[1]={{kEventClassWindow,kEventWindowBoundsChanged}};
    
    EventTypeSpec  windowEndSizeEventList[1]={{kEventClassWindow,kEventWindowResizeCompleted}};
    EventTypeSpec  windowCloseEventList[1]={{kEventClassWindow,kEventWindowClose}};
    
    EventTypeSpec  windowSpecialEventList[1]={{kEventClassWindow,kEventWindowContextualMenuSelect}};
    
    EventTypeSpec  windowClickEventList[1]={   {kEventClassWindow,kEventWindowHandleContentClick}};
    EventTypeSpec  windowFocusEventList[1]={   {kEventClassWindow,kEventWindowFocusAcquired}};
    
    if(refCon == NULL)realRefCon = (long)theWindow;
    // we should collect all these event refs in the window data struct
    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(PIMainWindowDrawingCode),     sizeof(windowDrawEventList)/sizeof(EventTypeSpec),    &windowDrawEventList,     (void *)theWindow,   &windowOutRef);
    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(PIMainWindowSizeCode),     sizeof(windowSizeEventList)/sizeof(EventTypeSpec),    &windowSizeEventList, (void *)theWindow,      &windowOutRef);
    
    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(PIMainWindowCloseCode),     sizeof(windowCloseEventList)/sizeof(EventTypeSpec),    &windowCloseEventList, (void *)theWindow,      &windowOutRef);
    
    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(PIWWindowConstrainCode),     sizeof(windowConstrainEventList)/sizeof(EventTypeSpec),    &windowConstrainEventList, (void *)theWindow,      &windowOutRef);
    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(PIWWindowActivateCode),     sizeof(windowStateEventList)/sizeof(EventTypeSpec),    &windowStateEventList, (void *)theWindow,      &windowOutRef);
    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(PIWWindowDeActivateCode),     sizeof(windowDieStateEventList)/sizeof(EventTypeSpec),    &windowDieStateEventList, (void *)theWindow,      &windowOutRef);

    
    
    
    
    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(PIMainWindowFocusCode),     sizeof(windowFocusEventList)/sizeof(EventTypeSpec),    &windowFocusEventList, (void *)theWindow,      &windowOutRef);
    
    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(PIMainWindowSizeCode),     sizeof(windowSizeEventList)/sizeof(EventTypeSpec),    &windowSizeEventList, (void *)theWindow,      &windowOutRef);
    
    InstallKeyHandlers( theWindow);
    
    myErr = InstallStandardEventHandler(GetWindowEventTarget (theWindow));
    
    
    
    return(myErr);
    
}




void PIPasteFromClipboard(PIMainWDataP nowCD)
{


    Ptr scrapData=0;
    UInt32 finalSize;
    SInt64 endPos=0;
    UInt32 finalFlavor;
    ScrapRef  scrap;
    Size size = 0;
    Size byteSize = 0;
    if(nowCD->modifying == kModifying){

    GetCurrentScrap(&scrap);
    
    GetScrapFlavorSize(
                       scrap,
                       'TEXT',
                       &size);
    GetScrapFlavorSize(
                       scrap,
                       'byte',
                       &byteSize);
    if(size || byteSize)
    {
// now which?
        // prefer bytesize
        if(byteSize){
            finalSize = byteSize;
            finalFlavor = 'byte';
        }            else {
            finalSize = size;
            finalFlavor = 'TEXT';
        }
        scrapData = malloc(finalSize);
        GetScrapFlavorData(
                                     scrap,
                          finalFlavor,
                           &finalSize,
                           scrapData)  ;
        SInt64 forkLen;

#if 0
        if(nowCD->forkShowing==0){
            forkLen =nowCD->theFT->dataForkLen; 
        } else {
            forkLen =nowCD->theFT->resForkLen; 
            
        }
#endif
        switch(nowCD->forkShowing){	
            case kPIMainShowingDataFork:
                forkLen =nowCD->theFT->dataForkLen; 
                break;
            case kPIMainShowingResFork:
                forkLen =nowCD->theFT->resForkLen; 
                break;  
            case    kPIMainShowingNoFork:
                forkLen = kFileBufferSize;
                break;
        };
        // make sure we don't go too far
        endPos = (nowCD->startSel->totalPos+finalSize)-1; // since endPos is inclusive
        if(endPos > forkLen)endPos = forkLen-1;
        if(endPos>0){
         ChangeAByteRange(  nowCD,nowCD->startSel->totalPos,endPos ,scrapData,0, kPIChangeTypePaste,0);
            pimwMoveToThisByte( nowCD->us, endPos);
        }
         free(scrapData);
         
    }
    } else {
        /************/
        DialogRef                             outSheet;
        AlertStdCFStringAlertParamRec theRec;
        // bring a sheet down
        OSStatus myErr = 0;
        GetStandardAlertDefaultParams(&theRec,kStdCFStringAlertVersionOne);
//        theRec.cancelText=(CFStringRef)kAlertDefaultCancelText;
//        theRec.cancelButton=kAlertStdAlertCancelButton;

            myErr=    CreateStandardSheet(
                                          1,
                                          CFSTR("You have not enabled modifications."),
                                          CFSTR("You cannot paste until you enable file modifications by clicking the Modifiable radio button."),
                                          &theRec,
                                          GetWindowEventTarget( nowCD->us),
                                          &outSheet) ;
        myErr=           ShowSheetWindow(
                                         GetDialogWindow(outSheet),
                                         nowCD->us);
        /**************/
    }
    
}
void PICopyToClipboard(PIMainWDataP nowCD)
{
    Ptr dataRead;
    short readerForkRef = 0;
    SInt64 sizeRead;
    Size didRead;
    sizeRead =( nowCD->rangeEnd - nowCD->rangeStart) +1;
    // sanity check
    if(sizeRead > 10000){
        
        DialogRef outAlert;
        Str255 theStr = "\pCopy a great deal of data";
        Str255 theStr2 = "\pCancel";
        
        AlertStdCFStringAlertParamRec therec;
        short item;
        GetStandardAlertDefaultParams(&therec,kStdCFStringAlertVersionOne);
        therec.cancelText = CFStringCreateWithPascalString(0,theStr,0);
        therec.defaultText = CFStringCreateWithPascalString(0,theStr2,0);
        
        CreateStandardAlert(
                            1,
                            CFSTR("Very large range of data!"),
                            CFSTR("You've asked to copy more than 10,000 bytes to the clipboard.  Are you sure you want to do that?"),       /* can be NULL */
                                  &therec,             /* can be NULL */
                                  &outAlert); //     );
                            RunStandardAlert(outAlert,0,&item);
                            mSafeCFRelease(therec.cancelText);
                            mSafeCFRelease(therec.defaultText);
                            if(item == 1){
                                return;
        
                            }
    }
// read the current fork data into a seperate buffer    


{
#if 0    
if(nowCD->forkShowing == 0){
    readerForkRef =nowCD->theFT->dataForkRef; 
} else {
    readerForkRef =nowCD->theFT->resForkRef; 
    
    
}	
#endif

switch(nowCD->forkShowing){	
    case kPIMainShowingDataFork:
        readerForkRef =nowCD->theFT->dataForkRef; 
        break;
    case kPIMainShowingResFork:
        readerForkRef =nowCD->theFT->resForkRef; 
        break;  
    case    kPIMainShowingNoFork:
        readerForkRef = 0;
        break;
};	



if(readerForkRef){
dataRead = malloc(sizeRead);
  FSReadFork (readerForkRef,fsFromStart,  nowCD->rangeStart,
                      sizeRead,
                      dataRead,
                      &didRead
                      );

}
}



    ClearCurrentScrap();
    
    ScrapRef  scrap;

    GetCurrentScrap(&scrap);
    PutScrapFlavor(
                   scrap,
                   'TEXT',
                   kScrapFlavorMaskNone,
                   sizeRead,
                   dataRead);

PutScrapFlavor(
               scrap,
               'byte',
               kScrapFlavorMaskSenderOnly,
               sizeRead,
               dataRead);

}

void    SizePIMainWINDWithRef(CGContextRef cgContext, WindowRef theWindow,  EventRecord *theEvent, short how)
{

#pragma unused (theEvent )
    static Rect theRect = {0,0,0,0};
    Rect curRect;
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    
    mPushPort(theWindow)
        GetWindowPortBounds(theWindow,&curRect );
    if(!EqualRect(&theRect,&curRect)){
        theRect = curRect;
        CalcNumColumns(cgContext,theWindow);
        SizePIMainWINDControls(theWindow);
        
        CalcNumRows(theWindow);
        
        extern OSStatus UpdateCellPoses(piCell *theCell, PIMainWDataP nowCD);
        UpdateCellPoses(nowCD->startSel,  nowCD);
        pdoscrollto(nowCD);
        
    }
    mPullPort

}


Boolean PIHasRange(PIMainWDataP nowCD)
{Boolean retVal = false;
    if(nowCD->rangeStart != nowCD->rangeEnd && nowCD->rangeStart < nowCD->rangeEnd)retVal = true;
    return(retVal);
}
void PIRangeMark(PIMainWDataP nowCD,UInt32 which)
{
    switch(which){
        case kRangeStartCommand:        
            nowCD->rangeStart = nowCD->startSel->totalPos;
            break;
        case  kRangeEndCommand:
            nowCD->rangeEnd = nowCD->startSel->totalPos;

            break;
            case 'RNGC':
                nowCD->rangeStart = 0;
                nowCD->rangeEnd = 0;

                break;
    }
    HIViewSetNeedsDisplay(
                          nowCD->rawPane,
                          true);
    HIViewSetNeedsDisplay(
                          nowCD->transPane,
                          true);
 // and update the bottom thingus
        HIViewSetNeedsDisplay( nowCD->curPosThingie,true);
// and if the compate drawer is open
        if(nowCD->compDrawer){
            UpdateDiffViews(nowCD,nowCD->compDrawer);
        }
    
}

void  CommandPIMainWIND(WindowRef theWindow, EventRef inEvent,void *inUserData,HICommand *commandStruct)
{
    WindowRef oodWind = theWindow;
    MenuID theID;
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    char it[5];
    // switch on the command
    {Str255 theS;
        
        theS[0]=4;
        BlockMoveData((Ptr)&((commandStruct->commandID)),(Ptr)&theS[1],4);
        
    } 
    
    switch((commandStruct->commandID)){ 
        case 0:
            // shoudl be a menu
            // and we only have one, so
            if(commandStruct->menu.menuRef){
                // parse out by specific menus
                theID= GetMenuID(commandStruct->menu.menuRef);
                switch(theID){
 //                   case 700:
//                        OpenOpenRecent(commandStruct->menu.menuItemIndex);
//                        break;
                    case kNotePUMenuID:
                        bmPopUpItemPicked(nowCD,commandStruct->menu.menuItemIndex);
                        break;
                    case kNotesMenu:
                        
                        bmDoNotesMenu(nowCD,commandStruct->menu.menuItemIndex);
                        break;
                    case 801:  
                        bmPopUpItemPicked(nowCD,commandStruct->menu.menuItemIndex);
                        
                        break;
                    case 802:  // files with notes
                        DoBookMarkedFileMenu(commandStruct->menu.menuItemIndex);
                        
                        break;
                }
            }
            break;
        case kHICommandSaveAs:
            SaveFileAs(nowCD);
            break;
        case  kExportCommand:
            OuterExportFile(nowCD);
            break;            
        case kHICommandUndo:
            PIUndoLast(nowCD);
            break;
            // undo at selection
            case 'UNDS':
                PIUndoAtSelection(nowCD);
                break;
        case kHICommandCancel:
            if(nowCD->savingChanges){
                // cancel everything on a save
                nowCD->savingChanges = false;
                if(gSavesPending){gSavesPending--;
                    if(gQuitting)gQuitting = false;
                }
            }else{
//                PICancelSaveModifications(nowCD);
                if(gSavesPending)gSavesPending--;
                if(gQuitting)gQuitting = false;
            }
            
            break;
        case kHICommandOK:
            break;
        case 'othr':
            // just close
            docoreclose(nowCD->us);
            // and shut the window
            DisposeWindow(theWindow);
            if(gSavesPending)gSavesPending--;
                if(gSavesPending == 0 &&  gQuitting){
                    // all the windows are closed, go away
                    SpecialExit();
                }
                    
                    break;
        case 'BMPU':
            // just do a mad movetobyte thing
            // nah
            bmPopUpItemPicked(nowCD,commandStruct->menu.menuItemIndex);
            
            break;
            case kRangeStartCommand:
            case  kRangeEndCommand:
                case 'RNGC':
                PIRangeMark(nowCD, (commandStruct->commandID));
                
                break;
                case 'MODR':
                    PIModifyRange(theWindow,nowCD);
                    break;
                case kHICommandCopy:
                    PICopyToClipboard(nowCD);
                    break;
                    case kHICommandPaste:
                        PIPasteFromClipboard( nowCD);

                        break;
        default:
#ifndef __FINAL__
            DebugStr("\p command in PIMain window defaulted, was");
            BlockMoveData(   (Ptr)&commandStruct->commandID ,(Ptr)&it[1],4);
            DebugStr(it);
            
            
            
#endif
            break;
    }
    
}
void GenPIMainWIND(WindowRef theWindow, UShort selector, void *theData)
{
#pragma unused (theWindow,theData )
    OSStatus myErr;
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    WindowPrefStructHdl thePrefs;
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    LoopVar qq;
    switch (selector) {
case kwmgRevert:
    pmwindDoRevert(nowCD);
        break;
        case kwmgPrintWindow:
            AddPrintWSheetWIND(theWindow,0);
            break;
        case            kwmgPrintPageSetupWindow:
            DoPIPageSetup(nowCD-> pageFormat);
            
            
            break;
            
        case kwmgSetUpMenus:
            SetUpPIMainWindowMenus(nowCD,theData);
            
            break;
        case kMenuGeneral:
            break;
        case kwmgActContHit:
            // coming forward mouse hit, so use it as well
            SetPort(theWindow);
            HitPIMainWIND( theWindow,nil);
            break;
        case kwmgHaveChangesQuery:
            break;
        case kwmgUpdatePrefs:
            
            
            // stuff the current stuff in the stuff
            //now stuff the other stuff
            break;
        case kwmgUpdateViews:
            // have to redraw the views
            HIViewSetNeedsDisplay(
                                  nowCD->rawPane,
                                  true);
            HIViewSetNeedsDisplay(
                                  nowCD->transPane,
                                  true);
            if(nowCD->compDrawer){
                UpdateDiffViews(nowCD,nowCD->compDrawer);
            }
                
            // change the metallic state gumba
            if(        gAddPrefs.windowFlags&  kWindowMetalFlag)
                MakeWindowMetal(theWindow,true);
            else
                MakeWindowMetal(theWindow,false);
            
            if(gAddPrefs.windowFlags & kWindowHexFlag)
                    nowCD->    drawingPosAs = kDrawingAddyInHex;
                else
                     nowCD->    drawingPosAs = kDrawingAddyInDec;

            
            break;
        case	kGenFindCommand:
            myErr=  ShowSheetWindow(
                                    nowCD->findDrawer,
                                    theWindow);
            
            break;
        case kGoToByteCommand:
        {extern WindowRef AddGoToBWIND(WindowRef theWindow,SInt64 largest);
            
            SInt64 theTrueLen ;
            switch(nowCD->forkShowing){	
                case kPIMainShowingDataFork:
                    theTrueLen =nowCD->theFT->dataForkLen; 
                    break;
                case kPIMainShowingResFork:
                    theTrueLen =nowCD->theFT->resForkLen; 
                    break;  
                case    kPIMainShowingNoFork:
                    theTrueLen = kFileBufferSize;
                    break;
            };
            
            
            
            
            
            AddGoToBWIND( theWindow,theTrueLen);
        }
            break;
        case kToggleAddressViewCommand:
            SwitchAddyView(theWindow,nowCD);
            break;
        case kFindAgainCommand:
            pimwDoFindAgain(theWindow,nowCD);
            break;
            
        case kFindNotCommand:
            break;
        case kFindNotAgainCommand:
            break;
            
        case            kChooseFontCommand: 
            break;
        case kSetDefWindSizeCommand:
            SnapshotWindowSize(theWindow,nowCD);

            break;
        case kFontBiggerCommand: 
            nowCD->fontSize ++;
            if(nowCD->fontSize > 20)nowCD->fontSize = 20;
                CalcNumColumns(0, theWindow);
            HIViewSetNeedsDisplay(
                                  nowCD->rawPane,
                                  true);
            HIViewSetNeedsDisplay(
                                  nowCD->transPane,
                                  true);
            if(nowCD->compDrawer){
                UpdateDiffViews(nowCD,nowCD->compDrawer);
            }
                
            TellValWindowAboutChange(nowCD->valueDrawer);
            break;
        case kFontSmallerCommand:
            nowCD->fontSize--;
            if(nowCD->fontSize < 9)nowCD->fontSize = 9;
                CalcNumColumns(0, theWindow);
            HIViewSetNeedsDisplay( 
                                   nowCD->rawPane,
                                   true);
            HIViewSetNeedsDisplay( 
                                   nowCD->transPane,
                                   true);
            if(nowCD->compDrawer){
                UpdateDiffViews(nowCD,nowCD->compDrawer);
            }
                
            TellValWindowAboutChange(nowCD->valueDrawer);
            
            break;
        case kToggleValueDrawer:

            ToggleDrawer(nowCD->valueDrawer);
            
            break;
        case            kCompFile:
            PIMainCompareFileStart(theWindow,nowCD,0);
            break;
        case kCompNextDiff:
            PIMainGotoNextDiff(theWindow,nowCD,0);
            break;
        case kDoSaveChangesFile:
            PIMakeChangesFile( nowCD);
            
            break;
        case kDoApplySaveChangesFile:
            PIApplyChangesFile(nowCD);
            break;
        case kwmgSelectionChanged:
            bmUpdateNoteButtonStates(theWindow);
            // and force the notes window to redisplete
            bmUpdateNotePane(theWindow);
            TellValWindowAboutChange(nowCD->valueDrawer);
            break;
            
            
    }
}

static  OSStatus PIValueDrawerEventHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
/*
enum {
kPINewMainWindowNoFile = 0x1
};
*/
#pragma mark creation
WindowRef CreateOrShowPIMainWIND(FileTrackerPtr theFile, Boolean vis,Boolean newWindow,UInt32 newFlags)
{
    HFSUniStr255 outName;
    Rect temper;
    
    LoopVar qq;
    WindowPrefStructHdl thePrefs=nil;
    WCH tempWC;
    Boolean dontOpen = false;
    PIMainWDataP nowCD;
    OSErr myErr = 0;
    AliasHandle theA;
    short newID;
    WindowRef PIMainWINDWindow = nil;
    
    EventTypeSpec	colControlEvents[] =    {		{ kEventClassControl, kEventControlHit },    {kEventClassControl,    kEventControlDraw},    {kEventClassControl,    kEventControlClick}    };
    EventTypeSpec	posControlEvents[] =    {    {kEventClassControl,    kEventControlDraw}    };
    EventTypeSpec	scrollControlEvents[] ={   {kEventClassControl,    kEventControlHit}    };
    EventTypeSpec	hexBoxControlEvents[] ={    {kEventClassControl,    kEventControlHit}    };
    
    PIMainWINDWindow = PIIsFileOpenYet(theFile);
    if(PIMainWINDWindow){
        ShowWindow(PIMainWINDWindow);
        SelectWindow(PIMainWINDWindow);
        
        return(PIMainWINDWindow);
    }
    
    
    
    myErr = CreateWindowFromNib(gNibRef, CFSTR("MainWindow"), &PIMainWINDWindow);
    
    // NEW
    if(     gAddPrefs.windowFlags&  kWindowMetalFlag)
        MakeWindowMetal(PIMainWINDWindow,true);
    else 
        MakeWindowMetal(PIMainWINDWindow,false);
    
    
    
    tempWC = (WCH)NewHandleClear(sizeof(windowControl));
    
    SetWindowKind(PIMainWINDWindow, kPIMainWINDWindow);
    nowCD = (PIMainWDataP)calloc(1,sizeof(PIMainWindData)); // NewHandleClear(sizeof(PIMainWindData));
//    ZeroPtr((Ptr)nowCD,sizeof(PIMainWindData));
    (*tempWC)->undoAction = (UndoHand)NewHandleClear(sizeof(UndoControl));
    (*tempWC)->dataStore = (Ptr)nowCD;
    (*tempWC)->dataStore2 = 0;
    InstallPIMainWindowHandlers(PIMainWINDWindow,0,0);
    
    
    (*tempWC)->helpHint = nil;
    (*tempWC)->lastID = 0;
    (*tempWC)->selectionRect.top = 0;
    (*tempWC)->selectionRect.left = 0;
    (*tempWC)->selectionRect.bottom = 0;
    (*tempWC)->selectionRect.right = 0;
    (*tempWC)->currentAction = 0;
    
    
    (*tempWC)->windowSizeBounds.top=-1;
    (*tempWC)->windowSizeBounds.left= -1;
    (*tempWC)->windowSizeBounds.bottom= -1;
    (*tempWC)->windowSizeBounds.right= -1;
    
    (*tempWC)->contentInset.top= -1;
    (*tempWC)->contentInset.left= -1;
    (*tempWC)->contentInset.bottom= -1;
    (*tempWC)->contentInset.right= -1;
    
    
    (*tempWC)->toolBarWide;                                      /* don't know if this is perm or not */
    (*tempWC)->arrowAmount;
    (*tempWC)->pageAmount;
    (*tempWC)->maxContentHi;
    (*tempWC)->maxContentWide;
    (*tempWC)->auxControls=0;
    (*tempWC)->hasSelection=false;                                   /* is there a selection? */
    (*tempWC)->windowDirty=false;
    (*tempWC)->windAlias=0;
    (*tempWC)->refNum=0;			// this does have to be here
    (*tempWC)->windowName[0]=0;
    
    
    
    
    SetWRefCon(PIMainWINDWindow, (long)tempWC);
    
    
    tempWC = (WCH)GetWRefCon((WindowRef)PIMainWINDWindow);
    nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    
    
    AddWindowID(PIMainWINDWindow);
    
    /* set these goddam things */
    //    (*tempWC)->drawMe = DrawPIMainWIND;
       (*tempWC)->generalMe = GenPIMainWIND;
    (*tempWC)->commandMe = CommandPIMainWIND;
        (*tempWC)->closeMe = ClosePIMainWIND;
    // new way Jose
    
    
    nowCD->modifying = kNotModifying;
    nowCD->editingAs =kEditingAsAscii; // kEditingAsHex;  maybe make this a pref
    if(newFlags & kPINewMainWindowNoFile)
        nowCD->noFile = true;
    // font info
    nowCD->fontSize = gDefaultFontSize;
    
    nowCD->posPane = SnatchCRef(PIMainWINDWindow,'PEEK',kPeekPosPane);
    nowCD->readOnlyPane = SnatchCRef(PIMainWINDWindow,'PEEK',kPeekReadOnlyPane);
    HideControl(nowCD->readOnlyPane);
    InstallControlEventHandler(  nowCD->posPane,  PIPosPaneEventHandlerProc , GetEventTypeCount(posControlEvents), posControlEvents, PIMainWINDWindow, NULL );
    
    nowCD->curPosThingie= SnatchCRef(PIMainWINDWindow,'PEEK',kPeekCurrentPosPane);
    InstallControlEventHandler(   nowCD->curPosThingie,  PICurFilePosPaneEventHandlerProc , GetEventTypeCount(posControlEvents), posControlEvents, PIMainWINDWindow, NULL );
    
    
    
    InstallControlEventHandler(  nowCD->readOnlyPane,  PIReadOnlyPaneEventHandlerProc , GetEventTypeCount(posControlEvents), posControlEvents, PIMainWINDWindow, NULL );
    
    
    nowCD->oldNumColumns = 0;
    nowCD->rawPane = 0;
    nowCD->transPane = 0;
    nowCD->rawScroll = SnatchCRef(PIMainWINDWindow,'PEEK',kPeekItRawScroll);
    nowCD->transScroll = SnatchCRef(PIMainWINDWindow,'PEEK',kPeekItTransScroll);
    nowCD->infoCont = SnatchCRef(PIMainWINDWindow,'PEEK',kInfoDiscTriangle);
    nowCD->hexCont = SnatchCRef(PIMainWINDWindow,'PEEK',kPeekShowHexCheck);
    nowCD->modifiRadio = SnatchCRef(PIMainWINDWindow,kPeekItID,kPeekModifiableRadio);    
    nowCD->hexEditBox = SnatchCRef(PIMainWINDWindow,'PEEK',kPeekHexEditBox);
    nowCD->dataForkRadio = SnatchCRef(PIMainWINDWindow,'PEEK',kPeekDataForkRadio);
    nowCD->resForkRadio= SnatchCRef(PIMainWINDWindow,'PEEK',kPeekResForkRadio);
    nowCD->forkShowing = 0; // data fork
    
    // this will be a pref  LOOOK! It is now
    nowCD->showingHex = true; // gPrefs.showHex;
    SetControlValue(nowCD->hexCont,nowCD->showingHex);
    nowCD->modBuffer = malloc(kFileBufferSize);
    for(qq=0;qq<kFileBufferSize;qq++)*(nowCD->modBuffer+qq) = 0;

    nowCD->startSel = calloc(1,sizeof(piCell));
    nowCD->selections[0]=calloc(1,sizeof(piCell));    
    nowCD->selections[1]=calloc(1,sizeof(piCell));
    nowCD->endSelections[0]=calloc(1,sizeof(piCell));    
    nowCD->endSelections[1]=calloc(1,sizeof(piCell));
    
    ZeroCell(nowCD->startSel); 
    
    nowCD->changes = nil; // starts with no changes 
    nowCD->lastFindPtr = nil;
    nowCD->bookMarksDirty = false;
    nowCD-> theFileNotes=0;
    nowCD->currentNote=0;
    nowCD->preload = 0;
    nowCD->nextNoteIsAtByte=0xFFFFFFFFFFFFFFFF;  
    
    nowCD->pageFormat =  ReturnCurrentPageFormat();
    
    InstallControlEventHandler(  nowCD->infoCont,  PIDiscTriEventHandlerProc , GetEventTypeCount(scrollControlEvents), scrollControlEvents, PIMainWINDWindow, NULL );
    InstallControlEventHandler(  nowCD->hexCont,  PIDiscHexEventHandlerProc , GetEventTypeCount(scrollControlEvents), scrollControlEvents, PIMainWINDWindow, NULL );
    InstallControlEventHandler(  nowCD->modifiRadio,  PIModifiRadioHandlerProc , GetEventTypeCount(scrollControlEvents), scrollControlEvents, PIMainWINDWindow, NULL );
    
    InstallControlEventHandler(  nowCD->dataForkRadio,  PIResAndDataRadioHandlerProc , GetEventTypeCount(scrollControlEvents), scrollControlEvents, PIMainWINDWindow, NULL );
    InstallControlEventHandler(  nowCD->resForkRadio,  PIResAndDataRadioHandlerProc , GetEventTypeCount(scrollControlEvents), scrollControlEvents, PIMainWINDWindow, NULL );
    
    
    
    
    InstallControlEventHandler( SnatchCRef(PIMainWINDWindow,'PEEK',kPeekEnterHexOrASCII),  PIHexOrAsciiHandlerProc , GetEventTypeCount(scrollControlEvents), scrollControlEvents, PIMainWINDWindow, NULL );
    nowCD->editAsRadio=SnatchCRef(PIMainWINDWindow,'PEEK',kPeekEnterHexOrASCII);
    // hide the modification box at first
    HideControl( SnatchCRef(PIMainWINDWindow,'PEEK',kPeekHexEditBox));
    DisableControl( SnatchCRef(PIMainWINDWindow,'PEEK',kPeekHexEditBox));
    ClearKeyboardFocus(PIMainWINDWindow);
    
    HideControl( SnatchCRef(PIMainWINDWindow,'PEEK',kPeekHexEditWords));
    HideControl(SnatchCRef(PIMainWINDWindow,'PEEK',kPeekApplyEditButt));
    
    // new control for hex vs ascii input
    HideControl( SnatchCRef(PIMainWINDWindow,'PEEK', kPeekEnterHexOrASCII));
    HideControl( SnatchCRef(PIMainWINDWindow,'PEEK', kPeekEnterASCIIWords));
    
    
    DisableControl(SnatchCRef(PIMainWINDWindow,'PEEK',kPeekNextChange));
    
    
    InstallControlEventHandler(  nowCD->hexEditBox,  PIHexBoxEventHandlerProc , GetEventTypeCount(hexBoxControlEvents), hexBoxControlEvents, PIMainWINDWindow, NULL );
    InstallControlEventHandler( SnatchCRef(PIMainWINDWindow,'PEEK',kPeekNextChange),  PINextChangeEventHandlerProc , GetEventTypeCount(hexBoxControlEvents), hexBoxControlEvents, PIMainWINDWindow, NULL );
    InstallControlEventHandler( SnatchCRef(PIMainWINDWindow,'PEEK',kPeekValDrawerToggle),  PIValueDrawerEventHandlerProc , GetEventTypeCount(hexBoxControlEvents), hexBoxControlEvents, PIMainWINDWindow, NULL );
    
     OpenPIStrings( nowCD);

    
    
    {
        EventTypeSpec	PIScrollToControlEvents[] =
    {
    {kEventClassControl,    kEventControlHit}
    };
        
        InstallControlEventHandler( SnatchCRef(PIMainWINDWindow,'PEEK',kPeekScrollTo),  PIPIScrollToEventHandlerProc , GetEventTypeCount(scrollControlEvents), PIScrollToControlEvents, PIMainWINDWindow, NULL );
    }
    
    {
        EventTypeSpec	PIApplyControlEvents[] =
    {
    {kEventClassControl,    kEventControlHit}
    };
        
        InstallControlEventHandler( SnatchCRef(PIMainWINDWindow,'PEEK',kPeekApplyEditButt),  PIPIApplyEventHandlerProc , GetEventTypeCount(scrollControlEvents), PIApplyControlEvents, PIMainWINDWindow, NULL );
    }
    {
        EventTypeSpec	PIApplyControlEvents[] =
    {
    {kEventClassControl,    kEventControlHit}
    };
        
        InstallControlEventHandler( SnatchCRef(PIMainWINDWindow,'PEEK',kPeekRevertButton),  PIRevertHandlerProc , GetEventTypeCount(scrollControlEvents), PIApplyControlEvents, PIMainWINDWindow, NULL );
    }
    {
        EventTypeSpec	PIApplyControlEvents[] =
    {
    {kEventClassControl,    kEventControlHit}
    };
        
        InstallControlEventHandler( SnatchCRef(PIMainWINDWindow,'PEEK',kPeekCommitButton),  PICommitHandlerProc , GetEventTypeCount(scrollControlEvents), PIApplyControlEvents, PIMainWINDWindow, NULL );
    }
    MenuRef theMenu;
    UInt16 itemNumber =  GetMenuCommandItemNumberAndMenu('VEWH',&theMenu);

    
    if(gAddPrefs.windowFlags & kWindowHexFlag){
        nowCD->    drawingPosAs = kDrawingAddyInHex;
        SetMenuItemText(
                        theMenu,
                        itemNumber,
                        "\pView positions as Decimal") ;
    }else{
        nowCD->    drawingPosAs = kDrawingAddyInDec;
        SetMenuItemText(
                        theMenu,
                        itemNumber,
                        "\pView positions as Hex") ;
    }
    
    /**********/
    // note section initializers
    InitNoteSection(PIMainWINDWindow, nowCD);
    
    /***********/
    InstallControlEventHandler(  nowCD->rawScroll,  PIScrollBarEventHandlerProc , GetEventTypeCount(scrollControlEvents), scrollControlEvents, PIMainWINDWindow, NULL );
    InstallControlEventHandler(  nowCD->transScroll,  PIScrollBarEventHandlerProc , GetEventTypeCount(scrollControlEvents), scrollControlEvents, PIMainWINDWindow, NULL );
    // and a live scroller
    SetControlAction ( nowCD->transScroll,
                       NewControlActionUPP(liveScroller2));
    
    SetControlAction ( nowCD->rawScroll,
                       liveScroller);
    nowCD->us = PIMainWINDWindow;
    // and circle the references please
    nowCD->   theWCH= tempWC;
    GetControlBounds(nowCD->transScroll,&temper);
    nowCD->scrollWide = temper.right-temper.left;
    
    
    
    RestoreWindowVitalStats(PIMainWINDWindow,CFSTR("STANDARDSTATE"));

    // default ullage
    nowCD->ullage = kPaneSpace+(kPosWide /* nowCD->posWide*/)+(nowCD->scrollWide * 2) +10; // the last 10 is the right border
    CalcNumColumns(0, PIMainWINDWindow);
    // moved sizing to later
    
    nowCD->displaying.fileBuffer = 0;
    // now set up the panes
    PIPanesViewCreate(                              PIMainWINDWindow );
    // add control IDs.  Why?  Dunno.  Then don't do it.  well, nevermind
    {  const ControlID	kCalendarID = { 'PEEK', 9023 };
        const ControlID	kCalendarID2 = { 'PEEK', 9024 };
        SetControlID( nowCD->rawPane, &kCalendarID );
        SetControlID( nowCD->transPane, &kCalendarID2 );
        ShowControl(nowCD->rawPane);
        ShowControl(nowCD->transPane);
        
    }
    // much later
    
    
    /*************/
    // if there is an FT,  open the file
    if(theFile){
        OSStatus fileErr = noErr;
        // set it up
        theFile->openDataFork = true;
        theFile->dataForkPerm=fsRdWrPerm;
        // optionally open the resource fork?  Or just open it if it exists and set a flag to display
        theFile->openResFork = true;
        theFile->resForkPerm=fsRdWrPerm;
        
        // get some infos
        fileErr=        OpenFile(theFile);
        
        if(fileErr == noErr){
            nowCD->theFT = theFile;
 // see if there is both or just one fork
            if(theFile->dataForkLen == 0 || theFile->resForkLen == 0){
                // disable the radio buttons
                DisableControl(nowCD->dataForkRadio);
                DisableControl(nowCD->resForkRadio);
                // if datafork is 0 and resfork non-zero, then go thither
                if(theFile->dataForkLen == 0 || theFile->resForkLen != 0){
                    nowCD->forkShowing =1;
                    SetControlValue(SnatchCRef(PIMainWINDWindow,'PEEK',kPeekDataForkRadio),0);
                    SetControlValue(SnatchCRef(PIMainWINDWindow,'PEEK',kPeekDataForkRadio+1),1);
                }
            }
            
            // allocate some memry and stuff
            nowCD->displaying.fileBuffer=malloc(kFileBufferSize); // 10k
            nowCD->displaying.bufStartInFile=0;
            nowCD->displaying.bufEndInFile=kFileBufferSize;
            nowCD->displaying.offsetInBuffer=0;
            nowCD->displaying.posInFile = 0;
            nowCD->comparing.fileBuffer=malloc(kFileBufferSize); // 10k
            nowCD->comparing.bufStartInFile=0;
            nowCD->comparing.bufEndInFile=kFileBufferSize;
            nowCD->comparing.offsetInBuffer=0;
            nowCD->comparing.posInFile = 0;
            
            
            {
                SInt16 forkRef ;
#if 0
                if(nowCD->forkShowing==0){
                    forkRef =theFile->dataForkRef; 
                } else {
                    forkRef =theFile->resForkRef; 
                    
                }
#endif
                switch(nowCD->forkShowing){	
                    case kPIMainShowingDataFork:
                        forkRef =theFile->dataForkRef; 
                        break;
                    case kPIMainShowingResFork:
                        forkRef =theFile->resForkRef; 
                        break;  
                    case    kPIMainShowingNoFork:
                        forkRef = 0;
                        break;
                };

                
                if(forkRef){
                FSReadFork (
                            forkRef,
                            fsFromStart,
                            0,
                            kFileBufferSize,
                            nowCD->displaying.fileBuffer,
                            0   // change this
                            );}}
            // set the initial values of the two scroll bars (which should always be locked together
            SetScrollValues(nowCD,0);
            
            // set the windw proxy to this file hehehe.
            SetWindowModified (
                               PIMainWINDWindow,
                               false
                               );
            
            
            
            
            if(theFile->fsSpecIsValid){
                SetWindowProxyFSSpec(
                                     PIMainWINDWindow,
                                     theFile->fsSpec);
                
                SetWTitle(PIMainWINDWindow,theFile->fsSpec->name);
                
            }
     }
        // dammit, have to double if it
        if(fileErr){
            if(fileErr == opWrErr || fileErr == permErr){
                // tell em an error happened
                // try and open it read-only
                
                DialogRef outAlert;
                Str255 theStr = "\pOpen Read-only";
                Str255 theStr2 = "\pCancel";
                
                AlertStdCFStringAlertParamRec therec;
                short item;
                GetStandardAlertDefaultParams(&therec,kStdCFStringAlertVersionOne);
                therec.cancelText = CFStringCreateWithPascalString(0,theStr,0);
                therec.defaultText = CFStringCreateWithPascalString(0,theStr2,0);
                
                CreateStandardAlert(
                                    1,
                                    CFSTR("Unable to open file."),
                                    CFSTR("The file is read-only, on a locked volume, or something I can't open for modification."),       /* can be NULL */
                                          &therec,             /* can be NULL */
                                          &outAlert); //     );
                                    RunStandardAlert(outAlert,0,&item);
                                    mSafeCFRelease(therec.cancelText);
                                    mSafeCFRelease(therec.defaultText);
                                    if(item == 2){
                                        /***************/
                                        OSStatus fileErr = noErr;
                                        // set it up
                                        theFile->openDataFork = true;
                                        theFile->dataForkPerm=fsRdPerm;
                                        theFile->openResFork = true;
                                        theFile->resForkPerm=fsRdPerm;
                                        // get some infos
                                        fileErr=        OpenFile(theFile);
                                        if(fileErr == noErr){
                                            nowCD->theFT = theFile;
#if 0
                                            nowCD->fsCatInfo = malloc(sizeof(FSCatalogInfo));
                                            FSGetCatalogInfo(                             theFile->fsRef,                            kFSCatInfoGettableInfo,
                                                                                          nowCD->fsCatInfo,       /* can be NULL */
                                                                                          0,           /* can be NULL */
                                                                                          0,            /* can be NULL */
                                                                                          0);
#endif                                        
                                            nowCD->modifying = kReadOnly;
                                            HideControl(nowCD->modifiRadio );
                                            ShowControl(nowCD->readOnlyPane);
                                            // allocate some memry and stuff
                                            nowCD->displaying.fileBuffer=malloc(kFileBufferSize); // 10k
                                            nowCD->displaying.bufStartInFile=0;
                                            nowCD->displaying.bufEndInFile=kFileBufferSize;
                                            nowCD->displaying.offsetInBuffer=0;
                                            nowCD->displaying.posInFile = 0;
                                            nowCD->comparing.fileBuffer=malloc(kFileBufferSize); // 10k
                                            nowCD->comparing.bufStartInFile=0;
                                            nowCD->comparing.bufEndInFile=kFileBufferSize;
                                            nowCD->comparing.offsetInBuffer=0;
                                            nowCD->comparing.posInFile = 0;
                                            
                                            
                                            {
                                                SInt16 forkRef ;
#if 0                                                
                                                if(nowCD->forkShowing==0){
                                                    forkRef =theFile->dataForkRef; 
                                                } else {
                                                    forkRef =theFile->resForkRef; 
                                                    
                                                }
                                                
#endif
                                                switch(nowCD->forkShowing){	
                                                    case kPIMainShowingDataFork:
                                                        forkRef =theFile->dataForkRef; 
                                                        break;
                                                    case kPIMainShowingResFork:
                                                        forkRef =theFile->resForkRef; 
                                                        break;  
                                                    case    kPIMainShowingNoFork:
                                                        forkRef = 0;
                                                        break;
                                                };
                                                if(forkRef){
                                                FSReadFork (
                                                            forkRef,                                                 fsFromStart,
                                                            0,
                                                            kFileBufferSize,
                                                            nowCD->displaying.fileBuffer,
                                                            0   // change this
                                                            );}
                                            }
                                            // set the initial values of the two scroll bars (which should always be locked together
                                            SetScrollValues(nowCD,0);
                                            
                                            // set the windw proxy to this file hehehe.
                                            SetWindowModified (
                                                               PIMainWINDWindow,
                                                               false
                                                               );
                                            
                                            
                                            
                                            
                                            if(theFile->fsSpecIsValid){
                                                SetWindowProxyFSSpec(
                                                                     PIMainWINDWindow,
                                                                     theFile->fsSpec);
                                                
                                                SetWTitle(PIMainWINDWindow,theFile->fsSpec->name);
                                            }}
                                        /**************/
                                        
                                        
                             } else {
                                 dontOpen = true;
                             }
                                    
                                    
     } else {
         // not a locked file, so just whine
         DialogRef outAlert;
         short item;
         
         CreateStandardAlert(
                             1,
                             CFSTR("Unable to open file."),
                             CFSTR("Try another file, or move the file to a different folder or volume and try again."),       /* can be NULL */
                                   0,             /* can be NULL */
                                   &outAlert); //     );
                             RunStandardAlert(outAlert,0,&item);
                             dontOpen = true;
                             
                             
     }

}
     } else {
         
         // failure to get an FT
         if(nowCD->noFile == false){
         // no file and we were expecting a file
             dontOpen = true; 
         } else {
         // no file and that's OK
             SetWTitle(
                       PIMainWINDWindow,
                       "\pNo file");
             nowCD->modifying =             kModifying;
             nowCD->forkShowing=kPIMainShowingNoFork;
             DisableControl(nowCD->dataForkRadio);
             DisableControl(nowCD->resForkRadio);
             SetControlValue(SnatchCRef(PIMainWINDWindow,'PEEK',kPeekDataForkRadio),0);
             SetControlValue(SnatchCRef(PIMainWINDWindow,'PEEK',kPeekDataForkRadio+1),1);
             SetControlValue(nowCD->modifiRadio,2);
             nowCD->displaying.fileBuffer=malloc(kFileBufferSize); // 10k
             nowCD->displaying.bufStartInFile=0;
             nowCD->displaying.bufEndInFile=kFileBufferSize;
             nowCD->displaying.offsetInBuffer=0;
             nowCD->displaying.posInFile = 0;
             
         }
         
         
     }

/***/
if(dontOpen){
    docoreclose(PIMainWINDWindow);
    DisposeWindow(PIMainWINDWindow);
    PIMainWINDWindow = 0;
    
} else {
    // this is NOT right, the sheets should be added even if the window is not visible.  Fix this when you use it
    if (vis ) {
        OSStatus tellMe;
        // add the value drawer
        nowCD->valueDrawer = AddPIValueDrawer(PIMainWINDWindow);

        // add a find drawer
       nowCD->findDrawer = AddFindWIND( PIMainWINDWindow,theFile);
        nowCD->commitSheet = AddCommitWIND( PIMainWINDWindow,theFile);
        // add the bookmarks
       if(nowCD->noFile==0){
           AddToRecentMenu(nowCD->theFT );

           nowCD->bmarkWindow =  AddBMarkWind( PIMainWINDWindow,theFile);
        // add the marks
        nowCD->theFileNotes= GetBookMarksForThisFile(nowCD->theFT );
        if( nowCD->theFileNotes){
            PIBRebuildNoteMenu(PIMainWINDWindow);
            
        }
       }
        
        HMInstallControlContentCallback (
                                         nowCD->rawPane, 
                                         NewHMControlContentUPP(PIPaneWindowPaneHelpContentCallback)
                                         );
        HMInstallControlContentCallback (
                                         nowCD->transPane, 
                                         NewHMControlContentUPP(PIPaneWindowPaneHelpContentCallback)
                                         );
        
        ShowWindow(PIMainWINDWindow);
        // insert a standard window size
        UpdateAllValDrawerPopups();
        
        HIViewSetNeedsDisplay(
                              nowCD->rawPane,
                              true);
        HIViewSetNeedsDisplay(
                              nowCD->transPane,
                              true);
            CalcNumColumns(0, PIMainWINDWindow);
        
        SizePIMainWINDControls(PIMainWINDWindow);
        CalcNumRows(PIMainWINDWindow);
        if(nowCD->compDrawer){
            UpdateDiffViews(nowCD,nowCD->compDrawer);
        }
        
        
        {                ScrapRef  scrap;            Size size = 0;            Size byteSize = 0;            GetCurrentScrap(&scrap);                        GetScrapFlavorSize(                               scrap,                               'TEXT',                               &size);            GetScrapFlavorSize(                               scrap,                               'byte',                               &byteSize);            if(size || byteSize)            {                EnableMenuCommand(0,kHICommandPaste);                            }else {                DisableMenuCommand(0,kHICommandPaste);}        }
        
    }}

return(PIMainWINDWindow);
}



// size scroll bar and text area
// taking the popup out now
// switching hex and ascii entry boogies
// 9.21.03 making mod buttonsalways visible
UInt16 CalculateMaxPosTextWidth(PIMainWDataP nowCD)
{UInt16 width = 53;

if(nowCD->calcedNewPosWidth){
width = nowCD->calcedNewPosWidth;
}
// pad it a little
width +4;

nowCD->posWide =  width-10;
 nowCD->ullage = kPaneSpace+(nowCD->posWide)+(nowCD->scrollWide * 2) +10; 
return(width);
}
#pragma mark Sizing
static void SizePIMainWINDControls(WindowRef theWindow)
{
#pragma unused (theWindow )
    // see if we can change the menu position by mussing with the rect
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    
    Rect newRect,scrollRect,wRect,tempContRect;
    short scrollWide,scrollMid;
    short bottomOfPanes,rightOfScroll;
    short botFromButt = 10;
    UInt16 halfOfRawPane = 0;
    short distFromWinBott = 100;
    ControlRef theRef;
    UInt32 theVal = GetControl32BitValue(nowCD->rawScroll);
    theVal = theVal *   nowCD->numColumns;
    
    
    // see if info is showing
    
    if(nowCD->infoShowing)
        distFromWinBott = distFromWinBott + kInfoPaneSize;
    // nowCD->infoPaneStarts
    
    // set up the info pane
    
    
    mPushPort(theWindow)
        GetWindowPortBounds(theWindow,&wRect );
    bottomOfPanes = wRect.bottom - distFromWinBott;
    newRect.right =  CalculateMaxPosTextWidth(nowCD); // was 57;
    newRect.top =24;  newRect.left = 0 ; // trying  a new way
    
    newRect.bottom = bottomOfPanes;
    SetControlBounds(
                     nowCD->posPane,
                     &newRect);
    
    // set the widths of the panes
    
    newRect.top =24;  newRect.left = CalculateMaxPosTextWidth(nowCD)+1;  // was 58 ; // trying  a new way
    newRect.right = newRect.left + (nowCD->columnWidth * nowCD->numColumns);
    newRect.bottom = bottomOfPanes;
    
    nowCD->rawTargetRect = newRect;
    halfOfRawPane = (newRect.right - newRect.left)/2;
    
    GetControlBounds(
                     nowCD->rawScroll,
                     &scrollRect);
    
    scrollWide = scrollRect.right-scrollRect.left;
    scrollRect.left = newRect.right+1;
    scrollRect.right = scrollRect.left + scrollWide;
    scrollRect.bottom = bottomOfPanes;
    SetControlBounds(
                     nowCD->rawScroll,
                     &scrollRect);
    
    rightOfScroll = scrollRect.right;
    
    // show hex checkbox, put this where the rawradios usta b.  Huh, it just happens
    
    GetControlBounds(
                     nowCD->hexCont,
                     &scrollRect);
    
    scrollWide = scrollRect.bottom-scrollRect.top;
    scrollRect = newRect;
    scrollRect.top = scrollRect.bottom + 4;
    scrollRect.bottom = scrollRect.top + scrollWide;
    SetControlBounds(
                     nowCD->hexCont,
                     &scrollRect);
    // 8.18.03 making scroll selection and next change same width
    // the bottom one is bigger, so...
    {Rect eeniemeenie; // 8.18.03
        GetControlBounds( SnatchCRef(theWindow,'PEEK',kPeekNextChange),&eeniemeenie);
        // adding the scrollTo button
        GetControlBounds( SnatchCRef(theWindow,'PEEK',kPeekScrollTo),&newRect);
        scrollWide = newRect.bottom - newRect.top; // mRectHi(newRect);
        newRect.top = scrollRect.bottom +8;
        newRect.bottom = newRect.top + scrollWide;
        //8.18.03        scrollWide = newRect.right - newRect.left ; // mRectWide(newRect);
        scrollWide  = eeniemeenie.right - eeniemeenie.left;
        
        newRect.left = scrollRect.left;
        newRect.right = newRect.left + scrollWide;
        SetControlBounds( SnatchCRef(theWindow,'PEEK',kPeekScrollTo),&newRect);
        // scroll to next change right under this
        
        // 8.18.03            GetControlBounds( SnatchCRef(theWindow,'PEEK',kPeekNextChange),&scrollRect);
        scrollRect = eeniemeenie; // 8.18.03
        scrollWide = scrollRect.bottom - scrollRect.top; // mRectHi(newRect);
        scrollRect.top = newRect.bottom +8;
        scrollRect.bottom = scrollRect.top + scrollWide;
        
        scrollWide = scrollRect.right - scrollRect.left ; // mRectWide(newRect);
        scrollRect.left = newRect.left;
        scrollRect.right = scrollRect.left + scrollWide;
        SetControlBounds( SnatchCRef(theWindow,'PEEK',kPeekNextChange),&scrollRect);
    }  // end 8.18.03
    
    
    
    // trans scroll
    GetControlBounds(
                     nowCD->transScroll,
                     &scrollRect);
    
    //     InvalWindowRect(theWindow,&scrollRect);
    newRect.top =24  ;
    newRect.left= rightOfScroll + 30;
    newRect.right = newRect.left + ((nowCD->columnWidth * nowCD->numColumns) * 2);
    newRect.bottom = bottomOfPanes;
    nowCD->transTargetRect = newRect;
    
    
    scrollWide = scrollRect.right-scrollRect.left;
    scrollRect.left = newRect.right+1;
    scrollRect.right = scrollRect.left + scrollWide;
    scrollRect.bottom = bottomOfPanes;
    SetControlBounds(
                     nowCD->transScroll,
                     &scrollRect);
    // new 8.27.03
    // we're either positiong the radios or the text box
    // 9.21.03 and now setting up for display when the hex pane is hidden
    if(nowCD->modifying <3){
        // modfieabekle radios
        theRef = SnatchCRef(theWindow,kPeekItID,kPeekModifiableRadio);
    } else {
        theRef = nowCD->readOnlyPane;   // will that work? Huh, it did
    }
    GetControlBounds(
                     theRef,
                     &newRect);
    
    scrollWide = newRect.bottom-newRect.top;
    newRect.top = bottomOfPanes + 10;
    newRect.bottom = newRect.top +scrollWide;
    scrollWide = newRect.right-newRect.left;
    // 9.21.03  I think all you need to do is switch this one left rect and things will just work
    if(nowCD->showingHex)
        newRect.left = rightOfScroll + 40;
    else
        newRect.left = halfOfRawPane;
    
    newRect.right = newRect.left+scrollWide;
    SetControlBounds(
                     theRef,
                     &newRect);
    
    
    // NEW 8.18.03
    // adding hex or ascii input
    tempContRect = newRect; // have to add this to keep everything else working right 8.18.03
    
    theRef = SnatchCRef(theWindow,kPeekItID,kPeekEnterHexOrASCII);
    GetControlBounds(
                     theRef,
                     &newRect);
    scrollWide = newRect.bottom-newRect.top;
    newRect.top = bottomOfPanes + 10;
    newRect.bottom = newRect.top +scrollWide;
    scrollWide = newRect.right-newRect.left;
    newRect.left = tempContRect.right + 10;
    
    newRect.right = newRect.left+scrollWide;
    SetControlBounds(
                     theRef,
                     &newRect);
    
    // switching
    /********************/
    // now the invisible (or not) text and edit box
    
    
    
    
    theRef = SnatchCRef(theWindow,'PEEK',kPeekEnterASCIIWords); // switched
    GetControlBounds(
                     theRef,
                     &scrollRect);
    scrollWide = scrollRect.right - scrollRect.left;
    scrollRect.left = newRect.right + 16;
    scrollRect.right = scrollRect.left +scrollWide;
    scrollWide =newRect.bottom - (( newRect.bottom - newRect.top)/2)-6;
    scrollMid = scrollWide;
    scrollWide = scrollRect.bottom - scrollRect.top;
    scrollRect.bottom = scrollMid;
    scrollRect.top = scrollRect.bottom - scrollWide;
    // take it down 4
    OffsetRect(&scrollRect,0,4);
    SetControlBounds(
                     theRef,
                     &scrollRect);
    // 8.18.03 adding the ascii edit words
    // switching from here
    tempContRect = scrollRect;
    theRef = SnatchCRef(theWindow,'PEEK',kPeekHexEditWords);
    GetControlBounds(
                     theRef,
                     &scrollRect);
    scrollWide = scrollRect.right - scrollRect.left;
    scrollRect.left = tempContRect.left;
    scrollRect.right = scrollRect.left+scrollWide;
    scrollWide = scrollRect.bottom - scrollRect.top;
    scrollRect.top = tempContRect.bottom; // +4;
    scrollRect.bottom = scrollRect.top + scrollWide;
    SetControlBounds(
                     theRef,
                     &scrollRect);
    // reset
    /**********/    
    //    scrollRect=tempContRect;
    
    
    //***********
    theRef = nowCD->hexEditBox;
    GetControlBounds(
                     theRef,
                     &newRect);
    scrollWide = newRect.right - newRect.left; // mRectWide(newRect);
    scrollMid = newRect.bottom - newRect.top; // mRectHi(newRect);
    newRect.left = scrollRect.right + 12;
    newRect.right = newRect.left+scrollWide;
    newRect.bottom = scrollRect.bottom;
    newRect.top = newRect.bottom-scrollMid;
    SetControlBounds(
                     theRef,
                     &newRect);
    
    // and the apply button for hte text
    
    theRef =SnatchCRef(theWindow,'PEEK',kPeekApplyEditButt);
    GetControlBounds(
                     theRef,
                     &scrollRect);
    scrollWide =scrollRect.right - scrollRect.left; // mRectWide( scrollRect);
    scrollRect.left = newRect.right + 16;
    scrollRect.right = scrollRect.left + scrollWide;
    scrollWide = scrollRect.bottom-scrollRect.top;
    scrollRect.bottom = newRect.bottom;
    scrollRect.top = scrollRect.bottom-scrollWide;
    SetControlBounds(theRef,&scrollRect);
    
    // taking the popup out
    
    
    // text over trans
    theRef = SnatchCRef(theWindow,kPeekItID,kPeekText2);
    
    
    GetControlBounds(
                     theRef,
                     &newRect);
    scrollWide = newRect.right-newRect.left;
    newRect.left = rightOfScroll + 32;
    newRect.right = newRect.left+scrollWide;
    SetControlBounds(
                     theRef,
                     &newRect);
    
    // bottom buttons
    
    theRef = SnatchCRef(theWindow,kPeekItID,kPeekCommitButton);
    
    
    GetControlBounds(
                     theRef,
                     &newRect);
    scrollWide = newRect.bottom - newRect.top;
    newRect.bottom = wRect.bottom - botFromButt;
    if(nowCD->infoShowing)
        newRect.bottom -=kInfoPaneSize;
    newRect.top = newRect.bottom - scrollWide;
    scrollWide = newRect.right - newRect.left;
    newRect.right = wRect.right - 16;
    
    newRect.left = newRect.right - scrollWide;
    SetControlBounds(theRef,&newRect);
// inserting the toggle drawer button move here
    {   Rect vdRect;
        theRef = SnatchCRef(theWindow,kPeekItID,kPeekValDrawerToggle);
        
        
        GetControlBounds(
                         theRef,
                         &vdRect);
        scrollWide = vdRect.bottom - vdRect.top;
        vdRect.bottom = newRect.top - 4;
        vdRect.top = vdRect.bottom - scrollWide;
        scrollWide = vdRect.right - vdRect.left;
        vdRect.right = newRect.right;
        vdRect.left = vdRect.right - scrollWide;
   SetControlBounds(theRef,&vdRect);
    }
    // end insert
    
    theRef = SnatchCRef(theWindow,kPeekItID,kPeekRevertButton);
    
    GetControlBounds(
                     theRef,
                     &scrollRect);
    scrollWide = scrollRect.right-scrollRect.left;
    scrollRect.bottom = newRect.bottom;
    scrollRect.top = newRect.top;
    scrollRect.right = newRect.left - 10;
    scrollRect.left = scrollRect.right - scrollWide;
    SetControlBounds(
                     theRef,
                     &scrollRect);
    
    // bookmark disclosure triangle is on the same line
	// 06.05.06  moving these two down 3 nice!
    theRef = nowCD->infoCont;
    GetControlBounds(
                     theRef,
                     &scrollRect);
    scrollWide = scrollRect.right-scrollRect.left;
    scrollRect.left = wRect.left + 6;
    scrollRect.right = scrollRect.left + scrollWide;
    scrollWide = scrollRect.bottom-scrollRect.top;
    
    scrollRect.bottom = newRect.bottom+3; // NEW 06.05.06
    scrollRect.top = scrollRect.bottom-scrollWide;
    
    SetControlBounds(
                     theRef,
                     &scrollRect);
    // new, adding a file position text line right after the notes words
    
    theRef =SnatchCRef(theWindow,'PEEK',kPeekCurrentPosPane);
    GetControlBounds(
                     theRef,
                     &newRect);
    scrollWide = newRect.right-newRect.left;
    newRect.left = scrollRect.right + 6;
    newRect.right = newRect.left + scrollWide;
    scrollWide = scrollRect.bottom-scrollRect.top; // making the height the same as the triangle
    
    newRect.bottom = scrollRect.bottom;
    newRect.top = newRect.bottom-scrollWide;
    
    SetControlBounds(
                     theRef,
                     &newRect);
    
    
    // and here we arrange all the bookmark controls 
    /*****/
    ResizeNotesControls(theWindow,nowCD,&wRect);
    
    /*****/
    
    // if this all chanages then the scroll bar values have to change
    // or not.
    // value only, actually
    SetScrollValues(nowCD,theVal);
    SizePIPanesViews(theWindow,nowCD);
    // and make sure the val drawer updates itself
  if(  IsWindowVisible(nowCD->valueDrawer)){
      TellValWindowAboutChange(nowCD->valueDrawer);
}
    mPullPort
        
}
















// Raw pane
static  OSStatus PIRawPaneEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    ControlRef theCont;
    ControlID theID;
    UInt32 theKind;
    OSStatus myErr = noErr;
    mPushPort((WindowRef)inUserData);
    GetEventParameter (inEvent, kEventParamDirectObject, typeControlRef,
                       NULL, sizeof(ControlRef), NULL, &theCont);
    /*    GetControlID(
        theCont,
        &theID);
*/
    theKind = GetEventKind(inEvent);
    
    
    switch(theKind){
        case kEventControlHit:
            
            break;
        case kEventControlDraw:
        {Rect bRect;
            GetControlBounds(
                             theCont,
                             &bRect);
            EraseRect(&bRect);
            ColDrawRect(&bRect,kForRawData,(WindowRef)inUserData);
            //            RGBForeColor(&gBlack);
            
            DebugStr("\this is being called");
            Debugger();       DrawData((WindowRef)inUserData,kDrawRawData);
            
        }
            break;
        case kEventControlClick:
            break;
    }
    
    
    mPullPort;
    return(myErr);
    
}
void PISetEditEntryThings(PIMainWDataP nowCD,    UInt16 theVal)
{WindowRef theWindow = nowCD->us;
    ControlRef tempCont;
    switch(theVal){
        case kEditingAsHex:
            SetKeyboardFocus(
                             theWindow,
                             nowCD->hexEditBox,
                             kControlFocusNoPart);
            
            SetKeyboardFocus(
                             theWindow,
                             nowCD->hexEditBox,
                             kControlFocusNextPart);
            EnableControl(nowCD->hexEditBox);
            
            EnableControl( SnatchCRef(theWindow,'PEEK',kPeekHexEditWords));
            EnableControl(SnatchCRef(theWindow,'PEEK',kPeekApplyEditButt));
            DisableControl( SnatchCRef(theWindow,'PEEK', kPeekEnterASCIIWords));
            
            
            break;
            
        case kEditingAsAscii:
            // turned it off
            // see if it has focus
            GetKeyboardFocus(
                             theWindow,
                             &tempCont);
            if(tempCont ==      nowCD->hexEditBox)
                ClearKeyboardFocus(theWindow);
                DisableControl( SnatchCRef(theWindow,'PEEK',kPeekHexEditBox));
            SetKeyboardFocus(
                             theWindow,
                             nowCD->hexEditBox,
                             kControlFocusNoPart);
            
            DisableControl(nowCD->hexEditBox);
            
            DisableControl( SnatchCRef(theWindow,'PEEK',kPeekHexEditWords));
            DisableControl(SnatchCRef(theWindow,'PEEK',kPeekApplyEditButt));
            EnableControl( SnatchCRef(theWindow,'PEEK', kPeekEnterASCIIWords));
            
            
            break;
            
    }
}
static  OSStatus PIHexOrAsciiHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{OSStatus myErr = noErr;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    UInt16 theVal;
    ControlRef theCont,tempCont;
    ControlPartCode thePart;
    GetEventParameter (inEvent, kEventParamDirectObject, typeControlRef,
                       NULL, sizeof(ControlRef), NULL, &theCont);
    theVal = GetControlValue(nowCD->editAsRadio); // theCont);
    if(theVal != nowCD->editingAs) {
        // changed state
        nowCD->editingAs = theVal;
        PISetEditEntryThings(nowCD,theVal);
    }
    return(myErr);
    
}


static  OSStatus PIModifiRadioHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{OSStatus myErr = noErr;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    Boolean theVal;
    ControlRef theCont,tempCont;
    ControlPartCode thePart;
    GetEventParameter (inEvent, kEventParamDirectObject, typeControlRef,
                       NULL, sizeof(ControlRef), NULL, &theCont);
    theVal = GetControlValue(nowCD->modifiRadio); // theCont);
    if(theVal != nowCD->modifying) {
        // changed state
        nowCD->modifying = theVal;
        // see if this is the first time
        if(nowCD->editingAs == 0){
            // then it defaults to hex
            nowCD->editingAs=kEditingAsAscii;
        }
        switch(theVal){
            case 1:
                // turned it off
                // see if it has focus
                GetKeyboardFocus(
                                 theWindow,
                                 &tempCont);
                if(tempCont ==      nowCD->hexEditBox)
                    ClearKeyboardFocus(theWindow);
                    DisableControl( SnatchCRef(theWindow,'PEEK',kPeekHexEditBox));
                
                HideControl(nowCD->hexEditBox);
                HideControl( SnatchCRef(theWindow,'PEEK',kPeekHexEditWords));
                HideControl(SnatchCRef(theWindow,'PEEK',kPeekApplyEditButt));
                HideControl( SnatchCRef(theWindow,'PEEK', kPeekEnterHexOrASCII));
                HideControl( SnatchCRef(theWindow,'PEEK', kPeekEnterASCIIWords));
                
                break;
                
            case 2:
                // turned it on
                ShowControl(nowCD->hexEditBox);
                
                if(  nowCD->editingAs == kEditingAsHex){
                    EnableControl(nowCD->hexEditBox);
                    SetKeyboardFocus(
                                     theWindow,
                                     nowCD->hexEditBox,
                                     kControlFocusNextPart);
                    
                }
                    ShowControl( SnatchCRef(theWindow,'PEEK',kPeekHexEditWords));
                ShowControl(SnatchCRef(theWindow,'PEEK',kPeekApplyEditButt));
                ShowControl( SnatchCRef(theWindow,'PEEK', kPeekEnterHexOrASCII));
                ShowControl( SnatchCRef(theWindow,'PEEK', kPeekEnterASCIIWords));
                // hah, we have to call the thing that sets up buttons as if hex/ascii was clicked
                PISetEditEntryThings( nowCD,    nowCD->editingAs)                     ;
                break;
                
                
        }
        // draw1
        HIViewSetNeedsDisplay(nowCD->hexEditBox,true);
        // draw1
        HIViewSetNeedsDisplay( SnatchCRef(theWindow,'PEEK',kPeekHexEditWords),true);
        // draw1
        HIViewSetNeedsDisplay(SnatchCRef(theWindow,'PEEK',kPeekApplyEditButt),true);
        
    }
    return(myErr);
    
}

OSStatus ChangeAByte( PIMainWDataP nowCD,char holder)
{OSStatus myErr = noErr;
    SInt64 forkLen;
    changedBytePtr theP=0;
    // now we have the byte, we need to see if we've changed this byte already.
    // if yes, then reutn if this is the same byte again
    //  is a new value, if so change and go away
    // is nothing,then actually create a new one
    // AH!   We actually have to re-link if the byte was modified, since we only undo from the end of the chain
      // make a changedByte
    theP = NewClearChangedByte(0,kPIChangeTypeSingleByte,0,nowCD->changeGeneration);
    if(theP){
        
        // stuff it in the thingie
        theP->currentByte = holder;
        // now figure out what the selection currently is
        theP->realPos = nowCD->startSel->totalPos;
        // we don't really need to have the original byte in here, since we decided not to change the real file
        // actually, we don't need to do anything else, do we?
        // 8.7.05, yes we do, so we can show it in a help tag
        // add it
        // OK, so look in the buffer first.  If it's not there then read it from the file.
        if(theP->realPos >=  (nowCD->displaying.bufStartInFile  && theP->realPos <= (nowCD->displaying.bufStartInFile + kFileBufferSize))){
        // its in the buffer
            SInt64 theLoggie = theP->realPos - nowCD->displaying.bufStartInFile;
                                                theP->originalByte =        *( (nowCD->displaying.fileBuffer)+theLoggie);
        } else {
        // we have to go read it.  This shoudl only happen during range modifies, by the way
            short readerForkRef =0;
#if 0
            if(nowCD->forkShowing == 0){
                readerForkRef =nowCD->theFT->dataForkRef; 
            } else {
                readerForkRef =nowCD->theFT->resForkRef; 
                                
            }		
#endif
            switch(nowCD->forkShowing){	
                case kPIMainShowingDataFork:
                    readerForkRef =nowCD->theFT->dataForkLen; 
                    break;
                case kPIMainShowingResFork:
                    readerForkRef =nowCD->theFT->resForkLen; 
                    break;  
                case    kPIMainShowingNoFork:
                    readerForkRef = 0;
                    break;
            };	
            
            
            if(readerForkRef){
            FSReadFork (readerForkRef,fsFromStart,  theP->realPos,
                        1,
                        &theP->originalByte,
                        0
                        );
            }
            
            
            
        }
        if(nowCD->changes){
            changedBytePtr oogle= nowCD->changes;
            // get to the end
            while(oogle->next){
                oogle = oogle->next;
            }
            oogle->next = theP;
            theP->previous = oogle;
        } else {
            nowCD->changes = theP;
        }
        
        // and one more thing.  I just decide to advance the selection point.
        // find the next thingme, then upodate that thingme in the thingme and make the thingme move
        (nowCD->startSel)->totalPos ++;  // hmmmm, should check for past end of file
        switch(nowCD->forkShowing){	
            case kPIMainShowingDataFork:
                forkLen =nowCD->theFT->dataForkLen; 
                break;
            case kPIMainShowingResFork:
                forkLen =nowCD->theFT->resForkLen; 
                break;  
            case    kPIMainShowingNoFork:
                forkLen = kFileBufferSize;
                break;
        };	
        
        
        // >= added 06.05.06
        if( (nowCD->startSel)->totalPos >=forkLen){
            (nowCD->startSel)->totalPos--; // take it back
        }
        // check to see if the selection has gone below the line, update if so
        // that worked
        {
            UInt32 theVal =(GetControl32BitValue(nowCD->rawScroll) * nowCD->numColumns);
            theVal +=nowCD->displaying.bytesShowing;
            if((nowCD->startSel)->totalPos >= theVal){
                // bump the control value by one
                theVal =GetControl32BitValue(nowCD->rawScroll);
                theVal ++;
                SetControl32BitValue(nowCD->rawScroll,theVal);
                SetControl32BitValue(nowCD->transScroll,theVal);
                CouldReadDataChunk(nowCD,kFlagRedraw);
                UpdateCellPoses(nowCD->startSel,  nowCD);
                // draw1
                HIViewSetNeedsDisplay(nowCD->posPane,true);
                
            }
        }
        UpdateCellPoses(nowCD->startSel, nowCD);
        
        FillInPendingChanges( nowCD);
        HIViewSetNeedsDisplay(
                              nowCD->rawPane,
                              true);
        HIViewSetNeedsDisplay(
                              nowCD->transPane,
                              true);
        if(nowCD->compDrawer){
            UpdateDiffViews(nowCD,nowCD->compDrawer);
        }
        
        EnableControl(SnatchCRef(nowCD->us,'PEEK',kPeekRevertButton));
        EnableControl(SnatchCRef(nowCD->us,'PEEK',kPeekCommitButton));
        EnableControl(SnatchCRef(nowCD->us,'PEEK',kPeekNextChange));
        SetWindowModified (nowCD->us,true);
        
    }
    // draw1
    HIViewSetNeedsDisplay(nowCD->curPosThingie,true);
    return(myErr);
}

// as above, we have to make sure we're not adding a byte that is already changed.  So we have to check each.
// rangeStart & rangeEnd had better be set up
/// oooh, I just thought of something sneaky
OSStatus ChangeAByteRange( PIMainWDataP nowCD,SInt64 rangeStart, SInt64 rangeEnd,Ptr dataPointer,char toThisByte, UInt32 changeTypeID,UInt32 changeIDNumber)
{

    OSStatus myErr=0;
    changedBytePtr theP=0;
    changedBytePtr storePtr=0;
    Ptr currentPtr = dataPointer;
    Boolean hadIt = false;
    SInt64 currentByteToChange= rangeStart;
    char newByte = toThisByte;
        // see if there are any

    if(nowCD->changes){
            do{
// run changes to see if there were any
                changedBytePtr oogle= nowCD->changes;
                hadIt = false;
                // TEST TEMP
                if(hadIt == false){
                // did NOT have it, jsut add to the end
                    theP = NewClearChangedByte(0,changeTypeID,changeIDNumber,nowCD->changeGeneration);
                    theP->realPos =currentByteToChange;
                    if(currentPtr){
                        newByte = *currentPtr;
                        currentPtr ++;
                    }
                    theP->currentByte = newByte;
                    // find the end and add it
                    changedBytePtr oogle= nowCD->changes;
                    while(oogle->next)
                        oogle=oogle->next;
                    oogle->next = theP;
                    theP->previous = oogle;
                        
                    
                  
                
                }

                currentByteToChange++;
            }while(currentByteToChange <= rangeEnd);

            } else {
        // none, so we just jam from zero on
                
                do{
                    theP = NewClearChangedByte(0,changeTypeID,0,nowCD->changeGeneration);
                    theP->realPos =currentByteToChange;
                    //**** try this
                    if(theP->realPos >=  (nowCD->displaying.bufStartInFile  && theP->realPos <= (nowCD->displaying.bufStartInFile + kFileBufferSize))){
                        // its in the buffer
                        SInt64 theLoggie = theP->realPos - nowCD->displaying.bufStartInFile;
                        theP->originalByte =        *( (nowCD->displaying.fileBuffer)+theLoggie);
                    } else {
                        // we have to go read it.  This shoudl only happen during range modifies, by the way
                        short readerForkRef =0;
#if 0                        
                        if(nowCD->forkShowing == 0){
                            readerForkRef =nowCD->theFT->dataForkRef; 
                        } else {
                            readerForkRef =nowCD->theFT->resForkRef; 
                            
                        }		
#endif
                        switch(nowCD->forkShowing){	
                            case kPIMainShowingDataFork:
                                readerForkRef =nowCD->theFT->dataForkLen; 
                                break;
                            case kPIMainShowingResFork:
                                readerForkRef =nowCD->theFT->resForkLen; 
                                break;  
                            case    kPIMainShowingNoFork:
                                readerForkRef = 0;
                                break;
                        };	
                        
                        if(readerForkRef){
                        FSReadFork (readerForkRef,fsFromStart,  theP->realPos,
                                    1,
                                    &theP->originalByte,
                                    0
                                    );}
                        
                        
                        
                        
                    }
                    
                    //****
                    
                    if(currentPtr){
                        newByte = *currentPtr;
                        currentPtr ++;
                    }
                    
                    theP->currentByte = newByte;

                    if(storePtr == 0){                        
                        storePtr=theP;
                        nowCD->changes = theP;
                    }else {
                        theP->previous = storePtr;
                        
                        storePtr->next = theP;
                        storePtr=theP;

                    }
                    currentByteToChange++;
                }while(currentByteToChange <= rangeEnd);
                
            }
    
    
    
        
    
        FillInPendingChanges( nowCD);
        HIViewSetNeedsDisplay(
                              nowCD->rawPane,
                              true);
        HIViewSetNeedsDisplay(
                              nowCD->transPane,
                              true);
        EnableControl(SnatchCRef(nowCD->us,'PEEK',kPeekRevertButton));
        EnableControl(SnatchCRef(nowCD->us,'PEEK',kPeekCommitButton));
        EnableControl(SnatchCRef(nowCD->us,'PEEK',kPeekNextChange));
        SetWindowModified (nowCD->us,true);
        if(nowCD->compDrawer){
            UpdateDiffViews(nowCD,nowCD->compDrawer);
        }
        
    
    
    return(myErr);
}

OSStatus ChangeMarkedByteRange( WindowRef theWindow,char toThisByte)
{    WCH tempWC = (WCH)GetWRefCon((WindowRef)theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    ChangeAByteRange(  nowCD,nowCD->rangeStart, nowCD->rangeEnd,0, toThisByte,kPIChangeTypeModRange,toThisByte);

}

UInt64 PIReturnFileFIndFlags(WindowRef theWindow)
{
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    UInt64 flags=0;
#if 0
    if(nowCD->forkShowing == 0)
        flags = kFileSearchDataFork;
    else
        flags = kFileSearchResFork;
#endif
    switch(nowCD->forkShowing){	
        case kPIMainShowingDataFork:
            flags = kFileSearchDataFork;
            break;
        case kPIMainShowingResFork:
            flags = kFileSearchResFork;
            break;  
        case    kPIMainShowingNoFork:
            flags = 0;
            break;
    };	
    
    return(flags);
}

static void innerApplyChangeButt(  PIMainWDataP nowCD )
{OSStatus myErr=0;
    Size theS = 0;
    char theSel[2];
    //    UInt32 theVal;
    //    UInt32 newVal;

    ControlPartCode thePart;
    
    LoopVar qq;
    Byte holder;
    static        char raw[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    static char ookies[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

    // whatever is, gets set.
    // first, see if there are actually two characters
    GetControlDataSize(
                       nowCD->hexEditBox ,
                       5,
                       kControlEditTextTextTag,
                       &theS
                       );
    if(theS != 2){
        SysBeep(1);
        return(noErr);
    }
    
    
    GetControlData(
                   nowCD->hexEditBox ,
                   5,
                   kControlEditTextTextTag,
                   2,
                   &theSel,
                   0);
    
    
    
    
    //I'm too lazy to think this one out
    for(qq=0;qq<16;qq++){
        if(theSel[0] == raw[qq] || theSel[0] ==ookies[qq]){
            holder = qq << 4;
            break;
        }
    }
    for(qq=0;qq<16;qq++){
        if(theSel[1] == raw[qq] || theSel[1] ==ookies[qq]){
            holder |= qq;
            break;
        }
    }
    
    // moving the byte applied code ouut
    myErr =        ChangeAByte(  nowCD, holder);
    
}

static  OSStatus PIPIApplyEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    OSStatus myErr = noErr;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    ControlRef theCont;
    GetEventParameter (inEvent, kEventParamDirectObject, typeControlRef,
                       NULL, sizeof(ControlRef), NULL, &theCont);
    innerApplyChangeButt( nowCD );  
    return(myErr);
    
}
// ‚Ä¢‚Ä¢‚Ä¢‚Ä¢ TO DO fix result block leak
void             pimwStoreLastFind(WindowRef theWindow,SLibSearchParamBlockPtr theSearchBlock)
{
    // clear the current one if there is one   
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    if(nowCD->lastFindPtr){
        free(        nowCD->lastFindPtr->searchString);
        free( nowCD->lastFindPtr);
        nowCD->lastFindPtr = 0;
    }
    nowCD->lastFindPtr = theSearchBlock;
}


void pimwMoveToThisByte(WindowRef theWindow, SInt64 theByte)
{    
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    
    nowCD->startSel->totalPos = theByte;   
    pdoscrollto(nowCD);
}

static void pdoscrollto(PIMainWDataP nowCD)
{
    ControlRef theCont;
    ControlPartCode thePart;
    SInt64 startRange =GetControl32BitValue(nowCD->rawScroll)* nowCD->numColumns;
    SInt64 endRange = startRange + nowCD->sizeDataInPane;
    SInt64 leftOver = nowCD->startSel->totalPos/nowCD->numColumns;
    Boolean inPage = (nowCD->startSel->totalPos > startRange && nowCD->startSel->totalPos < endRange);
    // well, go ahead.
    // for smoothness, lets figure out how to stay in frame
    

    if(inPage){
        // do nothing
	/**************/
    {RgnHandle r1 = NewRgn();
	Rect tempRect = nowCD->startSel->rawRect;
	NormalizeRect(&nowCD->rawTargetRect,&tempRect);
	RectRgn(r1,&tempRect);
	HIViewSetNeedsDisplayInRegion(
                                      nowCD->rawPane,
                                      r1,
                                      true);
	
	tempRect = nowCD->startSel->realRect;
	NormalizeRect(&nowCD->transTargetRect,&tempRect);

	
	RectRgn(r1,&tempRect);
	HIViewSetNeedsDisplayInRegion(
                                      nowCD->transPane,
                                      r1,
                                      true);
	DisposeRgn(r1);
    }
        
        
        /****************/
        
    } else {
        SetControl32BitValue(nowCD->rawScroll,leftOver);
        SetControl32BitValue(nowCD->transScroll,leftOver);
        CouldReadDataChunk(nowCD,kFlagRedraw);
    }
    // and of course set the value of the other control to this one
    // and tell the views to redraw
    UpdateCellPoses(nowCD->startSel,  nowCD);
    if(inPage){
    {RgnHandle r1 = NewRgn();
	Rect tempRect = nowCD->startSel->rawRect;
	NormalizeRect(&nowCD->rawTargetRect,&tempRect);
	
	RectRgn(r1,&tempRect);
	HIViewSetNeedsDisplayInRegion(
                                      nowCD->rawPane,
                                      r1,
                                      true);
	
	tempRect = nowCD->startSel->realRect;
	NormalizeRect(&nowCD->transTargetRect,&tempRect);
	
	RectRgn(r1,&tempRect);
	HIViewSetNeedsDisplayInRegion(
                                      nowCD->transPane,
                                      r1,
                                      true);
	DisposeRgn(r1);
 
        
    }
        
    } else {
        HIViewSetNeedsDisplay(
                              nowCD->rawPane,
                              true);
        HIViewSetNeedsDisplay(
                              nowCD->transPane,
                              true);
        
        
        // draw1
        HIViewSetNeedsDisplay(nowCD->posPane,true);
        
    }
    // draw1
    HIViewSetNeedsDisplay( nowCD->curPosThingie,true);
    if(nowCD->compDrawer){
        UpdateDiffViews(nowCD,nowCD->compDrawer);
    }
    
}

static  OSStatus PIPIScrollToEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    OSStatus myErr = noErr;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    //    UInt32 theVal;
    //    UInt32 newVal;
    pdoscrollto(nowCD);
    return(myErr);
    
}

void HexBoxValidator(                    ControlRef control                     )
{
    Size theS = 0;
    WindowRef theWindow = GetControlOwner(control);
    
    mPushPort(theWindow);
    GetControlDataSize(
                       control,
                       5,
                       kControlEditTextTextTag,
                       &theS
                       );
    if(theS == 2){
        //        EnableControl(SnatchCRef(theWindow,'PEEK',kPeekApplyEditButt));
        
    } else {
        //        DisableControl(SnatchCRef(theWindow,'PEEK',kPeekApplyEditButt));
        if(theS > 2){
            char ook;
            SetControlData(
                           control,
                           kControlEntireControl,
                           kControlEditTextTextTag,
                           0,
                           &ook);
            
        }
    }
    mPullPort;
}
static  OSStatus PIValueDrawerEventHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{OSStatus myErr = noErr;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    ToggleDrawer(nowCD->valueDrawer);
    return(myErr);
    
}

static  OSStatus PINextChangeEventHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{OSStatus myErr = noErr;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    changedBytePtr goHere = 0;
    if(nowCD->lastChangeMovedTo && (nowCD->lastChangeMovedTo)->next){
        goHere=(nowCD->lastChangeMovedTo)->next;
        nowCD->lastChangeMovedTo = goHere;
    } else {
        // it's the first one (or the last one), so go to the front of the class
        goHere=nowCD->changes;
        nowCD->lastChangeMovedTo = goHere;
        
    }
    // paranoia
    if(goHere){
        piCell *theCell= malloc(sizeof(piCell));
        
        ZeroCell(theCell);
        // find the next thingme, then upodate that thingme in the thingme and make the thingme move
        theCell->totalPos = goHere->realPos;
        UpdateCellPoses(theCell, nowCD);
        
        // are we really ready?
        // no, dang it, dispose the old selection and add this one
        free(nowCD->startSel);
        nowCD->startSel = theCell;
        pdoscrollto(nowCD);
        HIViewSetNeedsDisplay(
                                      nowCD->rawPane,
                                      true);
	
	HIViewSetNeedsDisplay(
                                      nowCD->transPane,
                                      true);
        
        if(nowCD->compDrawer){
            UpdateDiffViews(nowCD,nowCD->compDrawer);
        }
        
    }
    return(myErr);
    
}

static  OSStatus PIHexBoxEventHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )

{
    OSStatus myErr = noErr;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    Size theS=0;
    
    
    
    
    GetControlDataSize(
                       nowCD->hexEditBox ,
                       5,
                       kControlEditTextTextTag,
                       &theS
                       );
    
    CallNextEventHandler(
                         inCallRef,
                         inEvent);
    
    
    return(myErr);
    
}
static  OSStatus PIDiscHexEventHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    OSStatus myErr = noErr;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    Boolean theVal;
	OSStatus err;
    ControlRef theCont;
    ControlPartCode thePart;
	CGContextRef cgContext;
	
    GetEventParameter (inEvent, kEventParamDirectObject, typeControlRef,
                       NULL, sizeof(ControlRef), NULL, &theCont);

					   mGetCGContext;
    theVal = GetControlValue(theCont);
    
    
    
    
    
    
    if(theVal != nowCD->showingHex){
        // 9.21.03
        // lets show the modification buttons anytime, bucky
        
        if(theVal){
            // we now want to show hex
            
            ShowControl(nowCD->transPane );
            ShowControl(nowCD->transScroll );
            
            nowCD->showingHex = theVal;
            CalcNumColumns(cgContext,theWindow);
            SizePIMainWINDControls(theWindow);
              if( nowCD->comparingWithFile)
                  SizeDiffDWINDControls(nowCD->compDrawer);
            CalcNumRows(theWindow);
            
            CouldReadDataChunk(nowCD,kFlagRedraw);
            extern OSStatus UpdateCellPoses(piCell *theCell, PIMainWDataP nowCD);
            UpdateCellPoses(nowCD->startSel,  nowCD);
            pdoscrollto(nowCD);
        } else {
            // we are turning off hex showing
            nowCD->showingHex = theVal;
            
            HideControl(nowCD->transPane );
            HideControl(nowCD->transScroll );
            //            HideControl( SnatchCRef(theWindow,'PEEK',kPeekPopup));
            //            HideControl( SnatchCRef(theWindow,'PEEK',kPeekText3));
            
            CalcNumColumns(cgContext,theWindow);
            SizePIMainWINDControls(theWindow);
            if( nowCD->comparingWithFile)
                SizeDiffDWINDControls(nowCD->compDrawer);

            CalcNumRows(theWindow);
            
            CouldReadDataChunk(nowCD,kFlagRedraw);
            extern OSStatus UpdateCellPoses(piCell *theCell, PIMainWDataP nowCD);
            UpdateCellPoses(nowCD->startSel,  nowCD);
            pdoscrollto(nowCD);
            
        }
        
        
        // no matter what, redraw
        // draw1
        HIViewSetNeedsDisplay(nowCD->posPane,true);
        
    }
    return(myErr);
    
}

static  OSStatus PIDiscTriEventHandlerProc ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{Rect globalBounds;
    OSStatus myErr = 0;
    short counter;
    ULong qq;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    if(nowCD->infoShowing){
        nowCD->infoShowing = 0;
        // do your jindg and showing
        HideControl( SnatchCRef(theWindow,'PEEK',kNotesUserPane));
        HideControl( SnatchCRef(theWindow,'PEEK',kNotesPopUp));
        HideControl( SnatchCRef(theWindow,'PEEK',kNotesDeleteNote));
        HideControl( SnatchCRef(theWindow,'PEEK',kNotesNewNote));
        //       HideControl( SnatchCRef(theWindow,'PEEK',kScrollToCurrentNoteByte)); 
        HideControl( SnatchCRef(theWindow,'PEEK',kEditNote));
        HideControl( SnatchCRef(theWindow,'PEEK',kExportNotes));
        
        
        
        
    } else {
        nowCD->infoShowing=-1;
        
    }
    
    
    
    
    
    
    GetWindowBounds(
                    theWindow,
                    kWindowStructureRgn,
                    &globalBounds);
    if( nowCD->infoShowing )
        counter=kInfoPaneSize;
    else
        counter = -kInfoPaneSize;
    
    globalBounds.bottom +=counter;
    SetWindowBounds(
                    theWindow,
                    kWindowStructureRgn,
                    &globalBounds);
    SizePIMainWINDControls(theWindow);
    // doing this after the sizing so the buttons don't move on yah
    if(nowCD->infoShowing==-1)
    {        ShowControl( SnatchCRef(theWindow,'PEEK',kNotesUserPane));
        ShowControl( SnatchCRef(theWindow,'PEEK',kNotesPopUp));
        ShowControl( SnatchCRef(theWindow,'PEEK',kNotesDeleteNote));
        ShowControl( SnatchCRef(theWindow,'PEEK',kNotesNewNote));
        //       ShowControl( SnatchCRef(theWindow,'PEEK',kScrollToCurrentNoteByte));
        ShowControl( SnatchCRef(theWindow,'PEEK',kEditNote));
        ShowControl( SnatchCRef(theWindow,'PEEK',kExportNotes));
        bmPopUpItemPicked(nowCD,1);
    }
    //    Draw1Control(SnatchCRef(theWindow,kPeekItID,kInfoDiscWords));
    
    
    
    return(myErr);
    
}



void liveScroller(ControlRef theCont, ControlPartCode thePart)
{
    if(thePart >0){
        WindowRef theWindow = GetControlOwner(theCont);
        if(theWindow){
            WCH tempWC = (WCH)GetWRefCon(theWindow);
            PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
            UInt32 newVal;
            UInt32 theVal=GetControl32BitValue(theCont);
            
            // get the value and move to it
            switch(thePart){
                case  kControlUpButtonPart :
                    newVal = theVal-1;
                    if(newVal <0)newVal = 0;
                        break;
                    
                case  kControlDownButtonPart:
                    //            SetControl32BitValue(theCont,theVal+1);
                    newVal = theVal+1;
                    
                    break;
                    
                case kControlPageUpPart:
                    newVal = theVal-10;
                    if(newVal <0)newVal = 0;
                        
                        break;
                    
                case kControlPageDownPart:
                    newVal = theVal+10;
                    if(newVal <0)newVal = 0;
                        
                        break;
                default:
                    // should be the Tumb
                    newVal = theVal;
                    break;
            }
            SetControl32BitValue(nowCD->rawScroll,newVal);
            SetControl32BitValue(nowCD->transScroll,newVal);
            
            CouldReadDataChunk(nowCD,kFlagRedraw);
            UpdateCellPoses(nowCD->startSel,  nowCD);
            
            // and of course set the value of the other control to this one
            // and tell the views to redraw
            
            HIViewSetNeedsDisplay(
                                  nowCD->rawPane,
                                  true);
            HIViewSetNeedsDisplay(
                                  nowCD->transPane,
                                  true);
            // draw1
            HIViewSetNeedsDisplay(nowCD->posPane,true);
            if(nowCD->compDrawer){
                UpdateDiffViews(nowCD,nowCD->compDrawer);
            }
            
            
        }
    }
}
void liveScroller2(ControlRef theCont, ControlPartCode thePart)
{
    
    if(thePart >0){
        WindowRef theWindow = GetControlOwner(theCont);
        if(theWindow){
            WCH tempWC = (WCH)GetWRefCon(theWindow);
            PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
            UInt32 newVal;
            UInt32 theVal=GetControl32BitValue(theCont);
            
            // get the value and move to it
            switch(thePart){
                case  kControlUpButtonPart :
                    newVal = theVal-1;
                    if(newVal <0)newVal = 0;
                        break;
                    
                case  kControlDownButtonPart:
                    //            SetControl32BitValue(theCont,theVal+1);
                    newVal = theVal+1;
                    
                    break;
                    
                case kControlPageUpPart:
                    newVal = theVal-10;
                    if(newVal <0)newVal = 0;
                        
                        break;
                    
                case kControlPageDownPart:
                    newVal = theVal+10;
                    if(newVal <0)newVal = 0;
                        
                        break;
                default:
                    // should be the Tumb
                    newVal = theVal;
                    break;
            }
            SetControl32BitValue(nowCD->rawScroll,newVal);
            SetControl32BitValue(nowCD->transScroll,newVal);
            
            CouldReadDataChunk(nowCD,kFlagRedraw);
            UpdateCellPoses(nowCD->startSel,  nowCD);
            
            // and of course set the value of the other control to this one
            // and tell the views to redraw
            
            HIViewSetNeedsDisplay(
                                  nowCD->rawPane,
                                  true);
            HIViewSetNeedsDisplay(
                                  nowCD->transPane,
                                  true);
            // draw1
            HIViewSetNeedsDisplay(nowCD->posPane,true);
            
            if(nowCD->compDrawer){
                UpdateDiffViews(nowCD,nowCD->compDrawer);
            }
            
        }
    }
}


static  OSStatus PIScrollBarEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    OSStatus myErr = noErr;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    UInt32 theVal;
    UInt32 newVal;
    ControlRef theCont;
    ControlPartCode thePart;
    
    GetEventParameter (inEvent, kEventParamDirectObject, typeControlRef,
                       NULL, sizeof(ControlRef), NULL, &theCont);
    GetEventParameter (inEvent, kEventParamControlPart, typeControlPartCode,
                       NULL, sizeof(ControlPartCode), NULL, &thePart);
    
    theVal=GetControl32BitValue(theCont);
    
    // get the value and move to it
    switch(thePart){
        case  kControlUpButtonPart :
            //            newVal = theVal-1;
            //            if(newVal <0)newVal = 0;
            break;
            
        case  kControlDownButtonPart:
            //            SetControl32BitValue(theCont,theVal+1);
            //           newVal = theVal+1;
            
            break;
            
        case kControlPageUpPart:
            //        newVal = theVal-10;
            //          if(newVal <0)newVal = 0;
            
            break;
            
        case kControlPageDownPart:
            //        newVal = theVal+10;
            //            if(newVal <0)newVal = 0;
            
            break;
        default:
            // should be the Tumb
            newVal = theVal;
            SetControl32BitValue(nowCD->rawScroll,newVal);
            SetControl32BitValue(nowCD->transScroll,newVal);
            
            break;
    }
    
    CouldReadDataChunk(nowCD,kFlagRedraw);
    UpdateCellPoses(nowCD->startSel,  nowCD);
    
    // and of course set the value of the other control to this one
    // and tell the views to redraw
    HIViewSetNeedsDisplay(
                          nowCD->rawPane,
                          true);
    HIViewSetNeedsDisplay(
                          nowCD->transPane,
                          true);
    // draw1
    HIViewSetNeedsDisplay(nowCD->posPane,true);
    if(nowCD->compDrawer){
        UpdateDiffViews(nowCD,nowCD->compDrawer);
    }
    
    return(myErr);
    
}


changedBytePtr ChangedByteAtPosition(  PIMainWDataP nowCD,SInt64 position)
{changedBytePtr retVal = 0;

    if(nowCD->changes){
      changedBytePtr oogle= nowCD->changes;
        do{
            if(oogle->realPos == position){
                retVal = oogle;
                break;
            }
            oogle = oogle->next;
        }while(oogle);
    }
    return(retVal);
}

changedBytePtr ChangedByteAtPositionFromBack(  PIMainWDataP nowCD,SInt64 position)
{changedBytePtr retVal = 0;
    
    if(nowCD->changes){
        
        
        
        
        changedBytePtr oogle= nowCD->changes;
// go to the very end
        while(oogle->next)oogle = oogle->next;
        
        
        do{
            if(oogle->realPos == position){
                retVal = oogle;
                break;
            }
            oogle = oogle->previous;
        }while(oogle);
    }
    return(retVal);
}


static Boolean onece=false;

static  OSStatus PICurFilePosPaneEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    WindowRef theWindow=(WindowRef)inUserData;
    UInt16    oldFontSize;
	HIRect theHIRect;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    if(tempWC){
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    CGContextRef cgContext;
    ControlRef theCont;
    Rect theRect,ookRect;
    GetEventParameter (inEvent, kEventParamDirectObject, typeControlRef,
                       NULL, sizeof(ControlRef), NULL, &theCont);
    
    GetControlBounds(theCont,&theRect);
		GetEventParameter( inEvent, kEventParamCGContextRef, typeCGContextRef,
			NULL, sizeof( CGContextRef ), NULL, &cgContext );
			          HIViewGetFrame(
                           theCont,
                           &theHIRect);
//						                   theHIRect.origin.x=0;
//                theHIRect.origin.y=0;


/************************/

         CGContextSelectFont(cgContext, "Lucida Grande", nowCD->fontSize, kCGEncodingMacRoman);
         CGContextSetTextDrawingMode (cgContext,  kCGTextFill);          
//         CGContextSetRGBFillColor (cgContext, 0, 0, 0, 1);          
//         CGContextSetRGBStrokeColor (cgContext, 0, 0, 0,1 ); 
	CGContextScaleCTM (cgContext, 1,-1);// -1.0);
/*************************/







    CGDrawStringAtRGBColor( cgContext,"\pSelection position:",0,(theHIRect.size.height-2)*-1/* -10*/,&gBlack);

    SInt64 thePosToMatch= nowCD->startSel->totalPos;
 if(nowCD->drawingPosAs == kDrawingAddyInDec)
    CGWriteNumL(cgContext,thePosToMatch);
    else 
    CGWriteHexLong(cgContext,thePosToMatch);

    
/***********/
    // adding selection size
    if(nowCD->rangeStart != nowCD->rangeEnd && nowCD->rangeStart < nowCD->rangeEnd){
    CGDrawString( cgContext,"\p  size:");
        thePosToMatch= nowCD->rangeEnd - nowCD->rangeStart+1;
        if(nowCD->drawingPosAs == kDrawingAddyInDec)
            CGWriteNumL(cgContext,thePosToMatch);
        else 
            CGWriteHexLong(cgContext,thePosToMatch);
        
    }
    
        
    }
    /*********/
    
    return(noErr);
}
#if 0
static  OSStatus PIInfoPaneEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    // all we're doing is drawing
    //    nowCD->numColumns;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    
    ControlRef theCont;
    Rect theRect,ookRect;
    ControlID theID;
    UInt32 theKind;
    short hPos = 2;
    short vPos=nowCD->cellHi;
    short hi = nowCD->cellHi;
    
    SInt16 outItemHit;
    OSStatus myErr = noErr;
    mPushPort((WindowRef)inUserData);
    GetEventParameter (inEvent, kEventParamDirectObject, typeControlRef,
                       NULL, sizeof(ControlRef), NULL, &theCont);
    /*    GetControlID(
        theCont,
        &theID);
*/
    theKind = GetEventKind(inEvent);
    GetControlBounds(theCont,&theRect);
    
    switch(theKind){
        case kEventControlHit:
        case kEventControlClick:
            
            break;
        case kEventControlDraw:
            if(nowCD->infoShowing)
                DrawFileInfo( nowCD,0);
            
            break;
            
    }
    
    
    mPullPort;
    return(myErr);
    
}
#endif
static  OSStatus PIReadOnlyPaneEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    // all we're doing is drawing
    //    nowCD->numColumns;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    
    ControlRef theCont;
    Rect theRect,ookRect;
    ControlID theID;
    UInt32 theKind;
    short hPos = 2;
    short vPos=nowCD->cellHi;
    short hi = nowCD->cellHi;
    SInt64 byteCounter  = nowCD->displaying.bufStartInFile + nowCD->displaying.offsetInBuffer;
    RGBColor oldColor={0,0,0};
    RGBColor redddd = {0xffff,0,0};
    SInt16 outItemHit;
	HIRect theHIRect;
	CGContextRef  cgContext;
    OSStatus myErr = noErr;
//    mPushPort((WindowRef)inUserData);
    GetEventParameter (inEvent, kEventParamDirectObject, typeControlRef,
                       NULL, sizeof(ControlRef), NULL, &theCont);
					   
					   		GetEventParameter( inEvent, kEventParamCGContextRef, typeCGContextRef,
			NULL, sizeof( CGContextRef ), NULL, &cgContext );
			          HIViewGetFrame(
                           theCont,
                           &theHIRect);
    /*    GetControlID(
        theCont,
        &theID);
*/
    theKind = GetEventKind(inEvent);
    GetControlBounds(theCont,&theRect);
    
    switch(theKind){
        case kEventControlHit:
        case kEventControlClick:
            
            break;
        case kEventControlDraw:
/*            ookRect = theRect;
            ookRect.bottom = ookRect.top + hi-2;
            ookRect.right -=1;
            RGBForeColor(&redddd);
            MoveTo(ookRect.left,ookRect.bottom-10);
            DrawString("\pFile locked, no modification");
            RGBForeColor(&oldColor);
*/
{RGBColor ffRed = {0xffff,0,0};
         CGContextSelectFont(cgContext, "Lucida Grande", nowCD->fontSize, kCGEncodingMacRoman);
         CGContextSetTextDrawingMode (cgContext,  kCGTextFill);          
	CGContextScaleCTM (cgContext, 1,-1);// -1.0);
	CGDrawStringAtRGBColor( cgContext,"\pFile locked, no modification",0,(theHIRect.size.height-2)*-1/* -10*/,&ffRed);
}
            break;
            
    }
    
    
//    mPullPort;
    return(myErr);
    
}
static  OSStatus PIPosPaneEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    // all we're doing is drawing
    //    nowCD->numColumns;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    OSStatus myErr = noErr;

    if(nowCD){
    SInt64 forkLen;
    ControlRef theCont;
    Rect theRect,ookRect;
    ControlID theID;
    UInt32 theKind;
    short hPos = 2;
    short vPos=nowCD->cellHi;
    short hi = nowCD->cellHi;
	HIRect theHIRect,innerHIRect;
	CGContextRef cgContext ;
    SInt64 byteCounter  = nowCD->displaying.bufStartInFile + nowCD->displaying.offsetInBuffer;
    short oldFontSize;
    SInt16 outItemHit;
    GetEventParameter( inEvent, kEventParamCGContextRef, typeCGContextRef,
			NULL, sizeof( CGContextRef ), NULL, &cgContext );


    mPushPort((WindowRef)inUserData);
    GetEventParameter (inEvent, kEventParamDirectObject, typeControlRef,
                       NULL, sizeof(ControlRef), NULL, &theCont);
    theKind = GetEventKind(inEvent);
			          HIViewGetFrame(
                           theCont,
                           &theHIRect);
theHIRect.origin.x=theHIRect.origin.y=0;
// works	 PaintCGRectWithRGBColorPtr(cgContext,theHIRect,&gBlack);

						   innerHIRect = theHIRect;
    GetControlBounds(theCont,&theRect);
    
    switch(theKind){
        case kEventControlHit:
        case kEventControlClick:
            
            break;
        case kEventControlDraw:

{
innerHIRect.origin.y=2;

         CGContextSelectFont(cgContext, "Lucida Grande", nowCD->fontSize, kCGEncodingMacRoman);
         CGContextSetTextDrawingMode (cgContext,  kCGTextFill);          
	CGContextScaleCTM (cgContext, 1,-1);// -1.0);
	
	
	
//	 PaintCGRectWithRGBColorPtr(cgContext,innerHIRect,&gBlack);

            ookRect = theRect;
            ookRect.bottom = ookRect.top + hi-2;
            ookRect.right -=1;
            //            mPushPort(theWindow);
            oldFontSize=         GetPortTextSize(GetWindowPort(theWindow)) ;
//	theHIRect.origin.x = theRect.left;
//		theHIRect.origin.y = theRect.top;
            
            //           TextSize(nowCD->fontSize);
            innerHIRect.size.height =nowCD->fontSize;
            switch(nowCD->forkShowing){	
case kPIMainShowingDataFork:
                forkLen =nowCD->theFT->dataForkLen; 
    break;
case kPIMainShowingResFork:
    forkLen =nowCD->theFT->resForkLen; 
                break;  
case    kPIMainShowingNoFork:
    forkLen = kFileBufferSize;
    break;
            };
			
			
			// quickly do this
			if( (gAddPrefs.windowFlags&kIgnoreRightSizedPosPane) == 0){
			Str255 theS8;
			NumToString(forkLen,theS8);
			nowCD->calcedNewPosWidth = CGStringWidth(cgContext,theS8);
			}
			
                while(ookRect.bottom < theRect.bottom && byteCounter <=forkLen ){
                    // font size needs to be the same as the pane
                    if(nowCD->drawingPosAs == kDrawingAddyInDec){

	CGNumInBoxRightJust(cgContext,byteCounter,&innerHIRect);              

    } else {
        CGHexNumInBoxRightJust(cgContext,byteCounter,&innerHIRect,(kslibHexLongNoDollar | kslibHexLongNoLeadingZeros));
    }
        
    
	innerHIRect.origin.y +=nowCD->cellHi;
	                    ookRect.top+=hi;
                    ookRect.bottom+=hi;
                    byteCounter+=nowCD->numColumns;
                }
                
                // mPullPort
}				
                break;
				
 
			           
    }
    
    
    mPullPort;
    }
    return(myErr);
    
}

// Filtered pane
static  OSStatus PITransPaneEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    ControlRef theCont;
    ControlPartCode part;
    ControlID theID;
    UInt32 theKind;
    OSStatus myErr = noErr;
    mPushPort((WindowRef)inUserData);
    GetEventParameter (inEvent, kEventParamDirectObject, typeControlRef,
                       NULL, sizeof(ControlRef), NULL, &theCont);
    /*    GetControlID(
        theCont,
        &theID);
*/   
    theKind = GetEventKind(inEvent);
    
    
    
    switch(theKind){
        case kEventControlHit:
            
            break;
        case kEventControlDraw:
        {Rect bRect;
            GetControlBounds(
                             theCont,
                             &bRect);
            EraseRect(&bRect);
            ColDrawRect(&bRect,kForTransData,(WindowRef)inUserData);
            
            RGBForeColor(&gBlack);
            Debugger(); DrawData((WindowRef)inUserData,kDrawTransData);
            
        }
            break;
        case kEventControlClick:
            break;
    }
    
    mPullPort;
    
    return(noErr);
}



static  void ColDrawRectQuartz(CGContextRef cgContext,short forWhat, PIMainWDataP  nowCD )
{
    HIRect columnRect;
    HIRect theHIRect;
    short qq,limit,widde;
    Boolean switcher=true;
    // rectanlge has been erased
    // first column blue or white?
    if(gAddPrefs.horizontalBars == 0){
    widde = nowCD->columnWidth;

    limit = nowCD->numColumns;
    switch(forWhat){
        case kForRawData:
            HIViewGetFrame(
                           nowCD->rawPane,
                           &theHIRect);
            columnRect.origin.x = 0; // theHIRect.origin.x;
            columnRect.origin.y= 0; // theHIRect.origin.y ;
            columnRect.size.height = theHIRect.size.height;
            break;
        case kForTransData:
            HIViewGetFrame(
                           nowCD->transPane,
                           &theHIRect);
            columnRect.origin.x = 0; // theHIRect.origin.x;
            columnRect.origin.y= 0; // theHIRect.origin.y ;
            columnRect.size.height = theHIRect.size.height;
            
            widde *=2;
            break;
    }
    columnRect.size.width =widde;
    for(qq=0;qq<limit;qq++){
        if(switcher){
            PaintCGRectWithCGRGBColorPtr(cgContext,columnRect,&gTheColors[kRightColColor]);

            switcher=false;
        } else {
            switcher=true;
            PaintCGRectWithCGRGBColorPtr(cgContext,columnRect,&gTheColors[kLeftColColor]);

        }
        columnRect.origin.x +=widde;
        
        
    }
    } else {
        widde = nowCD->cellHi;
	
        limit = nowCD->numRows;
        switch(forWhat){
            case kForRawData:
                HIViewGetFrame(
                               nowCD->rawPane,
                               &theHIRect);
                columnRect.origin.x = 0; // theHIRect.origin.x;
                columnRect.origin.y= 0; // theHIRect.origin.y ;
                columnRect.size.width = theHIRect.size.width;
                break;
            case kForTransData:
                HIViewGetFrame(
                               nowCD->transPane,
                               &theHIRect);
                columnRect.origin.x = 0; // theHIRect.origin.x;
                columnRect.origin.y= 0; // theHIRect.origin.y ;
                columnRect.size.width = theHIRect.size.width;
                
                //            widde *=2; dont need this for rows
                break;
        }
        columnRect.size.height =widde;
        theHIRect.origin.x=0;
        theHIRect.origin.y=0;
        PaintCGRectWithCGRGBColorPtr(cgContext,theHIRect,&gTheColors[kLeftColColor]);

        for(qq=0;qq<limit;qq++){
            if(switcher){
                PaintCGRectWithCGRGBColorPtr(cgContext,columnRect,&gTheColors[kRightColColor]);
                
                switcher=false;
            } else {
                switcher=true;
                PaintCGRectWithCGRGBColorPtr(cgContext,columnRect,&gTheColors[kLeftColColor]);
                
            }
            columnRect.origin.y +=widde;
            
            
        }
        
        
    }
    
}




void CalcNumColumns(CGContextRef inRef, WindowRef theWindow)
{   WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    short oldFontSize,oldFontNum;
    Rect wRect;
    short colArea;
    FontInfo  info;
	CGContextRef cgContext=0;
    // OK, we'll do this based on the character width the loser has specified
    mPushPort(theWindow);
    oldFontSize=         GetPortTextSize(GetWindowPort(theWindow)) ;
    oldFontNum=        GetPortTextFont(GetWindowPort(theWindow))  ;
    
    TextSize(nowCD->fontSize);
    //    TextFont(nowCD->fontNum);
#if 0
	if(inRef == 0){
		QDBeginCGContext( GetWindowPort(theWindow), &cgContext );
	         
	CGContextSelectFont(cgContext, "Lucida Grande", nowCD->fontSize, kCGEncodingMacRoman);
	} else {
	cgContext = inRef;
	CGContextSelectFont(cgContext, "Lucida Grande", nowCD->fontSize, kCGEncodingMacRoman);

	}
#endif	
    nowCD->charWide = CharWidth(/*cgContext,*/ 'W'); // get the width of a W (duh)
/*
	if(inRef == 0)
		QDEndCGContext( GetWindowPort(theWindow), cgContext );
*/		
    TextFont(oldFontNum);
    // why am I reseting this????? 
// fixed     TextSize(oldFontSize);
    mPullPort
        nowCD->columnWidth =nowCD->charWide; //  + 2; // guttering NOT NEEDED
                                             //    nowCD->cellHi = 16; // make algorythmic;
    GetFontInfo(&info);                    //              AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER;
    nowCD->cellHi = nowCD->fontSize + 7; // info.ascent+info.descent+info.leading + 4; // 4?
    GetWindowPortBounds(theWindow,&wRect );
    colArea = (wRect.right - wRect.left)- nowCD->ullage;
    if(nowCD->showingHex == false){
        // add some of th ullage back
        colArea += 20;
    }
    
    colArea = colArea / nowCD->columnWidth;
    // if hex is showing, dived out
    
    nowCD->oldNumColumns = nowCD->numColumns;
    if(nowCD->showingHex)
        nowCD->numColumns = colArea  / 3;
    else
        nowCD->numColumns = colArea;
    
    
    
    
}

void CalcNumRows(WindowRef theWindow)
{
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    
    nowCD->numRows =  (nowCD->rawTargetRect.bottom-nowCD->rawTargetRect.top)/nowCD->cellHi;
    // and how much that is in bytes
    nowCD->sizeDataInPane =  nowCD->numRows *  nowCD->numColumns;
    (*tempWC)->arrowAmount=1;
    (*tempWC)->pageAmount=nowCD->numRows;
    
    
}
void SetScrollValues(PIMainWDataP nowCD,UInt64 filePos)
{
    
    ULong maxVal =0;
    UInt32 nowVal=0;
    switch(nowCD->forkShowing){	
        case kPIMainShowingDataFork:
if(nowCD && nowCD->theFT)
            maxVal =nowCD->theFT->dataForkLen; 
            break;
        case kPIMainShowingResFork:
if(nowCD && nowCD->theFT)
            maxVal =nowCD->theFT->resForkLen; 
            break;  
        case    kPIMainShowingNoFork:
            maxVal= kFileBufferSize;
            break;
    };	
    
    
    
    maxVal = maxVal / nowCD->numColumns;
    // figure out the val now
    nowVal = filePos/nowCD->numColumns;
    
    SetControl32BitMaximum(nowCD->rawScroll,maxVal);
    SetControl32BitMaximum(nowCD->transScroll,maxVal);
    SetControl32BitValue(nowCD->rawScroll,nowVal);   //nowCD->displaying.posInFile/nowCD->numColumns);
    SetControl32BitValue(nowCD->transScroll,nowVal); // nowCD->displaying.posInFile/nowCD->numColumns);
    HIViewSetNeedsDisplay(
                          nowCD->rawPane,
                          true);
    HIViewSetNeedsDisplay(
                          nowCD->transPane,
                          true);
    
    UpdateCellPoses(nowCD->startSel,  nowCD);
    if(nowCD->compDrawer){
        UpdateDiffViews(nowCD,nowCD->compDrawer);
    }
    
}
// every time the scroll bar moves or the window is resized we check here before redisplay

OSStatus CouldReadDataChunk(PIMainWDataP nowCD,UInt16 flags)
{
    //    WCH tempWC = (WCH)GetWRefCon(theWindow);
    //    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    OSErr myErr = noErr;
    LoopVar qq;
    FileTrackerPtr theFile = nowCD->theFT;
    FileTrackerPtr theComparingFile = nowCD->comparingWithFile;

    UInt32 currentVal = GetControl32BitValue(nowCD->rawScroll);
    UInt64 theOffsetStart = (currentVal * nowCD->numColumns);
    UInt64 theOffsetEnd = theOffsetStart + nowCD->sizeDataInPane;
    // so, what we have to do here is
    // 1. determine what file range should be displayed right now
    // 2. see if that file range already lives in our buffer
    // if so, just go away
    // if not, read it in
    // and if forcereread is on, just clear the current settings
    if(nowCD->forkShowing == kPIMainShowingNoFork)return(noErr);
    
    if(flags & kForceReReadBuffer){
        SInt16 forkRef=0 ;
        SInt16 compareForkRef = 0;
        if(nowCD->forkShowing==0){
            forkRef =theFile->dataForkRef; 
            if(theComparingFile)
                compareForkRef =theComparingFile->dataForkRef; 

        } else {
            forkRef =theFile->resForkRef; 
            if(theComparingFile)
                compareForkRef =theComparingFile->resForkRef; 
            
        }

        if(forkRef){
        myErr=    FSReadFork ( forkRef,fsFromStart,  theOffsetStart,
                               kFileBufferSize,
                               nowCD->displaying.fileBuffer,
                               0   // change this
                               );
        //  reading compare file
             
        }
        if(compareForkRef){
            myErr=    FSReadFork ( compareForkRef,fsFromStart,  theOffsetStart,
                                   kFileBufferSize,
                                   nowCD->comparing.fileBuffer,
                                   0   // change this
                                   );
        }
        
        // and reset our displaying vars
        nowCD->displaying.bufStartInFile= theOffsetStart;
        nowCD->displaying.offsetInBuffer = 0;
        nowCD->displaying.posInFile = theOffsetStart;
// set this, ignore file presence, doesn't matter
        nowCD->comparing.bufStartInFile= theOffsetStart;
        nowCD->comparing.offsetInBuffer = 0;
        nowCD->comparing.posInFile = theOffsetStart;
        
        // and since we're read fromt he file, we have to walk through our change list and update the in-memory copy of the changes
        for(qq=0;qq<kFileBufferSize;qq++)*(nowCD->modBuffer +qq) = 0;
        
        FillInPendingChanges(nowCD);
        return(myErr);
    }
    // so.....
    if(((theOffsetStart >= nowCD->displaying.posInFile )&& (theOffsetEnd <= (nowCD->displaying.bufStartInFile + kFileBufferSize ))) ){
        // everything is good
        // set the position we are at inside the buffer then
        // well, we don't really need to do anything
        // well yes we do, we have to set offSet in Buffer so it'll work
        nowCD->displaying.offsetInBuffer = theOffsetStart - nowCD->displaying.bufStartInFile;
        if(nowCD->displaying.offsetInBuffer < 0)nowCD->displaying.offsetInBuffer = 0;
       nowCD->comparing.offsetInBuffer= nowCD->displaying.offsetInBuffer;
// dang it, need to do the same for the comparo.  They continue to be the same as their counterparts
       nowCD->comparing.offsetInBuffer = theOffsetStart - nowCD->displaying.bufStartInFile;
       if(nowCD->comparing.offsetInBuffer < 0)nowCD->comparing.offsetInBuffer = 0;
       nowCD->comparing.offsetInBuffer= nowCD->displaying.offsetInBuffer;
       
       
       myErr = noErr;
    } else {
        // first, there is a chance that we've reached the end of the file
        UInt32 forkLen;
        if(nowCD->forkShowing==0){
            forkLen =nowCD->theFT->dataForkLen; 
        } else {
            forkLen =nowCD->theFT->resForkLen; 
            
        }
        if(theOffsetEnd >= forkLen+nowCD->sizeDataInPane ){
            // still OK, we don't want to read off the end
            myErr = noErr;
        } else {
            // I guess we have to read
            // nothing before this in this path affects the compare file, that starts here
            
            {	SInt16 compareForkRef = 0;	
                SInt16 forkRef ;
                if(nowCD->forkShowing==0){
                    forkRef =theFile->dataForkRef; 
                    if(theComparingFile)
                        compareForkRef =theComparingFile->dataForkRef; 

                } else {
                    forkRef =theFile->resForkRef; 
                    if(theComparingFile)
                        compareForkRef =theComparingFile->resForkRef; 
                    
                }
                
                
                myErr=    FSReadFork (forkRef,fsFromStart,  theOffsetStart,
                                      kFileBufferSize,
                                      nowCD->displaying.fileBuffer,
                                      0   // change this
                                      );
                if(compareForkRef){
                    // I think we have to see if it's even in the comparefuile range
                    myErr=    FSReadFork ( compareForkRef,fsFromStart,  theOffsetStart,
                                           kFileBufferSize,
                                           nowCD->comparing.fileBuffer,
                                           0   // change this
                                           );
                }
                
            }
            
            // and reset our displaying vars
            nowCD->displaying.bufStartInFile= theOffsetStart;
            nowCD->displaying.offsetInBuffer = 0;
            nowCD->displaying.posInFile = theOffsetStart;
            nowCD->comparing.bufStartInFile= theOffsetStart;
            nowCD->comparing.offsetInBuffer = 0;
            nowCD->comparing.posInFile = theOffsetStart;
            // and since we're read fromt he file, we have to walk through our change list and update the in-memory copy of the changes
            for(qq=0;qq<kFileBufferSize;qq++)*(nowCD->modBuffer +qq) = 0;
            
            FillInPendingChanges(nowCD);
        }
    }
    
    return(myErr);
}
void DrawFileInfo(PIMainWDataP nowCD,UInt16 flags)
{
    WindowRef theWindow = nowCD->us;
    short hPos=10;
    Rect winRect;
    short lineHi = 16;
    short vPos;
    FSCatalogInfoPtr fsCatInfo =nowCD->theFT->fsCatInfo;
    GetWindowPortBounds((theWindow),&winRect);
    vPos = winRect.bottom - kInfoPaneSize + lineHi;
    MoveTo(hPos,vPos);
    DrawString("\pFile data fork size: ");
    WriteNum(fsCatInfo->dataLogicalSize);
    vPos += lineHi;
    MoveTo(hPos,vPos);
    DrawString("\pFile resource fork size: ");
    WriteNum(fsCatInfo->rsrcLogicalSize);
    
    
}

// new stuff has been read in, or a new change has been applied, so see if we have anything that needs to be updated
void             FillInPendingChanges(PIMainWDataP nowCD)
{changedBytePtr current;
    if(nowCD->changes){
        SInt64 startRange;
        SInt64 endRange;
        SInt64 theSpot;
        Ptr moddedPtr = nowCD->modBuffer;
        Ptr temperPtr = 0;
        current = nowCD->changes;
        startRange = nowCD->displaying.bufStartInFile;
        endRange = startRange + kFileBufferSize;
        Ptr thePtr;
        do{
            // see if this is in the current range
            if(current->realPos >=startRange && current->realPos <endRange){
                // it is in range, effect it
                // so we do what, subtract the startRange from realPos, then splat that into the buffer.  Right?
                theSpot = current->realPos - startRange;
                thePtr  = nowCD->displaying.fileBuffer + theSpot;
                *thePtr = current->currentByte;
                temperPtr = moddedPtr + theSpot;
                *temperPtr = 0xFF;
                // done
            }
            current = current->next;
        }while(current);
        
    }
    
}


void OuterExportFile(PIMainWDataP nowCD)
{
    // drop the sheet
    SInt64 largest;
    SInt64 other=nowCD->rangeEnd;
    SInt64 smallest = nowCD->rangeStart;
#if 0
    if(nowCD->forkShowing==0){
        largest = nowCD->theFT->dataForkLen; 
    } else {
        largest = nowCD->theFT->resForkLen; 
        
    }
#endif
    switch(nowCD->forkShowing){	
        case kPIMainShowingDataFork:
            largest =nowCD->theFT->dataForkLen; 
            break;
        case kPIMainShowingResFork:
            largest =nowCD->theFT->resForkLen; 
            break;  
        case    kPIMainShowingNoFork:
            largest = kFileBufferSize;
            break;
    };	
    
    
    nowCD->exportSheet =  AddExpRanWIND(nowCD-> us,smallest,other,largest,nowCD->forkShowing);
     ShowSheetWindow(
                            nowCD->exportSheet,
                            nowCD-> us);
    

}

// void         ExportFile(PIMainWDataP nowCD)








void ExportFile(WindowRef theWindow,SInt64 start,SInt64 end)

{
    
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;

    LoopVar ii;
    SInt16 readerForkRef ;
    SInt64 theRealLength = (end-start);
    Boolean limitedRange=false;
    SInt64 checkHere=0;
    OSErr myErr=0;
    FileTrackerPtr theFile = 0;
    SInt64 fileSizeLeft;
    Str15 textE = "\p.txt";

    if(theRealLength != 1){
#if 0        
    if(nowCD->forkShowing == 0){
        checkHere =nowCD->theFT->dataForkLen; 
        if(checkHere !=theRealLength){
            limitedRange=true;
        }
    } else {
        checkHere =nowCD->theFT->resForkLen; 
        if(checkHere !=theRealLength){
            limitedRange=true;
        }
    }
#endif        
        switch(nowCD->forkShowing){	
            case kPIMainShowingDataFork:
                checkHere =nowCD->theFT->dataForkLen; 
                if(checkHere !=theRealLength){
                    limitedRange=true;
                }               
                    break;
            case kPIMainShowingResFork:
                checkHere =nowCD->theFT->resForkLen; 
                if(checkHere !=theRealLength){
                    limitedRange=true;
                }               
                    break;  
            case    kPIMainShowingNoFork:
                checkHere =kFileBufferSize; 
                if(checkHere !=theRealLength){
                    limitedRange=true;
                }                break;
        };	
        
    
    
    }	
    
    
    theFile=  SimplePutFile(0,0,0,0,textE); // CFStringRef prompt,CFStringRef startName);
    if(theFile){
        // export.  File has been created.  We do care if it's being replaced, huh?  Add flags to the FileTracker
        theFile->openDataFork = true;
        theFile->openResFork = false;
        myErr = OpenFile(theFile);
        if(myErr == noErr){
            // zig zig each across
            Ptr theBuff = malloc(10000);
            
            UInt32 amountToMung=0;
            UInt32 theOffer = start;
            ByteCount   actualCount;
            // if I can't get 10k we're hurt-in
            if(theBuff){
                for(ii=0;ii<2;ii++){
                if(true /* limitedRange && ii == nowCD->forkShowing*/){
                    if(ii==0){
                        fileSizeLeft =nowCD->theFT->dataForkLen; 
               if(theRealLength != fileSizeLeft)
                   fileSizeLeft = theRealLength; 
                        WriteAPString("\pData Fork",  theFile->dataForkRef);
                        WriteAByte(0xd,  theFile->dataForkRef);                                     
                    } else {
                        fileSizeLeft =nowCD->theFT->resForkLen; 
                        if(nowCD->forkShowing == 1 && theRealLength != fileSizeLeft)
                            fileSizeLeft = theRealLength; 
                        WriteAByte(0xd,  theFile->dataForkRef);  
                        WriteAPString("\pResource Fork",  theFile->dataForkRef);                        
                        WriteAByte(0xd,  theFile->dataForkRef);                        
theOffer = 0;
                    }
                    
                    
                    
                    // both files are open
                    //I'm sitting on my pipe cleaners, which is why I keep losing them, or thinking I have (4.12.03)
                    
                    while(fileSizeLeft){
                        amountToMung = 10000;
                        if(fileSizeLeft < 10000)
                            amountToMung = fileSizeLeft;
                        
                        readerForkRef = 0;
                        if(ii==0){
                            readerForkRef =nowCD->theFT->dataForkRef; 
                        } else {
                            readerForkRef =nowCD->theFT->resForkRef; 
                            
                            
                        }		
                        
                        if(readerForkRef){
                        myErr=    FSReadFork (readerForkRef,fsFromStart,  theOffer,
                                              amountToMung,
                                              theBuff,
                                              &actualCount
                                              );}
                        
                        if(myErr == noErr){
                            myErr =
                            FSWriteFork(
                                        theFile->dataForkRef,
                                        fsFromStart,
                                        theOffer,
                                        amountToMung,
                                        theBuff,
                                        &actualCount);
                        }
                        theOffer +=10000;
                        fileSizeLeft -= amountToMung;
                        
                        
                        
                    }
                }
                }
                FSCloseFork(theFile->dataForkRef);
                DisposeFileTracker(theFile);
                free(theBuff);
            }
            
            
        }
        
    }
}



void SetUpPIMainWindowMenus(PIMainWDataP nowCD,UInt32 theID)
{
    static MenuCommand fileenablers[]={  kHICommandQuit ,kOpenPathMenuCommand,
        
        kHICommandPreferences,  kHICommandAbout,kHICommandNew,
        kHICommandOpen ,  kHICommandClose ,kExportCommand,
        kHICommandSaveAs,
        kHICommandPrint ,
        kHICommandPageSetup,kApplyChangesFileCommand,
        kHICommandAppHelp,kCompareMenuCommand,kCompareNextDiff
        
    };
    //notes menu enablers
    
    
    static MenuCommand editenablers[]={
        kHICommandCopy
    };
    MenuRef theMenu;
    LoopVar qq;
    switch(theID){
        case kFileMenu:
            EnableMenuCommand(0,kApplyChangesFileCommand);
            for(qq=0;qq<sizeof(fileenablers)/sizeof(MenuCommand);qq++){
                EnableMenuCommand(0,fileenablers[qq]);
                if(nowCD->forkShowing ==kPIMainShowingNoFork)
                    DisableMenuCommand(0,kHICommandSaveAs);
                EnableMenuItem(
                               GetMenuRef(kFileMenu),
                               kRecentSubMenuPosition);
                
            }
            if(nowCD->changes){
                EnableMenuCommand(0,kChangeFileCommand);
                EnableMenuCommand(0,kHICommandRevert);

            }
            
            break;
        case kEditMenu:
            if(nowCD->startSel){
                // font big and small, we love them all
                EnableMenuCommand(0,'FTBG');
                EnableMenuCommand(0,'FTSM');
                EnableMenuCommand(0,'shft');
                
                // enable editors
                for(qq=0;qq<sizeof(editenablers)/sizeof(MenuCommand);qq++){
                    EnableMenuCommand(0,editenablers[qq]);
                }
                // see if there is a dingus
                if(nowCD->changes){
                    UInt16 whichUndo = 0;

                    { changedBytePtr theChanges=nowCD->changes;
                     // set the item title
                        while(theChanges->next)
                            theChanges = theChanges->next;

                         switch(theChanges->changeTypeID){
                             
                             case kPIChangeTypeModRange:
                                 whichUndo = 1;
                             break;
                             
                             case kPIChangeTypePaste:
                                 whichUndo = 2;

                                 break;
                             
                             case kPIChangeTypeApplyFile:
                                 whichUndo = 3;

                             break;

                             case kPIChangeTypeSingleByte:
                                 whichUndo = 4;

                             break;
                         }
                    }
                
                    CFStringRef * theS = nowCD->generalStrings;
                    CFStringRef unD = theS[whichUndo-1];
                    SetMenuItemTextWithCFString(
                                                GetMenuRef(kEditMenu),
                                                1,
                                                unD);                  
                    
                    
                    EnableMenuCommand(0,kHICommandUndo);
                    EnableMenuCommand(0,kChangeFileCommand);

                    if(ChangedByteAtPosition( nowCD,nowCD->startSel->totalPos)){
                    EnableMenuCommand(0,'UNDS');

                }
                
                }
                // always disable paste.  Hate paste, it tastes all yuuky
                // or not.
                {                ScrapRef  scrap;
                Size size = 0;
                Size byteSize = 0;
                GetCurrentScrap(&scrap);

                GetScrapFlavorSize(
                                      scrap,
                                       'TEXT',
                                       &size);
                GetScrapFlavorSize(
                                   scrap,
                                   'byte',
                                   &byteSize);
                if(size || byteSize)
                {
                    EnableMenuCommand(0,kHICommandPaste);

                }else {
                    DisableMenuCommand(0,kHICommandPaste);}
                }
                
            }
            //
            break;
        case kToolsMenu:
            // mainly range stuff
            EnableAllMenuItems( GetMenuRef(kToolsMenu));
            if(PIHasRange(nowCD)){
                EnableMenuCommand(0,'RNGC');
                EnableMenuCommand(0,'MODR');
            } else {
                DisableMenuCommand(0,'RNGC');
                DisableMenuCommand(0,'MODR');

            }
                if(isthereanotherdiff(nowCD)){
                     EnableMenuCommand(0,'COMN');
                } else {
                    DisableMenuCommand(0,'COMN');

                }
            
                {// disable the formatter tools
                    DisableMenuCommand(0,'EFOR');
                    DisableMenuCommand(0,'EAFR');
                
                }
            break;
        case kNotesMenu:
            theMenu = GetMenuRef(kNotesMenu);
            EnableMenuItem(theMenu,1); // open
            EnableMenuItem(theMenu,3);  // new
            EnableMenuItem(theMenu,7);
            EnableMenuItem(theMenu,8);
            EnableMenuItem(GetMenuRef(kNotesMenu),9);
            
            // now the two that depend on a note being sleections
            if(   NoteAtPosition(nowCD)){
                EnableMenuItem(theMenu,4); // edit
                EnableMenuItem(theMenu,5); // delect
                
            }
                
                break;
            
    }
}



void PIPushChangesOut(PIMainWDataP nowCD)
{
    
}
void PIClearAllChanges(PIMainWDataP nowCD)
{WindowRef theWindow = nowCD->us;
    changedBytePtr theChanges = nowCD->changes;
    changedBytePtr temp = 0;
    LoopVar qq,ii;
    for(ii=0;ii<2;ii++){
        theChanges = nowCD->forkChanges[ii];
        while(theChanges){
            temp = theChanges->next;
            free(theChanges);
            theChanges = temp;
        }
        nowCD->forkChanges[ii] = 0;
    }
    nowCD->changes = 0;
    for(qq=0;qq<kFileBufferSize;qq++)*(nowCD->modBuffer +qq) = 0;
    
    HIViewSetNeedsDisplay(
                          nowCD->rawPane,
                          true);
    HIViewSetNeedsDisplay(
                          nowCD->transPane,
                          true);
    if(nowCD->compDrawer){
        UpdateDiffViews(nowCD,nowCD->compDrawer);
    }
    
    // turn off the buttons
    
    DisableControl(SnatchCRef(theWindow,'PEEK',kPeekRevertButton));
    DisableControl(SnatchCRef(theWindow,'PEEK',kPeekCommitButton));
    DisableControl(SnatchCRef(theWindow,'PEEK',kPeekNextChange));
    SetWindowModified (
                       theWindow,
                       false
                       );
    
}

// new, replaces that convaluted stuff
void CommitFileChanges(WindowRef theWindow)
{
#if 0
// save it now
PISaveFileChanges(nowCD);
docoreclose(nowCD->us);
// and shut the window
DisposeWindow(theWindow);
if(gSavesPending)gSavesPending--;
if(gSavesPending == 0 &&  gQuitting){
    // all the windows are closed, go away
    SpecialExit();
}
#endif
}
static  OSStatus PICommitHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    DialogRef                             outSheet;
    AlertStdCFStringAlertParamRec theRec;
    // bring a sheet down
    OSStatus myErr = 0;
    
    ShowSheetWindow(
                    nowCD->commitSheet,
                    theWindow);
    
    
    return(0);
}


#if 0
Original
static  OSStatus PICommitHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    DialogRef                             outSheet;
    AlertStdCFStringAlertParamRec theRec;
    // bring a sheet down
    OSStatus myErr = 0;
    GetStandardAlertDefaultParams(&theRec,kStdCFStringAlertVersionOne);
    theRec.cancelText=(CFStringRef)kAlertDefaultCancelText;
    theRec.cancelButton=kAlertStdAlertCancelButton;
    nowCD->currentSaveAlertLevel = 1;
    if(gAddPrefs.extraWarningOff ==false){
    myErr=    CreateStandardSheet(
                                  1,
                                  CFSTR("Confirm File Modification.  I'm going to ask you 1 more time."),
                                  CFSTR("There is no way to undo this action, the file will be permanently changed.  You should only do this to a copy unless you're sure you're doing the right thing."),
                                  &theRec,
                                  GetWindowEventTarget( theWindow),
                                  &outSheet) ;
} else    {   
    myErr=    CreateStandardSheet(
                                  1,
                                  CFSTR("Confirm File Modification."),
                                  CFSTR("There is no way to undo this action, the file will be permanently changed.  You should only do this to a copy unless you're sure you're doing the right thing."),
                                  &theRec,
                                  GetWindowEventTarget( theWindow),
                                  &outSheet) ;
}
    myErr=           ShowSheetWindow(
                                     GetDialogWindow(outSheet),
                                     theWindow);
    
    
    return(0);
}
#endif
void   pmwindDoRevert(PIMainWDataP nowCD)
{
PIClearAllChanges( nowCD);
SetWindowModified (nowCD->us,false);

CouldReadDataChunk(nowCD,kForceReReadBuffer);
}
static  OSStatus PIRevertHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    
    pmwindDoRevert(nowCD);
    return(0);
}




#if 0
void PISortChanges(PIMainWDataP nowCD)
{
    // sorting so the writes can be sequential
    // just bubble sort them, cuz I'm a tired old man
    // two forks now, sort them in placce
    changedBytePtr theChanges =    nowCD->changes;
    
    changedBytePtr backOne,backOneNext,backOnePrev;
    changedBytePtr    frontOne,frontOneNext,frontOnePrev;
    
    
    nowCD->sortedChanges = theChanges;
    return;
    
    
    
    while(theChanges->next){
        if(theChanges->realPos > (theChanges->next)->realPos){
            // swap 'em
            backOne = theChanges;
            backOneNext = theChanges->next;
            backOnePrev = theChanges->previous;
            frontOne = (theChanges->next)->next;
            frontOneNext = frontOne->next;
            frontOnePrev = frontOne->previous;
            
            backOne->next = frontOneNext;
            backOne->previous = frontOne;
            
            frontOne->next = backOne;
            frontOne->previous = backOnePrev;
            
            /*
             temp = theChanges->next;
             temp->previous = theChanges->previous;
             theChanges->next = temp->next;
             temp->next = theChanges;
             theChanges->previous = temp;
             
             */
        }
        theChanges=   backOne;
        
    }
    nowCD->sortedChanges = theChanges;
}
#endif
// undo at selection has to go from aft to fore, not the reverse
void PIUndoAtSelection(PIMainWDataP nowCD)
{LoopVar qq;
       UInt32 thePosToMatch= nowCD->startSel->totalPos;
//    changedBytePtr hasByte = ChangedByteAtPosition(  nowCD,thePosToMatch);
changedBytePtr hasByte =ChangedByteAtPositionFromBack(  nowCD,thePosToMatch);
       if(hasByte){
    // disconnect this byte
        
        // get to the end
        changedBytePtr theChanges=nowCD->changes;
        if(hasByte->previous){
            hasByte->previous->next = hasByte->next;
        } else {
        // if there is no previous, then we're at the front of the chain
            nowCD->changes = hasByte->next;
        }
        if(hasByte->next){
            hasByte->next->previous = hasByte->previous;
        }
        
        if( nowCD->changes){

        } else {
                DisableControl(SnatchCRef(nowCD->us,'PEEK',kPeekRevertButton));
                DisableControl(SnatchCRef(nowCD->us,'PEEK',kPeekCommitButton));
                DisableControl(SnatchCRef(nowCD->us,'PEEK',kPeekNextChange));
                
                nowCD->changes = 0;
            }
            //      PIClearAllChanges( nowCD);
            for(qq=0;qq<kFileBufferSize;qq++)*(nowCD->modBuffer +qq) = 0;
            
            CouldReadDataChunk( nowCD,kForceReReadBuffer);
            HIViewSetNeedsDisplay(
                                  nowCD->rawPane,
                                  true);
            HIViewSetNeedsDisplay(
                                  nowCD->transPane,
                                  true);
            
            if(nowCD->compDrawer){
                UpdateDiffViews(nowCD,nowCD->compDrawer);
            }
            
       }
        
        
        
        
        
        
        
    }



// we need to do a scroll to selection, then undo
// I'm now going to move the selection backwards, too
void         PIUndoLast(PIMainWDataP nowCD)
{
    // get to the end
    SInt64 thePosThatGotUndid=0;
    LoopVar qq;
    Byte                 theByteThatShouldBe =0;

    changedBytePtr theChanges=nowCD->changes;
    changedBytePtr killMe = 0;
    changedBytePtr freeMe = 0;
    if(theChanges){
        while(theChanges->next){
            theChanges = theChanges->next;
        }
        
        // last one
        killMe = theChanges;
        switch(killMe->changeTypeID){
            case kPIChangeTypeModRange:
                while(killMe && killMe->changeTypeID == kPIChangeTypeModRange){
                    theChanges = killMe->previous;
                    thePosThatGotUndid=killMe->realPos;
//                    theByteThatShouldBe = killMe->originalByte;
if(nowCD->forkShowing==kPIMainShowingNoFork){	
   *(nowCD->displaying.fileBuffer+  killMe->realPos) =killMe->originalByte ;
}
                    freeMe = killMe;
                    killMe = killMe->previous;

                    free(freeMe);
                    
                }
                break;                
            case kPIChangeTypePaste:
                // back up until all of these are gone, or there is nothing left.
                while(killMe && killMe->changeTypeID == kPIChangeTypePaste){
                    theChanges = killMe->previous;
                    thePosThatGotUndid=killMe->realPos;
//                    theByteThatShouldBe = killMe->originalByte;
                    if(nowCD->forkShowing==kPIMainShowingNoFork){	
                        *(nowCD->displaying.fileBuffer+  killMe->realPos) =killMe->originalByte ;
                    }
                    freeMe = killMe;
                    killMe = killMe->previous;

                    free(freeMe);
                    
                }
                break;
            case kPIChangeTypeSingleByte:
        theChanges = killMe->previous;
        thePosThatGotUndid=killMe->realPos;
//                theByteThatShouldBe = killMe->originalByte;
                if(nowCD->forkShowing==kPIMainShowingNoFork){	
                    *(nowCD->displaying.fileBuffer+  killMe->realPos) =killMe->originalByte ;
                }
        free(killMe);
                break;
        }



        //
        // see if it was the last one
        if(theChanges){
            theChanges->next = 0;
            
        } else {
            DisableControl(SnatchCRef(nowCD->us,'PEEK',kPeekRevertButton));
            DisableControl(SnatchCRef(nowCD->us,'PEEK',kPeekCommitButton));
            DisableControl(SnatchCRef(nowCD->us,'PEEK',kPeekNextChange));
            
            nowCD->changes = 0;
        }
        //      PIClearAllChanges( nowCD);
        for(qq=0;qq<kFileBufferSize;qq++)*(nowCD->modBuffer +qq) = 0;
        if(nowCD->theFT)
            CouldReadDataChunk( nowCD,kForceReReadBuffer);
        
        HIViewSetNeedsDisplay(
                              nowCD->rawPane,
                              true);
        HIViewSetNeedsDisplay(
                              nowCD->transPane,
                              true);
        
        pimwMoveToThisByte(  nowCD->us,  thePosThatGotUndid);
if(nowCD->compDrawer){
    UpdateDiffViews(nowCD,nowCD->compDrawer);
}

    }
    
}
// copy all bookmarks and add to this new file also
void SaveFileAs(PIMainWDataP nowCD)
{changedBytePtr theChanges = 0;
    // get a new file first
    long dataForkPos,resForkPos,theCount;
    UInt16 outItemHit;
    if(nowCD->forkChanges[0] || nowCD->forkChanges[1] || nowCD->changes){
        StandardAlert(
                      kAlertNoteAlert,
                      "\pThis new file will contain all your modifications. ",
                      "\p The original file will remain untouched until you explicitly save the original file.",
                      0,                          &outItemHit)   ;
        
    }


    FileTrackerPtr newFile =   SimplePutFile(CFSTR("Save this file as...."),"\puntitled",nowCD->theFT->creator,nowCD->theFT->type,nowCD->theFT->extension);
    if(newFile){
        
OSStatus myErr =        OpenBothForks(newFile);
        if(nowCD->theFT->dataForkRef){
        GetFPos(
                nowCD->theFT->dataForkRef,
                &dataForkPos);
            SetFPos(
                    nowCD->theFT->dataForkRef,
                    fsFromStart,
                    0);
            
        }
        if(nowCD->theFT->resForkRef){
            GetFPos(
                    nowCD->theFT->resForkRef,
                    &resForkPos);
            SetFPos(
                    nowCD->theFT->resForkRef,
                    fsFromStart,
                    0);
            
        }
        CopyTrackedFile(nowCD->theFT,newFile,slibCopyBothForks);
       /************************/
        // now grab the changes
        // have to sync the fork that is current
         nowCD->forkChanges[nowCD->forkShowing] = nowCD->changes;
        theChanges = nowCD->forkChanges[0];
        while(theChanges){
            theCount = 1;
            
            myErr =   FSWriteFork(newFile->dataForkRef, fsFromStart, theChanges->realPos, theCount, &theChanges->currentByte,0);

            theChanges = theChanges->next;
        }
        theChanges = nowCD->forkChanges[1];
        while(theChanges){
            theCount = 1;
            myErr =   FSWriteFork(newFile->resForkRef, fsFromStart, theChanges->realPos, theCount, &theChanges->currentByte,0);

            theChanges = theChanges->next;
        }
        
        
        
        /********************/
        CloseFile(newFile);
        if(nowCD->theFT->dataForkRef){
            SetFPos(
                    nowCD->theFT->dataForkRef,
                    fsFromStart,
                    dataForkPos);
        }
        if(nowCD->theFT->resForkRef){
            SetFPos(
                    nowCD->theFT->resForkRef,
                    fsFromStart,

                    resForkPos);
        }
        
        
    }
    
}



// 4.20.03 just decided to make a restore file if they want it also.
// 9.18.06 Forget that, that plan never became clear.
// 6.20.07 Well, a revert file is just a Changes file applied backwards, right?   That will work.
// Now we are creating "generations" of changes, capturing this set of changes as a complete set.
// this means we can have multple change sets for an active file
void PISaveFileChanges(PIMainWDataP nowCD)
{changedBytePtr theChanges = 0;
    changedBytePtr nextC = 0;
    
    UInt32 theCount;
    OSStatus myErr=noErr; 
    extern OSStatus    SavePIRestoreData(FileTrackerPtr theFT,changedBytePtr changes);
    extern Boolean AskAboutPIRestoreFile(WindowRef theWindow, FileTrackerPtr theFT);
    // sorting doesn't actually do anyting, and messes up undo order
    //    PISortChanges(nowCD);
    
/*
 // We'll do this another time
    if(AskAboutPIRestoreFile(nowCD->us,nowCD-> theFT)){
        // save off the restore file before doing anything
        
        SavePIRestoreData(nowCD->theFT,nowCD->changes);
    }
*/    
    // ok, we're saving two forks now
    // now go through the file and spew out the changes
    // have to sync the fork that is current
    nowCD->forkChanges[nowCD->forkShowing] = nowCD->changes;
    theChanges = nowCD->forkChanges[0];
    while(theChanges){
        theCount = 1;
        myErr = FSWriteFork(nowCD->theFT->dataForkRef, fsFromStart, theChanges->realPos, theCount, &theChanges->currentByte, 0);

        theChanges = theChanges->next;
    }
    theChanges = nowCD->forkChanges[1];
    while(theChanges){
        theCount = 1;
        myErr = FSWriteFork(nowCD->theFT->dataForkRef, fsFromStart, theChanges->realPos, theCount, &theChanges->currentByte, 0);

        theChanges = theChanges->next;
    }
    
    //  clear the changes
    PIClearAllChanges(nowCD);
    
    
    
}


#if 0
void PICancelSaveModifications(PIMainWDataP nowCD)
{
    nowCD->currentSaveAlertLevel = 0;
    
}
#endif
#if 0
void         PINextStageOfModSave(PIMainWDataP nowCD)
{
    DialogRef                             outSheet;
    AlertStdCFStringAlertParamRec theRec;
    OSStatus myErr = 0;
    GetStandardAlertDefaultParams(&theRec,kStdCFStringAlertVersionOne);
    theRec.cancelText=(CFStringRef)kAlertDefaultCancelText;
    theRec.cancelButton=kAlertStdAlertCancelButton;
    
    
    nowCD->currentSaveAlertLevel++;
    // John B. asked for this removal of the second confirm dialog
    if(gAddPrefs.extraWarningOff ){
        nowCD->currentSaveAlertLevel = 3;

    }
    switch(    nowCD->currentSaveAlertLevel){
        case 2:
            myErr=    CreateStandardSheet(
                                          1,
                                          CFSTR("Confirm File Modification.  This is the last chance to say NO."),
                                          CFSTR("There is no way to undo this action, If you say OK it's done."),
                                          &theRec,
                                          GetWindowEventTarget( nowCD->us),
                                          &outSheet) ;
            
            myErr=           ShowSheetWindow(
                                             GetDialogWindow(outSheet),
                                             nowCD->us);
            
            break;
        case 3:
            // They Really Mean It
            PISaveFileChanges(nowCD);
            break;
    }
    
    
}
#endif
OSStatus PIKeyHandler(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
{OSErr myErr=noErr;
    Boolean tellEm = false;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    if(tempWC){
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    UInt32 modKeys;
    Boolean holid ;
    UInt32	eventKind = GetEventKind( inEvent );
    char theChar = 0;
    // get the key
    // kEventParamKeyCode
    
    myErr = GetEventParameter( inEvent, kEventParamKeyMacCharCodes, typeChar,
                               NULL, sizeof( typeChar ), NULL,&theChar );
    
    myErr = GetEventParameter( inEvent, kEventParamKeyModifiers, typeUInt32,
                               NULL, sizeof( UInt32 ), NULL,&modKeys );
    
    // ok, we got a problem.  We need to share undo
    // Now we have modes, so we might ignore all of this.
    //  well not really ignore, huh?
    // first see if we're modifying at all
    if(nowCD->modifying == kModifying ){
        // now what are they doing?
        switch(nowCD->editingAs){
            case kEditingAsHex:
                tellEm = true;
                switch(eventKind){
                    case kEventRawKeyDown:
                    case kEventRawKeyRepeat:
                        // zamine the key
                    {
                        // is it an edit key?
                        if(!IsEditKey(theChar,0)){
                            // nope
                            // see if we're at 2 chars already, or whatever.  I.e. can we accept this key?
                            //    FitInEditText(SnatchCRef((WindowRef)inUserData,'PEEK',kPeekHexEditBox),theChar,2)
                            if(FitInEditText(SnatchCRef((WindowRef)inUserData,'PEEK',kPeekHexEditBox),theChar,2) &&
                               ((theChar >='0' && theChar <='9') || (theChar >='a' && theChar <='f') || (theChar >='A' && theChar <='F')))
                            {
                                
                                
                                
                            } else {
                                tellEm = false;
                                if(theChar == 0xd || theChar == kEnterKey){
                                    innerApplyChangeButt( nowCD );  

                                }
                            }
                        }
                    }
                        break;
                    case kEventRawKeyUp:
                        tellEm = false;
                        
                        if( (theChar >='a' && theChar <='f')){
                            tellEm = false;
                        }
                            break;
                        
                }
                    break;
            case kEditingAsAscii:
                // so really we're just gonna take the raw keycode and slam it home.  Easy as Pie
                // only care about keydonws, please
                //     holid = cmdKeyBit & modKeys;
                if((modKeys&cmdKey )){
                    tellEm = true;
                } else {
                    switch(eventKind){
                        case kEventRawKeyDown:
                        case kEventRawKeyRepeat:
                            ChangeAByte( nowCD,theChar);
                            break;
                        default:
                            break;
                    }
                }
                
                break;
                
        } // eidit as switch
    } else { 
        
	// adding key modifiers
        if(       eventKind ==            kEventRawKeyDown || eventKind == kEventRawKeyRepeat){
            SInt16 holla = 1;
            piCell * currentCell =nowCD->startSel;
            SInt64 currentPos = currentCell->totalPos;
            if(modKeys&shiftKey )holla = 10;
            
            switch(theChar){
                case kHomeKey:
                    currentPos = 0;
                    break;
                case kEndKey:
                    if(nowCD->forkShowing==0){
                        currentPos =nowCD->theFT->dataForkLen; 
                    } else {
                        currentPos =nowCD->theFT->resForkLen; 
                        
                    }
                    //				currentPos = nowCD->theFT->dataForkLen;
                    break;
                case kPageUpKey :
                    currentPos -=   (nowCD->numRows *   nowCD->numColumns)*holla;
                    break;
                case kPageDownKey:
                    currentPos +=  ( nowCD->numRows *   nowCD->numColumns)*holla;
                    
                    break;
                    
                case 			kLeftArrowKey:
                    currentPos-=1 * holla;
                    break;
                case 			kRightArrowKey:
                    currentPos+=1*holla;
                    break;
                case 			kUpArrowKey:
                    currentPos -=(nowCD->numColumns)*holla;
                    break;
                case 			kDownArrowKey:
                    currentPos +=(nowCD->numColumns)*holla;
                    break;
                    
                    
            }
            // sanity check currentPos
            
            
            
            if(currentPos < 0)
                currentPos = 0;
            UInt32 theTrueLen ;
#if 0            
            if(nowCD->forkShowing==0){
                theTrueLen = nowCD->theFT->dataForkLen; 
            } else {
                theTrueLen = nowCD->theFT->resForkLen; 
                
            }
#endif            
            switch(nowCD->forkShowing){	
                case kPIMainShowingDataFork:
                    theTrueLen =nowCD->theFT->dataForkLen; 
                    break;
                case kPIMainShowingResFork:
                    theTrueLen =nowCD->theFT->resForkLen; 
                    break;  
                case    kPIMainShowingNoFork:
                    theTrueLen = kFileBufferSize;
                    break;
            };	
            
            
            
            
            
            if(currentPos >=theTrueLen-1)
                currentPos =theTrueLen-1;
            
            
            pimwMoveToThisByte( theWindow, currentPos);
            
	}
    } // modifying if
}
    if(tellEm){
        CallNextEventHandler(
                             inHandlerCallRef,
                             inEvent);
    }
    
    
    return(myErr);
    
}
// stupid edit text.  Well, I'll try and fix it this way
// raw keyboard messing about
void InstallKeyHandlers(WindowRef theWindow)

{OSErr myErr = 0;
    EventTypeSpec keyEventList[3]={
    {kEventClassKeyboard,kEventRawKeyDown},
    {kEventClassKeyboard,kEventRawKeyRepeat},
    {kEventClassKeyboard,kEventRawKeyUp}};
    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(PIKeyHandler),     sizeof(keyEventList)/sizeof(EventTypeSpec),    &keyEventList,     (void *)theWindow,   nil);
    
}
void SnapshotWindowSize(WindowRef theWindow, PIMainWDataP nowCD)
{
    // collect everything that makes this window and controls the size they are.
    // basically, the rect, I guess.  Lets try
    SaveWindowVitalStats( theWindow,CFSTR("STANDARDSTATE"));
    
}

void SwitchAddyView(WindowRef theWindow, PIMainWDataP nowCD)
{MenuRef theMenu;
    UInt16 itemNumber =  GetMenuCommandItemNumberAndMenu('VEWH',&theMenu);

    if(nowCD->    drawingPosAs == kDrawingAddyInHex){
        nowCD->    drawingPosAs = kDrawingAddyInDec;
        SetMenuItemText(
                        theMenu,
                        itemNumber,
                     "\pView positions as Hex") ;
    } else {
        nowCD->    drawingPosAs = kDrawingAddyInHex;
        SetMenuItemText(
                        theMenu,
                        itemNumber,
                        "\pView positions as Decimal") ;
    }
    // draw1
    HIViewSetNeedsDisplay(nowCD->posPane,true);
    // draw1
    HIViewSetNeedsDisplay(nowCD->curPosThingie,true);
   
}
void pimwDoFindAgain(WindowRef theWindow, PIMainWDataP nowCD);

void PIMWNoMoreMatchesInThisWindow(WindowRef theWindow)
{       WCH tempWC = (WCH)GetWRefCon((WindowRef)theWindow);
        PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
        pimwStoreLastFind(theWindow,0);
        ContinueMultifileFind();

//        pimwDoFindAgain( theWindow,  nowCD);
}
void pimwDoFindAgain(WindowRef theWindow, PIMainWDataP nowCD)
{OSStatus myErr = 0;
    Boolean goAhead=true;
    if(nowCD->lastFindPtr == 0){
        // we're at the end of the file.  If this is a multi-file search, then kick over to the next window
        // and let that routine handle it, please
        WindowRef nextWindow =            ContinueMultifileFind();

        goAhead = false;
        if(nextWindow){
#if 0
            // there is a next window, start it out fresh
            WCH tempWC = (WCH)GetWRefCon((WindowRef)nextWindow);
            PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
            {
                SLibSearchParamBlockPtr theSearchBlock = malloc(sizeof(SLibSearchParamBlock));
                SLibSearchParamBlockPtr xtheSearchBlock =gMultiFileFindBlock->slibBlock;
                theSearchBlock->searchFlags= xtheSearchBlock->searchFlags;  
                theSearchBlock->searchLength=        xtheSearchBlock->searchLength;
                theSearchBlock->startoffset=        xtheSearchBlock->startoffset;
                theSearchBlock->resultFlags=        xtheSearchBlock->resultFlags;
                theSearchBlock-> theFile=nowCD->theFT;
                theSearchBlock-> progRoutine=xtheSearchBlock-> progRoutine;
                theSearchBlock->searchString = malloc(theSearchBlock->searchLength);
                BlockMoveData(  xtheSearchBlock->searchString,  theSearchBlock->searchString,theSearchBlock->searchLength);
                // change the offset
                theSearchBlock->startoffset=0;  // xtheSearchBlock->result->foundLocation +1;

                myErr = SLibFindInFile(theSearchBlock);
                if(myErr == noErr){ UInt32 where;
                    
                    where = theSearchBlock->result->foundLocation;
                    pimwMoveToThisByte(theWindow,where);
                    pimwStoreLastFind(theWindow,theSearchBlock);
                    
                } else {
                nowCD->lastFindPtr =0;
                }
                
                
                
                
            }
#endif            
            
        } else {
        // no nextwindow, clean up the block
            CleanUpMultiFileFind();
            goAhead = false;
        }
    }
    
    
    
    if(nowCD->lastFindPtr){
        // so what do we do?
        // duplicate the find block and make it better
        SLibSearchParamBlockPtr theSearchBlock = malloc(sizeof(SLibSearchParamBlock));
        SLibSearchParamBlockPtr xtheSearchBlock =nowCD->lastFindPtr;
        theSearchBlock->searchFlags= xtheSearchBlock->searchFlags;  
        theSearchBlock->searchLength=        xtheSearchBlock->searchLength;
        theSearchBlock->startoffset=        xtheSearchBlock->startoffset;
        theSearchBlock->resultFlags=        xtheSearchBlock->resultFlags;
        // don't want the result block
        //        theSearchBlock->result=xtheSearchBlock->result;
        theSearchBlock-> theFile=xtheSearchBlock-> theFile;
        theSearchBlock-> progRoutine=xtheSearchBlock-> progRoutine;
        theSearchBlock->searchString = malloc(theSearchBlock->searchLength);
        BlockMoveData(  xtheSearchBlock->searchString,  theSearchBlock->searchString,theSearchBlock->searchLength);
        // change the offset
        theSearchBlock->startoffset=xtheSearchBlock->result->foundLocation +1;
        PIExecuteSearch( theWindow, theSearchBlock);
#if 0        
        myErr = SLibFindInFile(theSearchBlock);
        if(myErr == noErr){ UInt32 where;
            
            where = theSearchBlock->result->foundLocation;
            pimwMoveToThisByte(theWindow,where);
            pimwStoreLastFind(theWindow,theSearchBlock);
            
        } 
#endif        
    }
    
}


extern Boolean pNavDialogOptionsDefaulted;
extern NavDialogOptions pNavDialogOpts;
extern SLIBtheFilterProc;

// changing a bit to add access to apps and such
OSStatus pimwxSimpleGetFile(FileTrackerPtr * theFT)
{
    OSStatus myErr=noErr;
    FSSpec theSpec;
    Str255 ttt = "\p Select a file to Peek";
    NavReplyRecord      reply;
    NavTypeListHandle    typeList;
    if(pNavDialogOptionsDefaulted== false){
        NavGetDefaultDialogOptions(&pNavDialogOpts);
        pNavDialogOptionsDefaulted = true;
    }
    //    NavObjectFilterUPP SLIBtheFilterProcPtr =
    //        NewNavObjectFilterUPP(SLIBtheFilterProc);
    
    // add more optionsd
    pNavDialogOpts.dialogOptionFlags =kNavSupportPackages;
    pNavDialogOpts.dialogOptionFlags |=kNavAllowOpenPackages;
    pNavDialogOpts.dialogOptionFlags |=kNavAllowMultipleFiles;
    pNavDialogOpts.dialogOptionFlags |=kNavAllowInvisibleFiles;

CopyString(ttt,    pNavDialogOpts.message);
pNavDialogOptionsDefaulted = false;
    myErr=NavGetFile(
                     0, //  AEDesc *             defaultLocation,       /* can be NULL */
                     &reply,
                     &pNavDialogOpts,
                     0, // NavEventUPP          eventProc,             /* can be NULL */
                     0, //NavPreviewUPP        previewProc,           /* can be NULL */
                     0, //                  SLIBtheFilterProc, // 0, //NavObjectFilterUPP   filterProc,            /* can be NULL */
                     0, // typeList,              /* can be NULL */
                     0); //void *               callBackUD)            /* can be NULL */ AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER;
    if (myErr == noErr) {
        if( reply.validRecord){
            AEKeyword  myKeyword;
            DescType  myActualType;
            Size   myActualSize = 0;
            // get the FSSpec for the selected file
            myErr = AEGetNthPtr(&(reply.selection), 1, typeFSS, &myKeyword, &myActualType,&theSpec, sizeof(FSSpec), &myActualSize);
            NavDisposeReply(&reply);
            // have an FSSpec, make it into a FSRef
            if(myErr == noErr){
                FileTrackerPtr theFT2=                NewFileTrackerWith(&theSpec,0);
                if(theFT2)*theFT = theFT2;
            } else {
                myErr = kErrGetFailed;
            }
        }else {            myErr = kErrGetFailed;}
    }
    return (myErr);
}

BookMarkPtr PIMainWindHaveBMToLoad(WindowRef theWindow)
{BookMarkPtr theBM;
    
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    theBM = nowCD->preload;
    return(theBM);
}
void PIMainWindHaveBMToLoadClear(WindowRef theWindow)
{    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    nowCD->preload=0;
    
}
// a little flourish
void SwashOut(short top,short right,short bottom,Boolean small)
{LoopVar qq;
    short limit = 6;
    Point oldPos;
    GetPen(&oldPos);
    top--;
    if(small){ 
        limit = 3;
    }
    for(qq=0;qq<limit;qq++){
        MoveTo(right,top);
        LineTo(right,bottom);
        if(qq<3){
            top--;
            right++;
            bottom --;
        } else {
            top++;
            bottom++;
            right++;
            
        }
    }
    
    MoveTo(oldPos.h,oldPos.v);
}




OSStatus PIWWindowConstrainCode(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
{
    OSStatus myStatus = noErr;
    WindowRef theWindow = (WindowRef)inUserData;
    
    UInt32 attributes =0;
    myStatus = GetEventParameter (inEvent, kEventParamAttributes, typeUInt32,
                                  NULL, sizeof(UInt32), NULL, &attributes);
    if (attributes & kWindowBoundsChangeSizeChanged)
    {Rect newRect;
        
        myStatus = GetEventParameter (inEvent, kEventParamCurrentBounds, typeQDRectangle,
                                      NULL, sizeof(Rect), NULL, &newRect);    
        
        if((newRect.right - newRect.left)  < 650 || (newRect.bottom - newRect.top) <170 ){
            if((newRect.right - newRect.left)  < 650)    
                newRect.right = newRect.left + 650;
            if((newRect.bottom - newRect.top) <350)
                newRect.bottom = newRect.top + 350;
            SetEventParameter(inEvent, kEventParamCurrentBounds, typeQDRectangle,sizeof(Rect), &newRect);   
            
            
            
            
        }
        
    }
    
    CallNextEventHandler(
                         inHandlerCallRef,
                         inEvent);
    return(myStatus);
    
}
SInt64 PIReturnCurrentForkLen(WindowRef theWindow){
    UInt32 theTrueLen=0;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)theWindow);
    
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
#if 0    
    if(nowCD->forkShowing==0){
        theTrueLen = nowCD->theFT->dataForkLen; 
    } else {
        theTrueLen = nowCD->theFT->resForkLen; 
    }
#endif
    switch(nowCD->forkShowing){	
        case kPIMainShowingDataFork:
            theTrueLen =nowCD->theFT->dataForkRef; 
            break;
        case kPIMainShowingResFork:
            theTrueLen =nowCD->theFT->resForkRef; 
            break;  
        case    kPIMainShowingNoFork:
            theTrueLen = kFileBufferSize;
            break;
    };	
    
    
    
    return(theTrueLen);
}

SInt64 PIReturnSelectionRealPosition(WindowRef theWindow){
    WCH tempWC = (WCH)GetWRefCon((WindowRef)theWindow);

        PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
        return(nowCD->startSel->totalPos);
}
// return the actual count of bytes provided
SInt64 PIWindowBytesFromSelToEndOfFork(PIMainWDataP nowCD)
{
    SInt64 startVar1, eofVar,tempVar3,tempVar4;
    LoopVar qq=0;
    UInt32 selPos = nowCD->startSel->totalPos;
    
#if 0    
    if(nowCD->forkShowing==0){
        eofVar =nowCD->theFT->dataForkLen; 
    } else {
        eofVar =nowCD->theFT->resForkLen; 
        
    }
#endif
    switch(nowCD->forkShowing){	
        case kPIMainShowingDataFork:
            eofVar =nowCD->theFT->dataForkRef; 
            break;
        case kPIMainShowingResFork:
            eofVar =nowCD->theFT->resForkRef; 
            break;  
        case    kPIMainShowingNoFork:
            eofVar = 0;
            break;
    };	
    
    
    
    return(eofVar - selPos);
    
}
UInt16 PIWindowGiveMeBytesAtSelection(PIMainWDataP nowCD,Ptr putHere,UInt16 howMany)
{  SInt64 startVar1, eofVar,tempVar3,tempVar4;
    LoopVar qq=0;
    UInt32 selPos = nowCD->startSel->totalPos;
    Boolean readIt = false;
    Ptr realPtr=0;
    Ptr usePtr=0;
    Ptr buffPtr =     nowCD->displaying.fileBuffer;
    startVar1=nowCD->displaying.bufStartInFile;

#if 0    
    if(nowCD->forkShowing==0){
        eofVar =nowCD->theFT->dataForkLen; 
    } else {
        eofVar =nowCD->theFT->resForkLen; 
        
    }
#endif
    switch(nowCD->forkShowing){	
        case kPIMainShowingDataFork:
            eofVar =nowCD->theFT->dataForkLen; 
            break;
        case kPIMainShowingResFork:
            eofVar =nowCD->theFT->resForkLen; 
            break;  
        case    kPIMainShowingNoFork:
            eofVar = kFileBufferSize;
            break;
    };	
    
    
    
    if(    selPos >= startVar1 && (selPos+howMany <= (nowCD->displaying.bufStartInFile + kFileBufferSize))){
    
        realPtr = nowCD->displaying.fileBuffer + (selPos - nowCD->displaying.bufStartInFile);
    } else {
    // not in the buffer, read it in
        realPtr = malloc(howMany);
        readIt = true;
        SInt16 forkRef ;
        if(nowCD->forkShowing==0){
            forkRef =nowCD->theFT->dataForkRef; 
        } else {
            forkRef =nowCD->theFT->resForkRef; 
            
        }
                
        FSReadFork (forkRef,fsFromStart,  nowCD->startSel->totalPos,
                              howMany,
                              realPtr,
                              0   // change this
                              );
        
    }
    usePtr = realPtr;
    do{
        *putHere++=*usePtr++;
        howMany--;
        qq++;
        if(qq+ selPos > eofVar){
            qq--;
            break;
        }
    }while(howMany);
     if(readIt)
        free(realPtr);
//      DrawDevStringAndNum("\pqq is",qq);

    return(qq);
}

UInt16 PIWindowGiveMeBytesAtPosition(PIMainWDataP nowCD,Ptr putHere,UInt16 howMany,SInt64 positionToStartFrom)
{  SInt64 startVar1, eofVar,tempVar3,tempVar4;
    LoopVar qq=0;
    SInt64 selPos = positionToStartFrom;
    Boolean readIt = false;
    Ptr realPtr=0;
    Ptr usePtr=0;
    Ptr buffPtr =     nowCD->displaying.fileBuffer;
    startVar1=nowCD->displaying.bufStartInFile;
    
    
    if(nowCD->forkShowing==0){
        eofVar =nowCD->theFT->dataForkLen; 
    } else {
        eofVar =nowCD->theFT->resForkLen; 
        
    }
    
    if(    selPos >= startVar1 && (selPos+howMany <= (nowCD->displaying.bufStartInFile + kFileBufferSize))){
        
        realPtr = nowCD->displaying.fileBuffer + (selPos - nowCD->displaying.bufStartInFile);
    } else {
        // not in the buffer, read it in
        realPtr = malloc(howMany);
        readIt = true;
        SInt16 forkRef ;
        if(nowCD->forkShowing==0){
            forkRef =nowCD->theFT->dataForkRef; 
        } else {
            forkRef =nowCD->theFT->resForkRef; 
            
        }
        
        FSReadFork (forkRef,fsFromStart,  nowCD->startSel->totalPos,
                    howMany,
                    realPtr,
                    0   // change this
                    );
        
    }
    usePtr = realPtr;
    do{
        *putHere++=*usePtr++;
        howMany--;
        qq++;
        if(qq+ selPos > eofVar){
            qq--;
            break;
        }
    }while(howMany);
    if(readIt)
        free(realPtr);
    //      DrawDevStringAndNum("\pqq is",qq);
    
    return(qq);
}



void UpdateAllValDrawerPopups(void)
{
//    WindowRef theWind = FrontWindow();
    WindowRef theWind =    GetFrontWindowOfClass(kDocumentWindowClass,true);

    MenuRef theMenu;
    UInt16 freddy = 0;
    while(theWind){
        if(GetWindowKind(theWind) ==    kPIMainWINDWindow){
            // get the fttracker from this one
            WCH tempWC = (WCH)GetWRefCon(theWind);
            if(tempWC){
            PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
                EnableControl(SnatchCRef(nowCD->valueDrawer,'VALD',kValDrawerPopUp));

theMenu=  GetControlPopupMenuHandle(SnatchCRef(nowCD->valueDrawer,'VALD',kValDrawerPopUp));
freddy =            AddFormattersToMenu( theMenu,kFormatterMenuClear+kFormatterMenuNoPlugIns,0);
if(freddy){
            SetControlMaximum(   SnatchCRef(nowCD->valueDrawer,'VALD',kValDrawerPopUp),         AddFormattersToMenu( theMenu,kFormatterMenuClear+kFormatterMenuNoPlugIns,0));
} else {
    DisableControl(SnatchCRef(nowCD->valueDrawer,'VALD',kValDrawerPopUp));
}
            }
            }            
        theWind = GetNextWindow(theWind);
    }
}

void TellValDrawerFormatterIsLeaving(PeekitStructFormatterPtr startHere)
{
//    WindowRef theWind = FrontWindow();
    WindowRef theWind =    GetFrontWindowOfClass(kDocumentWindowClass,true);

    MenuRef theMenu;
    while(theWind){
        if(GetWindowKind(theWind) ==    kPIMainWINDWindow){
            // get the fttracker from this one
            WCH tempWC = (WCH)GetWRefCon(theWind);
            PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
            
            WCH xtempWC = (WCH)GetWRefCon((WindowRef)nowCD->valueDrawer);
            ValDrawerDataP xnowCD = (ValDrawerDataP)(*xtempWC)->dataStore;
            if(xnowCD->theFormatter == startHere){
            xnowCD->theFormatter = 0;
                HIViewSetNeedsDisplay(xnowCD->valDrawerView,true);
            }
        }            
        theWind = GetNextWindow(theWind);
    }
}


void PIExecuteSearch(WindowRef theWindow, SLibSearchParamBlockPtr theSearchBlock)
{
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    UInt32 where=0;
    if(theSearchBlock->theFile == 0){
        theSearchBlock->theFile = nowCD->theFT;
    }
OSStatus    myErr = SLibFindInFile(theSearchBlock);
    if(myErr == noErr){
        extern void MoveToThisByte(WindowRef theWindow, SInt64 theByte);
        //            extern            void             pimwStoreLastFind(WindowRef theWindow,SLibSearchParamBlockPtr theSearchBlock);
        
        where = theSearchBlock->result->foundLocation;
        pimwMoveToThisByte(theWindow,where);
        // so a successful find, store the Find block for re-finding
        // see if there is one already
        // actually, hand it back so we don't know too much
        pimwStoreLastFind(theWindow,theSearchBlock);
    } else {
        PIMWNoMoreMatchesInThisWindow(theWindow);
        // these two need to be cleaned up somehow ••• to do          free(theSearchBlock->searchString);
        //            free(theSearchBlock);
        // does a failed search clear searahc again?  Don't think so
    }
    
    
    
}

void          waitingForDiffsProc(EventLoopTimerRef inTimer, void *inUserData)
{WindowRef theWindow = (WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;   
    if(nowCD->diffingActive == false){
    // remove this timer and have everyone redraw
        RemoveEventLoopTimer(nowCD->theDiffTimer);
        // set the initial diff set
        switch(    nowCD->forkShowing){
                case kPIMainShowingDataFork:
                    nowCD->currentDiffs=nowCD->dataForkDiffs;

                    break;
                case kPIMainShowingResFork:
                    nowCD->currentDiffs=nowCD->resForkDiffs;

                    break;  
                case    kPIMainShowingNoFork:
                    nowCD->currentDiffs==0;

                    break;
            
            
                    }
            HIViewSetNeedsDisplay(
                              nowCD->rawPane,
                              true);
        HIViewSetNeedsDisplay(
                              nowCD->transPane,
                              true);
        // and if the compate drawer is open
        if(nowCD->compDrawer){
            UpdateDiffViews(nowCD,nowCD->compDrawer);
        }
    }
}

static Boolean isthereanotherdiff(PIMainWDataP nowCD)
{Boolean retVal = false;
    SInt64    currentPos = nowCD->startSel->totalPos;
    diffByteRangePtr theDiffs = nowCD->currentDiffs;
    while(theDiffs){
        if(theDiffs->rangeStart > currentPos){
            retVal = true;
            break;
        } else {
            theDiffs = theDiffs->next;
        }
    }
    return(retVal);
}
void PIMainGotoNextDiff(WindowRef theWindow,PIMainWDataP nowCD,FileTrackerPtr withThis)
{
 diffByteRangePtr theDiffs = nowCD->currentDiffs;
 diffByteRangePtr thisDiff = 0;   
    // ok, so where are we now?
    SInt64    currentPos = nowCD->startSel->totalPos;
    // is that somewhere?
    while(theDiffs){
        if(currentPos < theDiffs->rangeStart){
            thisDiff = theDiffs;
            break;
        }
        theDiffs = theDiffs->next;
    }
    if(thisDiff){
        pimwMoveToThisByte(theWindow,thisDiff->rangeStart);
    }
}


void PIMainCompareFileStart(WindowRef theWindow,PIMainWDataP nowCD,FileTrackerPtr withThis)
{
    OSStatus myErr=0;
    FileTrackerPtr compareFile=0;
    Str255 theOldTitle;
    Str255 fishBait = "\pSelect a file to compare with ";
    // get the file first
    if(nowCD->comparingWithFile){
        if(nowCD->comparingWithFile->dataForkRef)FSCloseFork(nowCD->comparingWithFile->dataForkRef);
        if(nowCD->comparingWithFile->resForkRef)FSCloseFork(nowCD->comparingWithFile->resForkRef);
        DisposeFileTracker(nowCD->comparingWithFile);
        nowCD->comparingWithFile = 0;
        UpdateCompareFileInfoDrawer(nowCD->compDrawer);
        DisposeCompareData(nowCD);
    }
    if( withThis == 0){
    GetWTitle(
              theWindow,
              theOldTitle); 
    AppendString(theOldTitle,fishBait);
     myErr = SimpleGetFile(&compareFile,"\pSelect  file",fishBait,0);
    } else {
        compareFile = withThis;
    }
        if(myErr == noErr){
            // add this to the thingie
            nowCD->comparingWithFile=compareFile;
            // might want to OPEN THE FUCKING FILE right about here, huh?
            compareFile->openDataFork = true;
            compareFile->dataForkPerm=fsRdPerm; //read it only
            compareFile->openResFork = true;
            compareFile->resForkPerm=fsRdPerm;
            
            // get some infos
        OSStatus    fileErr=        OpenFile(compareFile);
        AddToCompareMenu(compareFile);
// force re-reading to fill the buffer            
        CouldReadDataChunk(nowCD,kForceReReadBuffer);
        if( nowCD->compDrawer == 0){
        nowCD->compDrawer =  AddDiffDWIND( theWindow);
    }
        {
            //        BuildDifferencesList(theWindow);
            
            // spin off a thread for this since it could take a while
            MPTaskID taskID;
            nowCD->diffingActive = true;
        MPCreateTask(&BuildDifferencesList, theWindow, 5000, NULL, NULL, NULL, 0, &taskID);
// and set a timer to let us all know when it's done

       
        slibInstallTimer( waitingForDiffsProc,kEventDurationMillisecond,& nowCD->theDiffTimer,theWindow );

        }
    // show it or not
        switch( gAddPrefs.diffWindowWhere){
            case kDiffWindowAsDrawer:
        OpenDrawer(
                   nowCD->compDrawer ,
                   kWindowEdgeDefault,
                   true);
            break;
case kDiffWindowAsFloat:
        ShowWindow(nowCD->compDrawer);
    break;
        }
        
        }
}


#undef __PIMainWINDOW__





















