/*
 *  Bookmarkfile.pi.c
 *  PeekIt
 *
 *  Created by C.K. Haun on Mon Jan 19 2004.
 *  Copyright (c) 2004 RavenWare Software. All rights reserved.
 *7
 */
/*
mClearCArray(gCompareArray)
gCompareArray.isType = gCompareArray.isC2 = true;
gCompareArray.unitType = 'LTXT';
gCompareArray.compare2 = (*tHand)->libID;
tempHand = ReadFullIndexedMEntry((*tHand)->theRefNum,count,'LTXT',&gTempCompare, &gCompareArray);
 //	    mFillCompare(gTempCompare, 'TLIB',0, 0, 0)

*/

#include "PeekIt.h"
#define kBMFileID 1909 

short gBookMarkRefNum;
BookMarkHeaderPtr gBookMarkHeaders;
extern GRACompare gTempCompare;
static Ptr xxxflattentitles(BookMarkPtr theMarks,long *titSize);
static Ptr xxxflattentexts(BookMarkPtr theMarks,long *textSize);
static Ptr xxxflattenmarks(BookMarkPtr theMarks,long *marksSize);

OSStatus OpenBookMarkFile(void)
{
    OSStatus myErr = noErr;
    FSRef putItHere,fileRef;
    FSSpec dirSpec;
    HFSUniStr255  fileNameU;
    FSSpec fileSpec;
    Str255 name = "\pPeekIt Notes File.pimnotes";
    Str255 name2 = "\pPeekIt Notes File.pinotes";

    CFStringRef theFileName;
    gBookMarkRefNum=0;
    myErr =  GetRavenwareFolder(&putItHere);
    // until I move the mapped calls to fsrefs I'll do this
    FSGetCatalogInfo(
                     &  putItHere,
                     kFSCatInfoNone,
                     0,       /* can be NULL */ 
                     0,           /* can be NULL */
                     &dirSpec,            /* can be NULL */
                     0);
    theFileName=     CFStringCreateWithPascalString(0,name, 0);
    
    fileNameU.length = (UInt16) CFStringGetLength(theFileName);
    CFStringGetCharacters(theFileName, CFRangeMake(0, fileNameU.length), fileNameU.unicode);
    
    myErr = FSMakeFSRefUnicode(&putItHere, fileNameU.length, fileNameU.unicode, kTextEncodingUnknown, &fileRef);
    // dang it, have to pull the fsspec outta this
    if(myErr == noErr){
        myErr =        FSRefMakeFSSpec(&fileRef,&fileSpec);
    }
    if(myErr == -43){
        // try the same thing with the old name before creating new
        theFileName=     CFStringCreateWithPascalString(0,name2, 0);        
        fileNameU.length = (UInt16) CFStringGetLength(theFileName);
        CFStringGetCharacters(theFileName, CFRangeMake(0, fileNameU.length), fileNameU.unicode);        
        myErr = FSMakeFSRefUnicode(&putItHere, fileNameU.length, fileNameU.unicode, kTextEncodingUnknown, &fileRef);
        
        
        
        if(myErr == -43){
        
        myErr = FSCreateFileUnicode(
                                    &putItHere,
                                    fileNameU.length,
                                    fileNameU.unicode,
                                    0,
                                    0,       /* can be NULL */
                                    0,            /* can be NULL */
                                    &fileSpec);           /* can be NULL */ 
                                    if(myErr == noErr){
                                        InitMFile(&fileSpec);
                                    }
                                    
    }
    }


if(myErr == noErr){
    // open the file finally
    myErr = OpenMFile(&fileSpec,fsRdWrPerm, &gBookMarkRefNum);
    if(myErr == noErr){
        UInt32 numBMs=0;
        // actually, don't do shit I guess
        // well wait, we can at least, oh nevermind
        //mFillCompare(gTempCompare, 'BMHD',1, 0, 0);
        // ok, yes I do want to do something.  Load the headers
        numBMs=        CountMEntries(gBookMarkRefNum,kBookMarkHeader);
        if(numBMs){
            ULong counter=0;
            // load all the headers in
           do{
               Handle theBMH;
               BookMarkHeaderPtr theBMP,startHere;
               theBMH =  ReadIndexedMEntry(gBookMarkRefNum,counter,kBookMarkHeader,0);
               // now make it a pointer and copy it
               theBMP = malloc(sizeof(BookMarkHeader));
               BlockMoveData((Ptr)*theBMH,(Ptr)theBMP,sizeof(BookMarkHeader));
               theBMP->next=0; // I just know I'd make that mistake   at least once
               DisposeHandle((Handle)theBMH);
               
               if(gBookMarkHeaders == 0){
                gBookMarkHeaders=theBMP;
               } else {
               // go to the end and tack this one on
                   startHere = gBookMarkHeaders;
                   while(startHere->next)startHere = startHere->next;
                   startHere->next = theBMP;

               }

               
                numBMs--;
               counter++;
           } while(numBMs);
            
            
            CheckForExpiredBMs();
        }
        FillBookMarkedFileMenu();

    }
}
}


OSStatus CloseBookmarkFile(void)
{
    OSStatus myErr = noErr;
    
    
    if(gBookMarkRefNum){
        CloseMFile(gBookMarkRefNum);
        gBookMarkRefNum=0;
    }
    return(myErr);
}

BookMarkPtr xxxexpandmarks(Ptr flatMarks,long size)
{long count = size/sizeof(BookMark);
    Ptr here = flatMarks;
    BookMarkPtr first,theBM,tempBM;
    first = 0;
    while(count--){
        theBM = malloc(sizeof(BookMark));
        BlockMoveData(here,theBM,sizeof(BookMark));
        theBM->next =0;
        theBM->back = 0;
        here = here + sizeof(BookMark);
        if(first == 0){
            first = theBM;
            tempBM = theBM; 
        }        else        {
            tempBM->next = theBM;
            theBM->back = tempBM;
            tempBM = theBM;
        
        }
        
    }
    return(first);
}
Ptr xxxflattenmarks(BookMarkPtr theMarks,long *marksSize)
{Ptr thePtr,tempPtr;

    UInt16 count=0;
    long size = 0;
    BookMarkPtr tempBM=theMarks;
    while(tempBM){
        count++;
        tempBM=tempBM->next;
    }
    size = (count*sizeof(BookMark));
    thePtr = malloc(size);
    tempPtr = thePtr;
    // walk through 'em all
    tempBM = theMarks;
    while(tempBM){
    BlockMoveData(tempBM,tempPtr,sizeof(BookMark));
    tempPtr +=sizeof(BookMark);
    tempBM=tempBM->next;
    }
    *marksSize = size;
    return(thePtr);
}

void xxxexpandtitles(BookMarkPtr theMarks,Ptr titles)
{Ptr theTitles = titles;
    BookMarkPtr theBM = theMarks;
    
    // they are in order and layed out Uint16 size - string.  If size is 0 no padding, straight to the next
    // there is an entry for each BM even if it's just a 0 size entry
    do{
        theBM->titleSize = *((UInt16 *)theTitles);
        theTitles = theTitles + sizeof(UInt16);
        if(theBM->titleSize){
            theBM->title = malloc(theBM->titleSize);
            BlockMoveData(theTitles,theBM->title,theBM->titleSize);
            theTitles = theTitles +theBM->titleSize;
        }
        theBM = theBM->next;
    }while(theBM);
    
}

// UInt16 for size

Ptr xxxflattentitles(BookMarkPtr theMarks,long *titSize)
{Ptr thePtr,tempPtr;
    Handle assemblyHandle = NewHandle(0);
    BookMarkPtr theBM = theMarks;
    while(theBM){
        AddToHandle(assemblyHandle,&theBM->titleSize,sizeof(UInt16));
        if(theBM->titleSize)
            AddToHandle(assemblyHandle,theBM->title,theBM->titleSize);
        theBM= theBM->next;
    }
    *titSize = GetHandleSize(assemblyHandle);
    thePtr = malloc(    *titSize );
    BlockMoveData(*assemblyHandle,thePtr,    *titSize );
    DisposeHandle(assemblyHandle);
    return(thePtr);
}
void xxxexpandtexts(BookMarkPtr theMarks,Ptr texts)
{Ptr theTexts = texts;
    BookMarkPtr theBM = theMarks;
    
    // they are in order and layed out Uint16 size - string.  If size is 0 no padding, straight to the next
    // there is an entry for each BM even if it's just a 0 size entry
    do{
        theBM->textSize = *((UInt16 *)theTexts);
        theTexts = theTexts + sizeof(UInt16);
        if(theBM->textSize){
            theBM->text = malloc(theBM->textSize);
            BlockMoveData(theTexts,theBM->text,theBM->textSize);
            theTexts = theTexts +theBM->textSize;
        }
        theBM = theBM->next;
    }while(theBM);
    
}


// UInt16 for size
Ptr xxxflattentexts(BookMarkPtr theMarks,long *textSize)
{Ptr thePtr;
    Handle assemblyHandle = NewHandle(0);
    BookMarkPtr theBM = theMarks;
    while(theBM){
        AddToHandle(assemblyHandle,&theBM->textSize,sizeof(UInt16));
        if(theBM->textSize)
            AddToHandle(assemblyHandle,theBM->text,theBM->textSize);
        theBM= theBM->next;
    }
    *textSize = GetHandleSize(assemblyHandle);
    thePtr = malloc(    *textSize );
    BlockMoveData(*assemblyHandle,thePtr,    *textSize );
    DisposeHandle(assemblyHandle);
    return(thePtr);
    
    return(thePtr);
}

BookMarkPtr GetBookMarksForThisFile(FileTrackerPtr theFile)
{
        BookMarkPtr theMarks=0;   
    BookMarkHeaderPtr startHere=0;
    startHere = gBookMarkHeaders;
    while(startHere){
        if(    FSCompareFSRefs(
                               theFile->fsRef,
                               & startHere->theFile) == noErr){
            // found a match
            break;
        } else {
            // go to the next one 
            startHere = startHere->next;
        }
    }
    if(startHere){
        Handle reader;
        Size theSize;
        Ptr tempPtr;
        BookMarkPtr currentMark=0;
// found it
        // id is the master ID, so we get the three parts.  two parts.  something
        mFillCompare(gTempCompare, kBookMarkMarks,startHere->masterID , 0, 0);             
      reader=  ReadMEntry(gBookMarkRefNum,&gTempCompare);
      theSize = GetHandleSize(reader);
      if(theSize){
          tempPtr = malloc(theSize);
          BlockMoveData(*reader,tempPtr,theSize);
          currentMark = xxxexpandmarks(tempPtr,theSize);
          theMarks = currentMark;
          free(tempPtr);
          
      }
        mFillCompare(gTempCompare, kBookMarkTits,startHere->masterID , 0, 0);             
     reader=   ReadMEntry(gBookMarkRefNum,&gTempCompare);
     theSize = GetHandleSize(reader);
     if(theSize){
         tempPtr = malloc(theSize);
         BlockMoveData(*reader,tempPtr,theSize);
         DisposeHandle(reader);
         xxxexpandtitles(currentMark,tempPtr);
         free(tempPtr);

     }
     
     mFillCompare(gTempCompare, kBookMarkTexts,startHere->masterID , 0, 0);             
     reader=   ReadMEntry(gBookMarkRefNum,&gTempCompare);
     theSize = GetHandleSize(reader);
     if(theSize){
         tempPtr = malloc(theSize);
         BlockMoveData(*reader,tempPtr,theSize);
         DisposeHandle(reader);
         xxxexpandtexts(currentMark,tempPtr);
         free(tempPtr);

     }
     
    
    } 
    return(theMarks);
}

extern WindowRef      PIIsFileOpenYet(FileTrackerPtr theFile);

void RemoveBookMarkSet(BookMarkHeaderPtr thisOne)
{BookMarkHeaderPtr startHere =gBookMarkHeaders;
    BookMarkHeaderPtr lastOne = 0;
    
    // first see if the file is currently open
 WindowRef theWindow     ;
 FileTrackerPtr theFT = NewFileTrackerWith(   0,&thisOne->theFile);
 theWindow = PIIsFileOpenYet(theFT);
 DisposeFileTracker(theFT);
if(theWindow){
    // tell 'em
    DialogRef outAlert;
    short item;
    CreateStandardAlert(
                        kAlertNoteAlert,
                        CFSTR("Cannot delete notes for a file that is currently being Peeked."),
                        CFSTR("Close the window and try again."),       /* can be NULL */
                      0,             /* can be NULL */
                        &outAlert); 
    item = 0;
    RunStandardAlert(outAlert,0,&item);
                        SelectWindow(theWindow); 
    return; // EXIT POINT
}
    while(startHere != thisOne && startHere != 0){
        lastOne = startHere;
        startHere= startHere->next;
    }
    if(startHere){
        if(startHere == gBookMarkHeaders){
            gBookMarkHeaders = startHere->next;
    }else{
        lastOne->next = startHere->next;
    }
    } else {
    // no match.  can't be no match.  bitch
    }
    mFillCompare(gTempCompare, kBookMarkHeader,startHere->masterID , 0, 0);
    DeleteMEntry(gBookMarkRefNum, &gTempCompare);    
    mFillCompare(gTempCompare, kBookMarkMarks,startHere->masterID , 0, 0);             
    DeleteMEntry(gBookMarkRefNum, &gTempCompare);
    mFillCompare(gTempCompare, kBookMarkTits,startHere->masterID , 0, 0);             
    DeleteMEntry(gBookMarkRefNum, &gTempCompare);
    mFillCompare(gTempCompare, kBookMarkTexts,startHere->masterID , 0, 0);             
    DeleteMEntry(gBookMarkRefNum, &gTempCompare);
    
    // now have everyone re-do their menus
FillBookMarkedFileMenu();
theWindow = FindWindowByKind(kMangNoteWindWindow);
if(theWindow)
FillBookMarkedFileMenu2(theWindow);

}
OSStatus SaveBookMarksForThisFile(BookMarkPtr theMarks,FileTrackerPtr theFile)
{    OSStatus myErr = noErr;
    FSRefPtr theRef;
    BookMarkHeaderPtr startHere,hereAgain;

    // ok, I guess the first thing we do is see if there is a header with this FSRef in it
    if(theFile->fsRefIsValid== false){
    // make the spec a ref
        myErr = FSpMakeFSRef(
                     theFile->fsSpec, 
                             &theFile->fsRef); 
        if(myErr == noErr){
            theFile->fsRefIsValid=true; 
        }}
if(theFile->fsRefIsValid){
// run through a comparison of all of them
    startHere = gBookMarkHeaders;
    while(startHere){
if(    FSCompareFSRefs(
                   theFile->fsRef,
                      & startHere->theFile) == noErr){
// found a match
    break;
} else {
// go to the next one 
    startHere = startHere->next;
}
    }
    
    if(startHere== 0){
        startHere = malloc(sizeof(BookMarkHeader));
        startHere->version = kCurrentBMVersion;
        BlockMoveData(theFile->fsRef,&startHere->theFile,sizeof(FSRef));
 // number it and it's decendants
                      startHere->masterID = GetQuickUniqueMID(gBookMarkRefNum,kBookMarkHeader);

 }
    if(startHere){
        BookMarkPtr tempBMs = theMarks;
        GRACompare xxComp;
        Ptr flatMarks,flatTitles,flatText;
        long marksSize,titSize,textSize;
    // now save off
        // ok, we have one, either just made or preloaded.  It needs to be updated.
        startHere->numBookMarks = 0;
        while(tempBMs){
            startHere->numBookMarks++;
            tempBMs=tempBMs->next;
        }
        
        // set the date
             startHere->lastModified=CFAbsoluteTimeGetCurrent();
             // write it out
             mFillCompare(xxComp, kBookMarkHeader,startHere->masterID , 0, 0);

             SaveMEntry(gBookMarkRefNum,&xxComp,startHere, sizeof(BookMarkHeader));
// now write out all the bookmarks
// should we delete all the old ones first?  Probably.  I guess.  Well, only if there are more than now.  
             // dang,t hat complicates it
             // OK, forget it.  What we're stressing over is not important.  We're trying to make all the
             // titles and text stand alone.  We'll jsut flatten them and that takes all the complexity out of the probelm.
    // why is it so hard to pack a bookmark? it ain't
             flatMarks = xxxflattenmarks(theMarks,&marksSize);
             flatTitles=xxxflattentitles(theMarks,&titSize);
             flatText=xxxflattentexts(theMarks,&textSize);
             mFillCompare(gTempCompare, kBookMarkMarks,startHere->masterID , 0, 0);             
             SaveMEntry(gBookMarkRefNum,&gTempCompare, flatMarks, marksSize);
             mFillCompare(gTempCompare, kBookMarkTits,startHere->masterID , 0, 0);             
             SaveMEntry(gBookMarkRefNum,&gTempCompare, flatTitles, titSize);
             mFillCompare(gTempCompare, kBookMarkTexts,startHere->masterID , 0, 0);             
             SaveMEntry(gBookMarkRefNum,&gTempCompare, flatText, textSize);
             
    // add this in case they reopen the file this session.
             hereAgain= gBookMarkHeaders;
             if(hereAgain){
                 while(hereAgain->next)hereAgain = hereAgain->next;
                 hereAgain->next = startHere;
             } else {
                 gBookMarkHeaders = startHere;
             }
             
    }
    
    } else {
    myErr = -50;
}
    
    
    return(myErr);
    
    
    
}

OSStatus DeleteBookMarksForThisFile(BookMarkPtr theMarks,FileTrackerPtr theFile)
{    OSStatus myErr = noErr;
    
    
    
    
    return(myErr);
}


// since a bookmark could be associated with any window
OSStatus AddBookMark(BookMarkPtr theNewBM,FileTrackerPtr theFile)
{    OSStatus myErr = noErr;
    
    
    
    
    return(myErr);
    
    
    
}
OSStatus RemoveBookMark(BookMarkPtr theNewBM,FileTrackerPtr theFile)
{    OSStatus myErr = noErr;
    
    
    
    
    return(myErr);
    
    
}




void CheckForExpiredBMs(void)
{
    
}

void ExportTheseNotes(BookMarkPtr these, FileTrackerPtr theExportFile,UInt16 noteOrText)
{
    
    OSErr myErr=0;
    FileTrackerPtr theFile = 0;
    BookMarkPtr current = these;
    Str15 sedE;
        Str15 textE = "\p.txt";
        Str15 textE2 = "\p.pinotes";
        if(noteOrText == 0){
            CopyString(textE2,sedE);
        } else {
            CopyString(textE,sedE);

        }
    theFile=  SimplePutFile(0,0,0,0,sedE); 
    if(theFile){
        if(noteOrText == 0){
            theFile->openDataFork = true;
            theFile->openResFork = false;
            myErr = OpenFile(theFile);
            if(myErr == noErr){
myErr = InitMFileFromFileRefNum(theFile->dataForkRef);
myErr = ReadyMappedFile(theFile->dataForkRef);
/**********************************************/
                BookMarkPtr tempBMs = these;
                BookMarkHeaderPtr startHere,hereAgain;
                GRACompare xxComp;
                Ptr flatMarks,flatTitles,flatText;
                long marksSize,titSize,textSize;
                startHere = malloc(sizeof(BookMarkHeader));
                startHere->version = kCurrentBMVersion;
                BlockMoveData(theFile->fsRef,&startHere->theFile,sizeof(FSRef));
                // number it and it's decendants
                startHere->masterID =kBMFileID; //  GetQuickUniqueMID(theFile->dataForkRef,kBookMarkHeader);
                
                // now save off
                // ok, we have one, either just made or preloaded.  It needs to be updated.
                startHere->numBookMarks = 0;
                while(tempBMs){
                    startHere->numBookMarks++;
                    tempBMs=tempBMs->next;
                }
                
                // set the date
                startHere->lastModified=CFAbsoluteTimeGetCurrent();
                // write it out
                mFillCompare(xxComp, kBookMarkHeader,startHere->masterID , 0, 0);
                
                SaveMEntry(theFile->dataForkRef,&xxComp,startHere, sizeof(BookMarkHeader));
                // now write out all the bookmarks
                // should we delete all the old ones first?  Probably.  I guess.  Well, only if there are more than now.  
                // dang,t hat complicates it
                // OK, forget it.  What we're stressing over is not important.  We're trying to make all the
                // titles and text stand alone.  We'll jsut flatten them and that takes all the complexity out of the probelm.
                // why is it so hard to pack a bookmark? it ain't
                flatMarks = xxxflattenmarks(these,&marksSize);
                flatTitles=xxxflattentitles(these,&titSize);
                flatText=xxxflattentexts(these,&textSize);
                mFillCompare(gTempCompare, kBookMarkMarks,startHere->masterID , 0, 0);             
                SaveMEntry(theFile->dataForkRef,&gTempCompare, flatMarks, marksSize);
                mFillCompare(gTempCompare, kBookMarkTits,startHere->masterID , 0, 0);             
                SaveMEntry(theFile->dataForkRef,&gTempCompare, flatTitles, titSize);
                mFillCompare(gTempCompare, kBookMarkTexts,startHere->masterID , 0, 0);             
                SaveMEntry(theFile->dataForkRef,&gTempCompare, flatText, textSize);
                
                
                
                
                
/*********************************************/                
                
                
                
            }
            if(theFile->dataForkRef){
                FlushMFile(theFile->dataForkRef);
                FSCloseFork(theFile->dataForkRef);
            }
                DisposeFileTracker(theFile);            
            
        } else {
        // 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){
            // pretty simple
            Ptr stringBuff = malloc(1000);
            WriteAPString("\pNotes on file:",  theFile->dataForkRef);
            FSRefMakePath (theExportFile->fsRef,
                stringBuff,
                1000);
            WriteACString(stringBuff,  theFile->dataForkRef);
            WriteType(0,0,0xd, theFile->dataForkRef,kWTypeByte);

// walk through the notes
            while(current){
                Ptr theBuff;
                long toWrite;
                UInt32 oook;
                WriteAPString("\pFile Position:",  theFile->dataForkRef);
//                WriteType(current->position,0,0, theFile->dataForkRef,kWTypeLong);
                oook=current->position;
                NumToString(oook,gTempString);
                toWrite = gTempString[0];
                FSWrite(theFile->dataForkRef, &toWrite,&  gTempString[1]);

                WriteType(0,0,0xd, theFile->dataForkRef,kWTypeByte);
                toWrite = current->titleSize;
                theBuff = current->title;
                myErr =
                    FSWrite(theFile->dataForkRef, &toWrite, theBuff);
                WriteType(0,0,0xd, theFile->dataForkRef,kWTypeByte);
                toWrite = current->textSize;
                theBuff = current->text;
                myErr =
                    FSWrite(theFile->dataForkRef, &toWrite, theBuff);
                WriteType(0,0,0xd, theFile->dataForkRef,kWTypeByte);
                
                current = current->next;                
            }
            WriteAPString("\pExported from PeekIt by Ravenware, www.ravenware.com",  theFile->dataForkRef);

        } 
        if(theFile->dataForkRef)
            FSCloseFork(theFile->dataForkRef);
        DisposeFileTracker(theFile);
            
            
            
        }
        
    
    }
    
    
}
void FillBookMarkedFileMenu(void)
{
    
    UInt16 nowItem;
    MenuRef theMenu;
    OSStatus myErr = 0;
    MenuRef     iii= GetMenuRef(kNotesMenu);
    UInt16 index=1;
    HFSUniStr255 outName;
    CFStringRef theString;
    BookMarkHeaderPtr startHere =0;
    BookMarkHeaderPtr prevOne = 0;
startHere = gBookMarkHeaders;

    GetMenuItemHierarchicalMenu(
                                iii,
                                8,
                                &theMenu) ;
    DeleteMenuItems(theMenu, 1, CountMenuItems(theMenu));

    while(startHere){
            myErr= FSGetCatalogInfo(                           &startHere->theFile,                            kFSCatInfoGettableInfo,
                                                               0,       /* can be NULL */
                                                               &outName,                      /* can be NULL */
                                                               0,            /* can be NULL */
                                                               0);
        if(myErr == noErr){
        theString= CFStringCreateWithCharacters(0, &outName.unicode, outName.length);
                
                
                AppendMenuItemTextWithCFString (
                                                theMenu,
                                                theString,
                                                0,0,&nowItem
                                                );
                CFRelease(theString);
                index++; 
                prevOne = startHere;

                
        } else {
        // there was a file error on this cached file, delete it from the linkd list
        }
    // add a clear item
        
        startHere = startHere->next;
        if(prevOne)prevOne->next = startHere;
        prevOne = startHere;
        }
    AppendMenuItemTextWithCFString( theMenu, NULL, kMenuItemAttrSeparator,
                                    0, NULL );
    AppendMenuItemTextWithCFString( theMenu, CFSTR("Clear Menu"), 0,
                                    0, NULL );
    
    
    
    
}
BookMarkHeaderPtr GetNthBookMarkPtr(short index)
{ BookMarkHeaderPtr startHere =0;
    short counter = 0;
    startHere = gBookMarkHeaders;    

    while(startHere){
        if(counter == index)break;
        startHere = startHere->next;
        counter++;

    }
    return(startHere);

}


void DoBookMarkedFileMenu(short index)
{    BookMarkHeaderPtr startHere =0;
    short counter=1;
//    index++;

startHere = gBookMarkHeaders;    
while(startHere){
    if(counter == index)break;
    
    startHere = startHere->next;
    counter++;
}    
if(startHere){
    FileTrackerPtr theFile =NewFileTrackerWith(0,&startHere->theFile);
    Boolean gotIt;
    gotIt = DoesFileExist(theFile,0);
    
    if(   gotIt){
        CreateOrShowPIMainWIND(theFile,true);
    }        else {
        short outItemHit;
        OSErr fred;
fred =        StandardAlert(
                  kAlertCautionAlert,
                  "\pCould not open file.",
                  "\pThe file may not exist, cannot be found, or something.  Sorry.",
                  0,
                      &outItemHit)   ;
        
        
        
    }
}
}

// this is a packed bookmark file.  Is the file open?  I dunno, is it?
               BookMarkPtr   ExtractBookMarksFromFile(FileTrackerPtr theFT)
{
                   
                   BookMarkPtr theMarks=0;   
                       Handle reader;
                       Size theSize;
                       Ptr tempPtr;
                       BookMarkPtr currentMark=0;
                       // found it
                       // id is the master ID, so we get the three parts.  two parts.  something
                       mFillCompare(gTempCompare, kBookMarkMarks,kBMFileID, 0, 0);             
                       reader=  ReadMEntry(theFT->dataForkRef,&gTempCompare);
                       theSize = GetHandleSize(reader);
                       if(theSize){
                           tempPtr = malloc(theSize);
                           BlockMoveData(*reader,tempPtr,theSize);
                           currentMark = xxxexpandmarks(tempPtr,theSize);
                           theMarks = currentMark;
                           free(tempPtr);
                           
                       }
                       mFillCompare(gTempCompare, kBookMarkTits,kBMFileID , 0, 0);             
                       reader=   ReadMEntry(theFT->dataForkRef,&gTempCompare);
                       theSize = GetHandleSize(reader);
                       if(theSize){
                           tempPtr = malloc(theSize);
                           BlockMoveData(*reader,tempPtr,theSize);
                           DisposeHandle(reader);
                           xxxexpandtitles(currentMark,tempPtr);
                           free(tempPtr);
                           
                       }
                       
                       mFillCompare(gTempCompare, kBookMarkTexts,kBMFileID , 0, 0);             
                       reader=   ReadMEntry(theFT->dataForkRef,&gTempCompare);
                       theSize = GetHandleSize(reader);
                       if(theSize){
                           tempPtr = malloc(theSize);
                           BlockMoveData(*reader,tempPtr,theSize);
                           DisposeHandle(reader);
                           xxxexpandtexts(currentMark,tempPtr);
                           free(tempPtr);
                           
                       }
                       
                       
                    
                   return(theMarks);
                   
}
/*
 *  Bookmarklogic.pi.c
 *  PeekIt
 *
 *  Created by C.K. Haun on Tue Dec 09 2003.
 *  Copyright (c) 2003 Ravenware Software. All rights reserved.
 *
 */

#define __NOTES__


BookMarkPtr newclearbm(void)
{BookMarkPtr thePtr = malloc (sizeof(BookMark));
    if(thePtr){
    thePtr->version = kCurrentBMVersion;

        thePtr-> position=0;
         thePtr-> titleSize=0;
         thePtr-> title=0;
        thePtr->textSize=0;
         thePtr-> text=0;
         thePtr->flags=0;
         thePtr->next=0;
         thePtr->back=0;
    }
         return(thePtr);
}
void disposebm(BookMarkPtr theBM)
{
    if(theBM-> title)free(theBM-> title);
    if( theBM-> text)free(theBM->text);
    free(theBM);
}

BookMarkPtr bmNoteAtOrAfter(PIMainWDataP nowCD,UInt32 pos)
{
    // now have to pick the one for the fork we're looking at
    BookMarkPtr theBM = nowCD->theFileNotes;
    BookMarkPtr  startingPoint = theBM;
    UInt16 forkToBe=0;
    
    if(nowCD->forkShowing)forkToBe = kResForkBookMark;
    while(startingPoint){
    if(startingPoint->position >= pos && ((startingPoint->flags & kResForkBookMark) ==forkToBe )){
        break;
    }
        startingPoint = startingPoint->next;
    }
    return(startingPoint);
}

BookMarkPtr NoteAtPositionNumber(PIMainWDataP nowCD,UInt32 where){
    BookMarkPtr result = 0;
    UInt32 placeToFind =where; //  nowCD->startSel->totalPos;
    BookMarkPtr  startingPoint = nowCD->theFileNotes;
    UInt16 forkToBe=0;
    
    
    if(nowCD->forkShowing)forkToBe = kResForkBookMark;
    while(startingPoint){
        if(placeToFind == startingPoint->position && (((startingPoint->flags & kResForkBookMark) ==forkToBe ))){
            result = startingPoint;
            break;
        } else {
            startingPoint = startingPoint->next;
        }
    }
    return(result);
    
}
BookMarkPtr NoteAtPosition(PIMainWDataP nowCD)
{
return(NoteAtPositionNumber(nowCD, nowCD->startSel->totalPos));
    
}
void bmUpdateNoteButtonStates(WindowRef theWindow)
{
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    BookMarkPtr theBM = NoteAtPosition(nowCD);
    nowCD->currentNote = theBM;
    if(nowCD->theFileNotes){
        EnableControl(      SnatchCRef(theWindow,'PEEK',kExportNotes));

    } else {
    DisableControl(      SnatchCRef(theWindow,'PEEK',kExportNotes));
    }
    if(theBM){
        EnableControl( SnatchCRef(theWindow,'PEEK',kNotesDeleteNote));
        EnableControl( SnatchCRef(theWindow,'PEEK',kEditNote));
        // put it soemehwere
        nowCD->currentNote = theBM;
        
    } else {
        DisableControl( SnatchCRef(theWindow,'PEEK',kNotesDeleteNote));
        DisableControl( SnatchCRef(theWindow,'PEEK',kEditNote));

    }
    
}

void             bmUpdateNotePane(WindowRef theWindow)
{
    Draw1Control(SnatchCRef(theWindow,'PEEK',kNotesUserPane));

}
void bmRemoveNoteAtSelection(PIMainWDataP nowCD)
{
    WindowRef theWindow = nowCD->us;
    BookMarkPtr startingPoint,backGuy, frontGuy;
    startingPoint = nowCD->theFileNotes;
    UInt32 placeToFind = nowCD->startSel->totalPos;

    while(startingPoint){
        if(startingPoint->position == placeToFind)break;
        startingPoint = startingPoint->next;
    }        
    if(startingPoint){
        nowCD->bookMarksDirty = true;

        backGuy = startingPoint->back;
        frontGuy = startingPoint->next;
        if(backGuy){
            backGuy->next = frontGuy;
            if(frontGuy)frontGuy->back = backGuy;
        } else {
            // thsi one was first, so frontGUy is now first
            nowCD->theFileNotes = frontGuy;
            if(frontGuy){frontGuy->back = 0;}
        }
            disposebm(startingPoint);
    } else {
    // didn't find the position.  can't happen, I hope
    }
    startingPoint = nowCD->theFileNotes;
    if(startingPoint){
    nowCD->nextNoteIsAtByte =  startingPoint-> position; // optimizationssdfasF
        nowCD->nextNoteIsBM = startingPoint;} else {
            nowCD->nextNoteIsAtByte = 0xffffffff;
            nowCD->nextNoteIsBM;
        }
}
// currentsel has the, uuuuh, current cell
Boolean bmIsNoteDuped( PIMainWDataP nowCD)
{
    Boolean retVal = false; 
    return(retVal);
}
void bmDoNotesMenu(PIMainWDataP nowCD,SInt16 item)
{
 // itentical to the controls.
    // first one first
    switch(item){
        case 1:
            // toggle the pane
            PIDiscTriEventHandlerProc (0,0,nowCD->us );
            {            UInt16 tuna=nowCD->infoShowing ?1:0;
                SetControlData(
                               nowCD->infoCont,
                               kControlEntireControl,
                               kControlTriangleLastValueTag,
                               sizeof(tuna),
                               &tuna);
                
                SetControlValue(nowCD->infoCont,  tuna);
            
            
            Draw1Control(nowCD->infoCont);
            }
   
            break;
        case 3: // new edit delete space goto openfilewith
            PIBMarkNewNoteEventHandlerProc(0,0,nowCD->us );

            break;
        case 4:
            nowCD->preload =NoteAtPosition(nowCD); 
            bmAskForNewNote(nowCD->us,nowCD);
            break;
        case 5:
            PIBMarkDelNoteEventHandlerProc( 0,0,nowCD->us );

            break;
        case 9:
            AddMangNoteWind(0,0);

            break;
            
    }
    
}

void bmPopUpItemPicked(PIMainWDataP nowCD,SInt16 item)
{
    BookMarkPtr startingPoint;
    startingPoint = nowCD->theFileNotes;
    item--;
    while(item){
        startingPoint=startingPoint->next;
        item--;
    }
    // this should always be true, but we're paranouid
    if(startingPoint){
        UInt16 toFork;
        UInt32 toHere=startingPoint->position;
        // now we have to insure that the right fork is selected
        
        if(((startingPoint->flags & kResForkBookMark) && nowCD->forkShowing != 1) || (((startingPoint->flags & kResForkBookMark)  == 0) && nowCD->forkShowing != 0)){
        // have to switch forks
            
            SetControlValue(SnatchCRef(nowCD->us,'PEEK',kPeekDataForkRadio),0);
            SetControlValue(SnatchCRef(nowCD->us,'PEEK',kPeekDataForkRadio+1),0);
            if(startingPoint->flags & kResForkBookMark){
                SetControlValue(SnatchCRef(nowCD->us,'PEEK',kPeekResForkRadio),1);
            } else {
                SetControlValue(SnatchCRef(nowCD->us,'PEEK',kPeekDataForkRadio),1);
            
            }
            PIMainWindSwapForks(nowCD);

        }
        
        
        
        pimwMoveToThisByte(nowCD->us,toHere);
        // adjust the thingmes

        bmUpdateNoteButtonStates(nowCD->us);
        // and force the notes window to redisplete
        bmUpdateNotePane(nowCD->us);
        
    }
    
}


void         bmFitNoteIntoWindow(PIMainWDataP nowCD,BookMarkPtr theBM)
{
    WindowRef theWindow = nowCD->us;
    BookMarkPtr startingPoint,lastOne;
    startingPoint = nowCD->theFileNotes;
    lastOne = 0;
    if(startingPoint){
        // there is one (at least) so see of this one goes after or before
        lastOne = 0;

        while(startingPoint && theBM->position > startingPoint->position ){
            lastOne = startingPoint;
            startingPoint = startingPoint->next;
        }
// either less than or end
        if(startingPoint == 0){
            lastOne->next = theBM;
            theBM->back = lastOne;
        } else {
        // split where we are, lastOne is the previous and startingPoint is next
            theBM->back = lastOne;
            if(lastOne == 0){
            // this has become the front of the line
        nowCD->theFileNotes = theBM;
            } else {
                lastOne->next = theBM;                
            }
            theBM->next = startingPoint; 
            startingPoint->back = theBM;
        }
        
    } else {
    // first note
        nowCD->theFileNotes = theBM;
        nowCD->nextNoteIsAtByte =  theBM-> position; // optimizationssdfasF
        nowCD->nextNoteIsBM = theBM;
        
    }
}

// this builds many menus.
void         PIBRebuildNoteMenu(WindowRef theWindow)
{MenuRef theMenu = GetControlPopupMenuHandle (
                                              SnatchCRef(theWindow,'PEEK',kNotesPopUp)
                                              );
    MenuRef iii =  GetMenuRef(800); 

    MenuRef theOtherMenu; // = GetMenuRef(801); 
    
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
BookMarkPtr     startingPoint = nowCD->theFileNotes;
/*****/
 
    GetMenuItemHierarchicalMenu(
                               iii,
                                7,
                                &theOtherMenu) ;
/****/


DeleteMenuItems(theMenu, 1, CountMenuItems(theMenu));
    DeleteMenuItems(theOtherMenu, 1, CountMenuItems(theOtherMenu));

    // walk through the thinmuses
    while(startingPoint){
        Str255 holder;
        Str255 blank = "\pno title";
        BlockMoveData(startingPoint->title,&holder[1],startingPoint->titleSize);
        holder[0]=startingPoint->titleSize;
        if(holder[0] == 0){
            AppendString(blank,holder);
        }
        
        AppendMenuItemText (
                            theMenu,
                            holder
                            );
        AppendMenuItemText (
                            theOtherMenu,
                            holder
                            );
        startingPoint = startingPoint->next;
    }
    Draw1Control(SnatchCRef(theWindow,'PEEK',kNotesPopUp));
    // while we're in here, may as well change the note thing
    {Str255 ook;
        UInt32 count = CountMenuItems(theMenu);
        NumToString(count,ook);
        AppendString("\p notes",ook);
        if(count == 1)
            ook[0]--;
            SetControlTitle(
                    nowCD->infoCont,
                    ook);}
        
        
}


void bmAddNewNote(WindowRef theWindow,Size titSize,Ptr noteTitle,Size datSize,Ptr noteText)
{ 
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    BookMarkPtr  theBM=0;// totalpos is where we want to add this.  
        nowCD->bookMarksDirty = true;
        if(bmIsNoteDuped(nowCD)){
        // ask them
            
        }
        
        theBM = newclearbm();
        theBM-> position=nowCD->startSel->totalPos;
        theBM->titleSize=titSize;
        theBM->title=noteTitle;
        theBM->textSize=datSize;
        theBM->text=noteText;
        bmFitNoteIntoWindow(nowCD,theBM);
// new flag for a bookmark that is a resfork one
        if(nowCD->forkShowing==1){
            theBM->flags |= kResForkBookMark;
        } else {
//         theBM->flags |= kDataForkBookMark;
        }

        PIBRebuildNoteMenu(theWindow);
        bmUpdateNoteButtonStates( theWindow);
        // update the note area
        Draw1Control(SnatchCRef(theWindow,'PEEK',kNotesUserPane));

}
// user interface area
static void  bmAskForNewNote(WindowRef theWindow,PIMainWDataP nowCD)
{
// ,   nowCD->startSel->totalPos
    
   ShowSheetWindow(
                            nowCD->bmarkWindow,
                            theWindow);
    
}

static  OSStatus PIBMarkPopupEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    OSStatus myErr = noErr;
    // goes to the appropriate byte and note
    return(noErr);
}
static  OSStatus PIBMarkDelNoteEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    OSStatus myErr = noErr;
    // delete the note currently being displayed
    bmRemoveNoteAtSelection( nowCD);
    PIBRebuildNoteMenu(theWindow);
    bmUpdateNoteButtonStates( theWindow);

    // update the note area
    Draw1Control(SnatchCRef(theWindow,'PEEK',kNotesUserPane));
    
    return(noErr);
}

static  OSStatus PIBMarkNewNoteEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    OSStatus myErr = noErr;
    // create a new note for this byte
    nowCD->preload =NoteAtPosition(nowCD); 
 bmAskForNewNote(theWindow,nowCD);
    return(noErr);
}

static  OSStatus PIBMarkScrollToNoteEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    OSStatus myErr = noErr;
    
    return(noErr);
}
extern WindowRef AddExpNWind(WindowRef theWindow, BookMarkPtr theBM,FileTrackerPtr theExportFile);

static  OSStatus PIBMarkExportNoteEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    // export to any old file.
    OSStatus myErr = noErr;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    
    nowCD->expNotesDrawer= AddExpNWind( theWindow, nowCD->theFileNotes,nowCD->theFT);

       ShowSheetWindow(
                       nowCD->expNotesDrawer,
                       theWindow);
       // move these things over to the expnotes
//    ExportTheseNotes(nowCD->theFileNotes, nowCD->theFT);

        return(myErr);
}

static  OSStatus PIBMarkEditNoteEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    PIMainWDataP nowCD = (PIMainWDataP)(*tempWC)->dataStore;
    OSStatus myErr = noErr;
    nowCD->preload =NoteAtPosition(nowCD); 
    bmAskForNewNote(theWindow,nowCD);
    return(noErr);
}

static  OSStatus PIBMarkPaneEventHandlerProc( 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;
    Rect oringR;
    ControlRef theCont;
    Rect theRect,ookRect;
    Point ookPoint;
    CFStringRef theTextBlock = 0;
    ControlID theID;
    UInt32 theKind;
    short hPos,vPos;
    short oldFontSize;
    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:
            mPushPort((theWindow));
            // dang it, this makes things uneven.  We'll just combine the two
            oringR = theRect;
            vPos = theRect.top +nowCD->fontSize+ 6;
            hPos = theRect.left+2;
            MoveTo(hPos,vPos);
//            DrawString("\pNote Title: ");
            theRect.bottom = vPos;
            
                GetPen(&ookPoint);
            theRect.left = ookPoint.h;
            if(nowCD->currentNote){
            theTextBlock =  CFStringCreateWithBytes (
                                                               0,
                                                               nowCD->currentNote->title,
                                                               nowCD->currentNote->titleSize,
                                                                kCFStringEncodingMacRoman,
                                                               false );
            
            DrawThemeTextBox (
                             theTextBlock,
                               kThemeEmphasizedSystemFont,// kThemeCurrentPortFont,
                              kThemeStateActive,
                             true,
                              &theRect,
                              0,
                              0
                              );
            CFRelease(theTextBlock);
            TextFace(normal);
            theTextBlock =  CFStringCreateWithBytes (
                                                     0,
                                                     nowCD->currentNote->text,
                                                     nowCD->currentNote->textSize,
                                                     kCFStringEncodingMacRoman,
                                                     false );
            oringR.top = theRect.bottom;
            DrawThemeTextBox (
                              theTextBlock,
                             kThemeCurrentPortFont,
                              kThemeStateActive,
                              true,
                              &oringR,
                              0,
                              0
                              );
            CFRelease(theTextBlock);
            
            
            } else {
                // if there is no note there is no note.  DOn't have to tell 'em
//                DrawString("\p no note");
            }
            mPullPort;
            break;
            
    }
    
    
    mPullPort;
    return(myErr);
    
}    
/* kNotesUserPane = 4050,
kNotesPopUp,
kNotesDeleteNote,
kNotesNewNote,
kScrollToCurrentNoteByte,
kEditNote,
*/
#define mRectWide(A) A.right-A.left;
#define mRectHi(A) A.bottom-A.top;
void InitNoteSection(WindowRef PIMainWINDWindow,PIMainWDataP nowCD)
{   
    EventTypeSpec	posControlEvents[] =
{
{kEventClassControl,    kEventControlDraw}
};
EventTypeSpec	ookControlEvents[] =    {{ kEventClassControl, kEventControlHit }    };


    
MenuRef     theMenu =GetControlPopupMenuHandle (
                                                                    SnatchCRef(PIMainWINDWindow,'PEEK',kNotesPopUp)
                                                                    );
SetMenuID(theMenu,kNotePUMenuID);
    nowCD->infoShowing = 0;  
    
    HideControl( SnatchCRef(PIMainWINDWindow,'PEEK',kNotesUserPane));
    HideControl( SnatchCRef(PIMainWINDWindow,'PEEK',kNotesPopUp));
    HideControl( SnatchCRef(PIMainWINDWindow,'PEEK',kNotesDeleteNote));
    HideControl( SnatchCRef(PIMainWINDWindow,'PEEK',kNotesNewNote));
//    HideControl( SnatchCRef(PIMainWINDWindow,'PEEK',kScrollToCurrentNoteByte));
    HideControl( SnatchCRef(PIMainWINDWindow,'PEEK',kEditNote));
HideControl( SnatchCRef(PIMainWINDWindow,'PEEK',kExportNotes));

// set up the control handlers
    InstallControlEventHandler(  SnatchCRef(PIMainWINDWindow,'PEEK',kNotesUserPane),  PIBMarkPaneEventHandlerProc , GetEventTypeCount(posControlEvents), posControlEvents, PIMainWINDWindow, NULL );

InstallControlEventHandler(  SnatchCRef(PIMainWINDWindow,'PEEK',kNotesPopUp),  PIBMarkPopupEventHandlerProc , GetEventTypeCount(ookControlEvents), ookControlEvents, PIMainWINDWindow, NULL );
InstallControlEventHandler(  SnatchCRef(PIMainWINDWindow,'PEEK',kNotesDeleteNote),  PIBMarkDelNoteEventHandlerProc , GetEventTypeCount(ookControlEvents), ookControlEvents, PIMainWINDWindow, NULL );
InstallControlEventHandler(  SnatchCRef(PIMainWINDWindow,'PEEK',kNotesNewNote),  PIBMarkNewNoteEventHandlerProc , GetEventTypeCount(ookControlEvents), ookControlEvents, PIMainWINDWindow, NULL );
// InstallControlEventHandler(  SnatchCRef(PIMainWINDWindow,'PEEK',kScrollToCurrentNoteByte),  PIBMarkScrollToNoteEventHandlerProc , GetEventTypeCount(ookControlEvents), ookControlEvents, PIMainWINDWindow, NULL );
InstallControlEventHandler(  SnatchCRef(PIMainWINDWindow,'PEEK',kEditNote),  PIBMarkEditNoteEventHandlerProc , GetEventTypeCount(ookControlEvents), ookControlEvents, PIMainWINDWindow, NULL );
InstallControlEventHandler(  SnatchCRef(PIMainWINDWindow,'PEEK',kExportNotes),  PIBMarkExportNoteEventHandlerProc , GetEventTypeCount(ookControlEvents), ookControlEvents, PIMainWINDWindow, NULL );

PIBRebuildNoteMenu(PIMainWINDWindow); // fill or clear the menu
}                     
void ResizeNotesControls(WindowRef theWindow,PIMainWDataP nowCD,Rect *windRect)
{
    UInt16 width,height;
    Rect newRect,lastRect;
    ControlRef theRef;
    /*********/
theRef=    SnatchCRef(theWindow,'PEEK',kNotesNewNote);
    GetControlBounds(
                     theRef,
                     &newRect);
    width = mRectWide(newRect);
    height = mRectHi(newRect);
    newRect.bottom = windRect->bottom-4;
    newRect.left = windRect->left+4;
    newRect.top = newRect.bottom-height;
    newRect.right = newRect.left + width;
    SetControlBounds(
                     theRef,
                     &newRect);
    lastRect = newRect;
/***********/
    
        theRef=    SnatchCRef(theWindow,'PEEK',kEditNote);

    
    GetControlBounds(
                     theRef,
                     &newRect);
    width = mRectWide(newRect);
    newRect = lastRect;
    newRect.left = newRect.right + 10;
    newRect.right = newRect.left + width;
    SetControlBounds(
                     theRef,
                     &newRect);
    lastRect = newRect;
/********/    
    theRef=    SnatchCRef(theWindow,'PEEK',kNotesDeleteNote);
    
    
    GetControlBounds(
                     theRef,
                     &newRect);
    width = mRectWide(newRect);
    newRect = lastRect;
    newRect.left = newRect.right + 10;
    newRect.right = newRect.left + width;
    SetControlBounds(
                     theRef,
                     &newRect);
    lastRect = newRect;    
    /*********/
    theRef=    SnatchCRef(theWindow,'PEEK',kExportNotes);
    
    
    GetControlBounds(
                     theRef,
                     &newRect);
    width = mRectWide(newRect);
    newRect = lastRect;
    newRect.left = newRect.right + 10;
    newRect.right = newRect.left + width;
    SetControlBounds(
                     theRef,
                     &newRect);
    lastRect = newRect;
    /********/
    // add the popup
    theRef=    SnatchCRef(theWindow,'PEEK',kNotesPopUp);
    
    
    GetControlBounds(
                     theRef,
                     &newRect);
    width = mRectWide(newRect);
    newRect = lastRect;
    newRect.left = newRect.right + 10;
    newRect.right = newRect.left + width;
    SetControlBounds(
                     theRef,
                     &newRect);
    lastRect = newRect;
    
    
        
    /*******/
    // bottom of the user pane 6 above the top of the buttons?  Yeah, sure
    theRef=    SnatchCRef(theWindow,'PEEK',kNotesUserPane);
    
    
    GetControlBounds(
                     theRef,
                     &newRect);
    width = mRectWide(newRect);
    height = mRectHi(newRect);
    newRect = lastRect;
    newRect.bottom = newRect.top - 6;
    newRect.top = newRect.bottom - 75; // have to adjust this
    newRect.left = windRect->left+10;
    newRect.right = windRect->right - 10;
    SetControlBounds(
                     theRef,
                     &newRect);
    lastRect = newRect;    
/***********/    
}

#undef __NOTES__
/*
 *  Bookmarkpane.pi.c
 *  PeekIt
 *
 *  Created by C.K. Haun on Tue Dec 09 2003.
 *  Copyright (c) 2003 Ravenware Software. All rights reserved.
 *
 */

// #include "Bookmarklogic.pi.c"



// Drawer out
#define kBMarkWindSig 'BMRK'
enum {kBMarkPU=1000,kBMarkText,kBMarkRemove,kBMarkAdd};

void HitBMarkWind(WindowRef theWindow, Point *thePoint);
void GoToRware(void);

struct BMarkWindData {
    WindowRef mommy;
};


typedef struct BMarkWindData BMarkWindData;
typedef BMarkWindData *BMarkWDataP, **BMarkWDataH;
/* protos */


static void ReArrangeBMarkWControls(WindowRef theWindow, BMarkWDataH nowCD);
static void SizeBMarkWindControls(WindowRef theWindow);




static  OSStatus BMKCancelEH( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{OSStatus myErr = noErr;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    BMarkWDataH nowCD = (BMarkWDataH)(*tempWC)->dataStore;
    HideSheetWindow((WindowRef)inUserData);

    return(myErr);
}
static  OSStatus BMKOKEH( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    OSStatus myErr = noErr;
    
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    BMarkWDataH nowCD = (BMarkWDataH)(*tempWC)->dataStore;
    Ptr titData,restData;
    Size theS,theS2;
// reap the edit fileds
    // title
    ControlRef theControl = SnatchCRef(theWindow,kBMarkWindSig,1000);
    // coolet the rosebuds    
    GetControlDataSize(
                       theControl ,
                       5,
                       kControlEditTextTextTag,
                       &theS 
                       );
        titData = malloc(theS);
        GetControlData(
                       theControl ,
                       5,
                       kControlEditTextTextTag,
                       theS,
                       titData,
                       0);
// text        
 theControl = SnatchCRef(theWindow,kBMarkWindSig,1001);
        // coolet the rosebuds    
        GetControlDataSize(
                           theControl ,
                           5,
                           kControlEditTextTextTag,
                           &theS2 
                           );
            restData = malloc(theS2); 
            GetControlData(
                           theControl ,
                           5,
                           kControlEditTextTextTag,
                           theS2,
                           restData,
                           0);
            
    HideSheetWindow(theWindow);
// and hand it back to whomever called
    // which is in bookmarklogic, I guess.
    bmAddNewNote( (*nowCD)->mommy,theS,titData,theS2,restData);

    return(myErr);
}


OSStatus BMWindowShownCode(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
{
    OSStatus myStatus = noErr;
// see if there is a prefill
WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    BMarkWDataH nowCD = (BMarkWDataH)(*tempWC)->dataStore;
    BookMarkPtr hasOne = 0;
    // step up to the mommy
    hasOne  = PIMainWindHaveBMToLoad((*nowCD)->mommy);
    // turn on the saveas
    CallNextEventHandler(
                         inHandlerCallRef,
                         inEvent);
    
    if(hasOne){
        ControlRef theControl = SnatchCRef(theWindow,kBMarkWindSig,1000);
        
        // fill in the two lines
        SetKeyboardFocus(
                         theWindow,
                        theControl,
                         kControlFocusNextPart);
        SetControlData(
                       theControl ,
                       5,
                       kControlEditTextTextTag,
                       hasOne->titleSize,
                       hasOne->title);
        theControl = SnatchCRef(theWindow,kBMarkWindSig,1001);
        SetKeyboardFocus(
                         theWindow,
                         theControl,
                         kControlFocusNextPart);
        SetControlData(
                       theControl ,
                       5,
                       kControlEditTextTextTag,
                       hasOne->textSize,
                       hasOne->text);
        
        PIMainWindHaveBMToLoadClear((*nowCD)->mommy);
    }
    {    ControlRef theControl = SnatchCRef(theWindow,kBMarkWindSig,1000);

    SetKeyboardFocus(
                     theWindow,
                     theControl,
                     kControlFocusNextPart);
    }
    return(myStatus);
    
}


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

{
    OSStatus myErr = noErr;
    long realRefCon = 0;
    EventHandlerRef windowOutRef;
    EventTypeSpec  windowDrawEventList[1]={{kEventClassWindow,kEventWindowDrawContent}};
    
    EventTypeSpec  windowShowEventList[1]={{kEventClassWindow,kEventWindowShown}};
    
    EventTypeSpec  windowSizeEventList[1]={{kEventClassWindow,kEventWindowBoundsChanged}};
    
    EventTypeSpec  windowCloseEventList[1]={{kEventClassWindow,kEventWindowClose}};
    
    //    EventTypeSpec  windowSpecialEventList[1]={{kEventClassWindow,kEventWindowContextualMenuSelect}};
    
    EventTypeSpec  windowClickEventList[1]={   {kEventClassWindow,kEventWindowHandleContentClick}};
    
    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(BMWindowShownCode),     sizeof(windowShowEventList)/sizeof(EventTypeSpec),    &windowShowEventList, (void *)theWindow,      &windowOutRef);

    if(refCon == NULL)realRefCon = (long)theWindow;
    myErr = InstallStandardEventHandler(GetWindowEventTarget (theWindow));
    
    
    
    return(myErr);
    
}






WindowRef AddBMarkWind(WindowRef theWindow,FileTrackerPtr theFile)
{
#pragma unused (theFile )
    LoopVar qq;
    WindowPrefStructHdl thePrefs=nil;
    EventTypeSpec	aboutlControlEvents[] =
    {
    {kEventClassControl,    kEventControlHit}
    };
#if 0    
    EventTypeSpec	fwControlEvents[] =
    {
    {kEventClassControl,    kEventControlHit},
    {kEventClassControl,    kEventControlDraw},
    {kEventClassControl,    kEventControlClick}
        
        
    };
#endif
    
    WCH tempWC;
    BMarkWDataH nowCD;
    OSErr myErr = 0;
    AliasHandle theA;
    WindowRef BMarkWindWindow = nil;
    
    // see if it exists yet
    
    
    myErr = CreateWindowFromNib(gNibRef, CFSTR("NoteDraw"), &BMarkWindWindow);
    
    // NEW
    InstallBMarkWindowHandlers(
                              BMarkWindWindow,
                              0,
                              0);
    
    tempWC = (WCH)NewHandleClear(sizeof(windowControl));
    
    SetWindowKind(BMarkWindWindow, kSheetWindowClass);
    nowCD = (BMarkWDataH)NewHandleClear(sizeof(BMarkWindData));
    mPushPort(BMarkWindWindow)
        TextSize(9);
    
    mPullPort
        (*tempWC)->undoAction = (UndoHand)NewHandleClear(sizeof(UndoControl));
    (*tempWC)->dataStore = (Handle)nowCD;
    SetWRefCon(BMarkWindWindow, (long)tempWC);
    AddWindowID(BMarkWindWindow);
    
    /* set these goddam things */
    // new way Jose
    
    // set up the initial rects, either defaulted or saved
    SizeBMarkWindControls(BMarkWindWindow);
    InstallControlEventHandler(          SnatchCRef(BMarkWindWindow,kBMarkWindSig,1002),  BMKCancelEH , GetEventTypeCount(aboutlControlEvents), aboutlControlEvents, BMarkWindWindow, NULL );
    InstallControlEventHandler(          SnatchCRef(BMarkWindWindow,kBMarkWindSig,1003),  BMKOKEH , GetEventTypeCount(aboutlControlEvents), aboutlControlEvents, BMarkWindWindow, NULL );
    
    
    /*
    
        SetDrawerParent(BMarkWindWindow, theWindow);
        SetDrawerPreferredEdge(BMarkWindWindow,kWindowEdgeBottom);
     SetDrawerOffsets (BMarkWindWindow, 10.0, 10.0);
    */
    
    (*nowCD)->mommy = theWindow;
    
    return(BMarkWindWindow);
}



// size scroll bar and text area
static void SizeBMarkWindControls(WindowRef theWindow)
{
#pragma unused (theWindow )
    // see if we can change the menu position by mussing with the rect
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    BMarkWDataH nowCD = (BMarkWDataH)(*tempWC)->dataStore;
}






















void ReArrangeBMarkWControls(WindowRef theWindow, BMarkWDataH nowCD)
{
}








void DoBMarkWindMenu(short which)
{
    
    WindowRef theW = FindWindowByKind(kBMarkWindWindow);
    WCH tempWC = (WCH)GetWRefCon(theW);
    BMarkWDataH nowCD = (BMarkWDataH)(*tempWC)->dataStore;
#if 0
    switch(which){
        case kResetContPositions:
            ResetControlPostions();
            
            break;
            
        case 2:
            ExternRequestScreenUpdate(0x15);
            
            
            break;
            
        case 3:
        {
            if((*nowCD)->refreshOFF)
                (*nowCD)->refreshOFF = false;
            else
                (*nowCD)->refreshOFF = true;
            //  FIX		CheckItem(GetMenuHandle(5),3, ((*nowCD)->refreshOFF==true));
            
        }
            break;
        case 4:
            // say parameter
            SayBuffer(&(*nowCD)->paramName[1],(*nowCD)->paramName[0]);
            SayBuffer(&(*nowCD)->paramVal[1],(*nowCD)->paramVal[0]);
            
            break;
        case 5:
            // say whole screen
            SayBuffer((Ptr)&(*nowCD)->alltext,320);
            
            break;
    }
    
#endif
}



#undef __AboutPeekWINDOW__



