(FILECREATED " 4-Nov-87 19:05:31" {QV}<NOTECARDS>1.3KNEXT>RGPATCH063.;3 642690 

      changes to:  (VARS RGPATCH063COMS)
		   (FNS NCP.OpenCard NC.InstallTitleBarMiddleMenu NC.ShowLinks NC.CardP 
			NC.FetchStatus NC.FetchNewCardFlg NC.FetchTitle NC.FetchType NC.LinksCachedP 
			NC.ActiveCardP NC.SetFromLinks NC.SetLinksDirtyFlg NC.FetchFromLinks 
			NC.SetLinksDate NC.SetToLinks NC.SetGlobalLinks NC.CardNeedsFilingP 
			NC.TopLevelCardP NC.SetPropList NC.SetPropListDirtyFlg NC.FetchPropListDate 
			NC.SetPropListDate NC.FetchPropList NC.SetRegion NC.FetchSavedRegion 
			NC.FetchRegion NC.FetchDefaultWidth NC.FetchDefaultHeight NC.FetchItemDate 
			NC.SetItemDate NC.SetType NC.FetchLinksDate NC.FetchToLinks 
			NC.FetchGlobalLinks NC.SetTitleDate NC.SetTitle NC.ReadOnlyCardP 
			NC.SetUserDataProp NC.SetSubstance NC.MarkCardDirty NC.SetSubstanceDirtyFlg 
			NC.ActivateCard NC.FetchSubstance NC.MakeNoteCard NC.SetNewCardFlg 
			NC.DeactivateCard NC.SetTitleDirtyFlg NC.QuitCard NC.CardDirtyP 
			NC.FetchSubstanceDirtyFlg NC.FetchTitleDirtyFlg NC.FetchPropListDirtyFlg 
			NC.FetchLinksDirtyFlg NC.SetSavedRegion NC.FetchUserDataProp NC.CardSaveFn 
			NC.FetchBeingDeletedFlg NC.FetchTitleDate NC.AssignTitle NC.CheckFiling 
			NC.ObtainEditPermission NC.RetrieveTypeAndTitle NC.FetchLinkDisplayMode 
			NC.DeleteNoteCardInternal NC.SetBeingDeletedFlg NC.ClosePropListEditor 
			NC.FetchLinkIconAttachedBitMap NC.FetchLinkAnchorModesSupported 
			NC.DeleteNoteCard NC.FetchRegionViewed NC.FetchSlotNum NC.SetUserDataPropList 
			NC.AddParents NC.SeverExternalLinks NC.DeleteNoteCards NC.QuitWithoutSaving 
			NC.UnfileNoteCard NC.CollectReferences NC.EditProperties 
			NC.OpenPropListEditor NC.CardOrCardHolderFromUID NC.DeleteBadLink 
			NC.SameLinkP NC.ValidLinkP NC.DeleteLink NC.DeleteFromLink NC.DelFromLink 
			NC.FileInOrphanBox NC.HookToOrphanCard NC.MakeFilingLink NC.MakeLink 
			NC.UpdateLinkImages NC.UncacheLinks NC.MakeFilingLinks NC.AddToLink 
			NC.AddFromLink NC.DelToLink NC.DelReferencesToCard 
			NC.DelReferencesToCardFromGlobalList NC.DeleteToLink NC.ChangeLinkDisplayMode 
			NC.FetchLinkIconForLink NC.RelabelLink NC.ChangeCardTitleFromLinkIcon 
			NC.LinkIconWhenDeletedFn NC.CheckForOrphanDelete NC.InsertLinkBeforeMarker 
			NC.AddGlobalLinksToCard NC.AddLinkToCard NC.AddLinksToCard 
			NCP.CardTypeLinkDisplayMode NCP.CardTypeSuper NCP.RemoveSpecialCard 
			NCP.NoteFileFromCard NCP.CardNoteFile NCP.LocalGlobalLink 
			NCP.GlobalGlobalLink NCP.LinkType NC.GetCrossFileLinkDestCard 
			NC.CreateCrossFileLinkCard NC.AskCrossFileLinkMode NC.CheckCrossFileLinkType 
			NC.ComputeCrossFileLinkMode NC.RelayoutGraphCard 
			NC.InstallTextTitleBarMiddleMenu NC.MakeTEditCard NC.BringUpTEditCard 
			NC.TEditMenuFn NC.GetTextSubstance NC.MakeSketchCard NC.BringUpSketchCard 
			NCIDEASKETCH.MakeIdeaSketchCard NCIDEASKETCH.BringUpIdeaSketchCard 
			NC.InstallTitleBarLeftMenu NC.AskLinkLabel NC.SelectNoteCards 
			NC.AttachNoteFileName NC.CardImageObjP NC.CopyStructure NC.CloseStructure 
			NC.DeleteStructure NC.AddFileBoxCard NC.MakeFileBox NC.FileBoxCollectChildren 
			NC.AddBrowserCard NC.MakeBrowserCard NC.BringUpBrowserCard 
			NC.UpdateBrowserCard NC.RelayoutBrowserCard NC.ConnectNodesInBrowser 
			NC.UnconnectNodesInBrowser NC.ExpandBrowserNode NC.AskBrowserSpecs 
			NC.ChangeBrowserSpecs NC.BrowserCreateCard NC.BrowserAddNode 
			NC.DelBrowserContentsLink NC.MakeBrowserOverviewWin 
			NC.AskBrowserOverviewSpecs NC.BrowserCardQuitFn NC.GetBrowserNodeID 
			NC.GetBrowserHashArray NC.RemoveBrowserNodeHashArrayEntry NC.SetBrowserRoots 
			NC.AddLinkIndexCard NC.MakeLinkIndex NC.ComputeLinkIndex 
			NC.RecomputeLinkIndex NC.AskLinkIndexSpecs NC.ChangeLinkIndexSpecs 
			NC.MakeCardTypesList NC.AddCardType NC.IsSubTypeOfP NC.ModifyCardType 
			NC.RecomputeCardType NC.SubTypesOfCardType NC.InheritFieldsFromSuperType 
			NC.AutoLoadCardType NC.UIDSetPropList NC.UIDPutProp NC.UIDGetProp 
			NC.UIDGetPropList NC.ReadLink NC.OpenNoteFile NC.StoreNoteFileInHashArray 
			NC.FindNextCardPart NC.ForceDatabaseClose NC.RemoveNoteFileFromHashArray 
			NC.CreateNoteFile NC.PutNoteFileHeader NC.CopyCardPartInPlaceToEOF 
			NC.GetLinks NC.ReadCardPartHeader NC.PutFromLinks NC.WriteCardPartHeader 
			NC.WriteLink NC.PutPropList NC.GetPropList NC.GetType NC.PutLinks NC.GetTitle 
			NC.PutMainCardData NC.GetNoteCard NC.GetMainCardData NC.SetStatus 
			NC.InstallCardInNoteFile NC.LockListOfCards NC.CardCheckOpInProgress 
			NC.PutRegion NC.PutTitle NC.CloseNoteFile NC.CleanupCardObjects 
			NC.CloseListOfActiveCards NC.PutNoteCard NC.SetMainLoc NC.SetLinksLoc 
			NC.SetTitleLoc NC.SetPropListLoc NC.CopyCards NC.PutNoteCardToStream 
			NC.GetNoteCardFromStream NC.MakeHashKeyFromCard NC.UpdateIndexLocIfNeeded 
			NC.FixUpLinksInCardCopy NC.OperationInProgress NC.GetNewCard 
			NC.InstallCriticalUIDsInNoteFile NCLocalDevice.GetNoteFileHeader 
			NCLocalDevice.OpenNoteFile NCLocalDevice.PutNoteFileHeader 
			NCLocalDevice.NewCardUID NCLocalDevice.GetCardInfo NCLocalDevice.PutCardPart 
			NCLocalDevice.GetCardPart NCLocalDevice.GetHashArray 
			NCLocalDevice.PutHashArray NCLocalDevice.PutIndexEntry 
			NCLocalDevice.PutFromLinks NCLocalDevice.ReadIndexEntry 
			NC.ConvertNoteFileVersion2To3 NC.ConvertVersion2LinkIcon NC.ConvertLinkFormat 
			NC.ReadVersion2MainCardData NC.CompactNoteFileToTarget NC.GetCardPartLength 
			NC.SortIndexEntries NC.UpdateCardLoc NC.CopySortedCardPart 
			NC.CopySortedCardPartInPlace NC.CoerceToNoteFileStream 
			NC.CoerceToInterestedWindow NC.RobustGetSubstance NC.WorthlessCardP 
			NC.CheckIndexLocs NC.BuildTitlesInspectorMenu NC.BuildSubstancesInspectorMenu 
			NC.BuildLinksInspectorMenu NC.BuildPropListsInspectorMenu 
			NC.CardSubstanceVersionInspector NC.CardLinksVersionInspector 
			NC.CardPropListVersionInspector NC.CheckForBadLinksAndTitlesAndPropLists 
			NC.UndeletableCardP NC.RegistryCardMakeFn NC.RegisterCardByName 
			NC.LookupCardByName NC.MakeSearchCard NC.MakeDocument 
			NC.MakeDocInspectorSelectionFn NCHACKS.MakeLinkIconsInvisibleInTextCard 
			NCHACKS.MakeLinkIconForLinkInvisible NC.PostGreet)
		   (RECORDS Card)

      previous date: " 4-Nov-87 18:03:07" {QV}<NOTECARDS>1.3KNEXT>RGPATCH063.;1)


(* Copyright (c) 1987 by Xerox Corporation. All rights reserved.)

(PRETTYCOMPRINT RGPATCH063COMS)

(RPAQQ RGPATCH063COMS [[DECLARE: COPY FIRST (P (NC.LoadFileFromDirectories (QUOTE NCFILEBOXCARD))
						 (NC.LoadFileFromDirectories (QUOTE NCBROWSERCARD))
						 (NC.LoadFileFromDirectories (QUOTE NCLINKINDEXCARD))
						 (NC.LoadFileFromDirectories (QUOTE 
									     NCCONVERTVERSION2TO3))
						 (NC.LoadFileFromDirectories (QUOTE NCCOMPACT))
						 (NC.LoadFileFromDirectories (QUOTE NCREPAIR))
						 (NC.LoadFileFromDirectories (QUOTE NCHASHCARD))
						 (NC.LoadFileFromDirectories (QUOTE NCSEARCHCARD))
						 (NC.LoadFileFromDirectories (QUOTE NCDOCUMENTCARD))
						 (NC.LoadFileFromDirectories (QUOTE NCHACKS))
						 (NC.LoadFileFromDirectories (QUOTE NCGRAPHCARD))
						 (NC.LoadFileFromDirectories (QUOTE NCTEXTCARD))
						 (NC.LoadFileFromDirectories (QUOTE NCSKETCHCARD))
						 (NC.LoadFileFromDirectories (QUOTE NCIDEASKETCHCARD]
	(* * changes to NCCARDS)
	(RECORDS Card)
	(FNS NC.EditNoteCard NC.InstallTitleBarMiddleMenu NC.ShowLinks NC.CardP NC.FetchStatus 
	     NC.FetchNewCardFlg NC.FetchTitle NC.FetchType NC.LinksCachedP NC.ActiveCardP 
	     NC.SetFromLinks NC.SetLinksDirtyFlg NC.FetchFromLinks NC.SetLinksDate NC.SetToLinks 
	     NC.SetGlobalLinks NC.CardNeedsFilingP NC.TopLevelCardP NC.SetPropList 
	     NC.SetPropListDirtyFlg NC.FetchPropListDate NC.SetPropListDate NC.FetchPropList 
	     NC.SetRegion NC.FetchSavedRegion NC.FetchRegion NC.FetchDefaultWidth 
	     NC.FetchDefaultHeight NC.FetchItemDate NC.SetItemDate NC.SetType NC.FetchLinksDate 
	     NC.FetchToLinks NC.FetchGlobalLinks NC.SetTitleDate NC.SetTitle NC.ReadOnlyCardP 
	     NC.SetUserDataProp NC.SetSubstance NC.MarkCardDirty NC.SetSubstanceDirtyFlg 
	     NC.ActivateCard NC.FetchSubstance NC.MakeNoteCard NC.SetNewCardFlg NC.DeactivateCard 
	     NC.SetTitleDirtyFlg NC.QuitCard NC.CardDirtyP NC.FetchSubstanceDirtyFlg 
	     NC.FetchTitleDirtyFlg NC.FetchPropListDirtyFlg NC.FetchLinksDirtyFlg NC.SetSavedRegion 
	     NC.FetchUserDataProp NC.CardSaveFn NC.FetchBeingDeletedFlg NC.FetchTitleDate 
	     NC.AssignTitle NC.CheckFiling NC.ObtainEditPermission NC.RetrieveTypeAndTitle 
	     NC.FetchLinkDisplayMode NC.DeleteNoteCardInternal NC.SetBeingDeletedFlg 
	     NC.ClosePropListEditor NC.FetchLinkIconAttachedBitMap NC.FetchLinkAnchorModesSupported 
	     NC.DeleteNoteCard NC.FetchRegionViewed NC.FetchSlotNum NC.SetUserDataPropList 
	     NC.AddParents NC.SeverExternalLinks NC.DeleteNoteCards NC.QuitWithoutSaving 
	     NC.UnfileNoteCard NC.CollectReferences NC.EditProperties NC.OpenPropListEditor 
	     NC.CardOrCardHolderFromUID)
	(* * changes to NCLINKS)
	(FNS NC.TraverseLink NC.DeleteBadLink NC.SameLinkP NC.ValidLinkP NC.DeleteLink 
	     NC.DeleteFromLink NC.DelFromLink NC.FileInOrphanBox NC.HookToOrphanCard 
	     NC.MakeFilingLink NC.MakeLink NC.UpdateLinkImages NC.UncacheLinks NC.MakeFilingLinks 
	     NC.AddToLink NC.AddFromLink NC.DelToLink NC.DelReferencesToCard 
	     NC.DelReferencesToCardFromGlobalList NC.DeleteToLink NC.ChangeLinkDisplayMode 
	     NC.FetchLinkIconForLink NC.RelabelLink NC.ChangeCardTitleFromLinkIcon 
	     NC.LinkIconWhenDeletedFn NC.CheckForOrphanDelete NC.InsertLinkBeforeMarker 
	     NC.AddGlobalLinksToCard NC.AddLinkToCard NC.AddLinksToCard)
	(* * changes to NCPROGINT)
	(FNS NCP.OpenCard NCP.DisplayCard NCP.CardTypeLinkDisplayMode NCP.CardTypeSuper 
	     NCP.RemoveSpecialCard NCP.NoteFileFromCard NCP.CardNoteFile NCP.LocalGlobalLink 
	     NCP.GlobalGlobalLink NCP.LinkType)
	(* * changes to NCCROSSFILELINKS)
	(FNS NC.CrossFileLinkEditFn NC.GetCrossFileLinkDestCard NC.CreateCrossFileLinkCard 
	     NC.AskCrossFileLinkMode NC.CheckCrossFileLinkType NC.ComputeCrossFileLinkMode)
	(* * changes to NCGRAPHCARD)
	(FNS NC.GraphCardLeftButtonFn NC.RelayoutGraphCard)
	(* * changes to NCTEXTCARD)
	(FNS NC.InstallTextTitleBarMiddleMenu NC.MakeTEditCard NC.BringUpTEditCard NC.TEditMenuFn 
	     NC.GetTextSubstance)
	(* * changes to NCSKETCHCARD)
	(FNS NC.MakeSketchCard NC.BringUpSketchCard)
	(* * changes to NCIDEASKETCHCARD)
	(FNS NCIDEASKETCH.MakeIdeaSketchCard NCIDEASKETCH.BringUpIdeaSketchCard)
	(* * changes to NCINTERFACE)
	(FNS NC.InstallTitleBarLeftMenu NC.AskLinkLabel NC.SelectNoteCards NC.AttachNoteFileName 
	     NC.CardImageObjP NC.CopyStructure NC.CloseStructure NC.DeleteStructure)
	(* * changes to NCFILEBOXCARD)
	(FNS NC.AddFileBoxCard NC.MakeFileBox NC.FileBoxCollectChildren)
	(* * changes to NCBROWSERCARD)
	(FNS NC.AddBrowserCard NC.MakeBrowserCard NC.BringUpBrowserCard NC.UpdateBrowserCard 
	     NC.RelayoutBrowserCard NC.ConnectNodesInBrowser NC.UnconnectNodesInBrowser 
	     NC.ExpandBrowserNode NC.AskBrowserSpecs NC.ChangeBrowserSpecs NC.BrowserCreateCard 
	     NC.BrowserAddNode NC.DelBrowserContentsLink NC.MakeBrowserOverviewWin 
	     NC.AskBrowserOverviewSpecs NC.BrowserCardQuitFn NC.GetBrowserNodeID 
	     NC.GetBrowserHashArray NC.RemoveBrowserNodeHashArrayEntry NC.SetBrowserRoots)
	(* * changes to NCLINKINDEXCARD)
	(FNS NC.AddLinkIndexCard NC.MakeLinkIndex NC.ComputeLinkIndex NC.RecomputeLinkIndex 
	     NC.AskLinkIndexSpecs NC.ChangeLinkIndexSpecs)
	(* * changes to NCTYPESMECH)
	(FNS NC.MakeCardTypesList NC.AddCardType NC.IsSubTypeOfP NC.ModifyCardType 
	     NC.RecomputeCardType NC.SubTypesOfCardType NC.InheritFieldsFromSuperType 
	     NC.AutoLoadCardType)
	(* * changes to NCDATABASE)
	(FNS NC.UIDSetPropList NC.UIDPutProp NC.UIDGetProp NC.UIDGetPropList NC.ReadLink 
	     NC.OpenNoteFile NC.StoreNoteFileInHashArray NC.FindNextCardPart NC.ForceDatabaseClose 
	     NC.RemoveNoteFileFromHashArray NC.CreateNoteFile NC.PutNoteFileHeader 
	     NC.CopyCardPartInPlaceToEOF NC.GetLinks NC.ReadCardPartHeader NC.PutFromLinks 
	     NC.WriteCardPartHeader NC.WriteLink NC.PutPropList NC.GetPropList NC.GetType NC.PutLinks 
	     NC.GetTitle NC.PutMainCardData NC.GetNoteCard NC.GetMainCardData NC.SetStatus 
	     NC.InstallCardInNoteFile NC.LockListOfCards NC.CardCheckOpInProgress NC.PutRegion 
	     NC.PutTitle NC.CloseNoteFile NC.CleanupCardObjects NC.CloseListOfActiveCards 
	     NC.PutNoteCard NC.SetMainLoc NC.SetLinksLoc NC.SetTitleLoc NC.SetPropListLoc 
	     NC.CopyCards NC.PutNoteCardToStream NC.GetNoteCardFromStream NC.MakeHashKeyFromCard 
	     NC.UpdateIndexLocIfNeeded NC.FixUpLinksInCardCopy NC.OperationInProgress NC.GetNewCard 
	     NC.InstallCriticalUIDsInNoteFile)
	(* * changes to NCLOCALDEVICE)
	(FNS NCLocalDevice.GetNoteFileHeader NCLocalDevice.OpenNoteFile 
	     NCLocalDevice.PutNoteFileHeader NCLocalDevice.NewCardUID NCLocalDevice.GetCardInfo 
	     NCLocalDevice.PutCardPart NCLocalDevice.GetCardPart NCLocalDevice.GetHashArray 
	     NCLocalDevice.PutHashArray NCLocalDevice.PutIndexEntry NCLocalDevice.PutFromLinks 
	     NCLocalDevice.ReadIndexEntry)
	(* * changes to NCCONVERTVERSION2TO3)
	(FNS NC.ConvertNoteFileVersion2To3 NC.ConvertVersion2LinkIcon NC.ConvertLinkFormat 
	     NC.ReadVersion2MainCardData)
	(* * changes to NCCOMPACT)
	(FNS NC.CompactNoteFileToTarget NC.GetCardPartLength NC.SortIndexEntries NC.UpdateCardLoc 
	     NC.CopySortedCardPart NC.CopySortedCardPartInPlace)
	(* * changes to NCUTILITIES)
	(FNS NC.CoerceToNoteFileStream NC.CoerceToInterestedWindow)
	(* * changes to NCINTERFACE)
	(FNS NC.AskLinkLabel NC.SelectNoteCards NC.AttachNoteFileName NC.CardImageObjP 
	     NC.CopyStructure NC.CloseStructure NC.DeleteStructure)
	(* * changes to NCREPAIR)
	(FNS NC.RobustGetSubstance NC.WorthlessCardP NC.CheckIndexLocs NC.BuildTitlesInspectorMenu 
	     NC.BuildSubstancesInspectorMenu NC.BuildLinksInspectorMenu 
	     NC.BuildPropListsInspectorMenu NC.CardSubstanceVersionInspector 
	     NC.CardLinksVersionInspector NC.CardPropListVersionInspector 
	     NC.CheckForBadLinksAndTitlesAndPropLists NC.UndeletableCardP)
	(* * changes to NCHASHCARD)
	(FNS NC.RegistryCardMakeFn NC.RegisterCardByName NC.LookupCardByName)
	(* * changes to NCSEARCHCARD)
	(FNS NC.MakeSearchCard)
	(* * changes to NCDOCUMENTCARD)
	(FNS NC.MakeDocument NC.MakeDocInspectorSelectionFn)
	(* * changes to NCHACKS)
	(FNS NCHACKS.MakeLinkIconsInvisibleInTextCard NCHACKS.MakeLinkIconForLinkInvisible)
	(* * changes to NOTECARDS)
	(FNS NC.PostGreet)
	(DECLARE: DONTEVAL@LOAD DOEVAL@COMPILE DONTCOPY COMPILERVARS (ADDVARS (NLAMA)
									      (NLAML)
									      (LAMA NCP.LinkType])
(DECLARE: COPY FIRST 
(NC.LoadFileFromDirectories (QUOTE NCFILEBOXCARD))
(NC.LoadFileFromDirectories (QUOTE NCBROWSERCARD))
(NC.LoadFileFromDirectories (QUOTE NCLINKINDEXCARD))
(NC.LoadFileFromDirectories (QUOTE NCCONVERTVERSION2TO3))
(NC.LoadFileFromDirectories (QUOTE NCCOMPACT))
(NC.LoadFileFromDirectories (QUOTE NCREPAIR))
(NC.LoadFileFromDirectories (QUOTE NCHASHCARD))
(NC.LoadFileFromDirectories (QUOTE NCSEARCHCARD))
(NC.LoadFileFromDirectories (QUOTE NCDOCUMENTCARD))
(NC.LoadFileFromDirectories (QUOTE NCHACKS))
(NC.LoadFileFromDirectories (QUOTE NCGRAPHCARD))
(NC.LoadFileFromDirectories (QUOTE NCTEXTCARD))
(NC.LoadFileFromDirectories (QUOTE NCSKETCHCARD))
(NC.LoadFileFromDirectories (QUOTE NCIDEASKETCHCARD))
)
(* * changes to NCCARDS)

[DECLARE: EVAL@COMPILE 

(ACCESSFNS Card [

          (* * Instance variables of the card object)


		   (UID (fetch (CardObject UID) of DATUM)
			  (replace (CardObject UID) of DATUM with NEWVALUE))
		   (NoteFile [LET ((\NF (fetch (CardObject NoteFile) of DATUM)))
			          (COND
				    ((type? NoteFile \NF)
				      \NF)
				    (\NF (replace (CardObject NoteFile) of DATUM
					    with (NC.NoteFileFromNoteFileUID \NF]
			     (replace (CardObject NoteFile) of DATUM with NEWVALUE))
		   (Monitor (fetch (CardObject Monitor) of DATUM)
			    (replace (CardObject Monitor) of DATUM with NEWVALUE))
		   (Status (fetch (CardObject Status) of DATUM)
			   (replace (CardObject Status) of DATUM with NEWVALUE))
		   (IndexDirtyFlg (fetch (CardObject IndexDirtyFlg) of DATUM)
				  (replace (CardObject IndexDirtyFlg) of DATUM with NEWVALUE))
		   (IndexLoc (fetch (CardObject IndexLoc) of DATUM)
			     (replace (CardObject IndexLoc) of DATUM with NEWVALUE))
		   (MainLoc (fetch (CardObject MainLoc) of DATUM)
			    (replace (CardObject MainLoc) of DATUM with NEWVALUE))
		   (LinksLoc (fetch (CardObject LinksLoc) of DATUM)
			     (replace (CardObject LinksLoc) of DATUM with NEWVALUE))
		   (PropListLoc (fetch (CardObject PropListLoc) of DATUM)
				(replace (CardObject PropListLoc) of DATUM with NEWVALUE))
		   (TitleLoc (fetch (CardObject TitleLoc) of DATUM)
			     (replace (CardObject TitleLoc) of DATUM with NEWVALUE))
		   (Title (fetch (CardObject Title) of DATUM)
			  (replace (CardObject Title) of DATUM with NEWVALUE))
		   (TitleDirtyFlg (fetch (CardObject TitleDirtyFlg) of DATUM)
				  (replace (CardObject TitleDirtyFlg) of DATUM with NEWVALUE))

          (* Note the use of NC.GetType if CardType is NIL. This is required to force the access to go to the disk for the 
	  card type if the card type caching process is not finished before this fetch is being made.
	  Sort of a kludge.)


		   (Type (OR (fetch (CardObject Type) of DATUM)
			       (NC.GetType DATUM))
			 (replace (CardObject Type) of DATUM with NEWVALUE))
		   (ActiveFlg (fetch (CardObject ActiveFlg) of DATUM)
			      (replace (CardObject ActiveFlg) of DATUM with NEWVALUE))
		   (ActiveCardFlg (fetch (CardObject ActiveFlg) of DATUM)
				  (replace (CardObject ActiveFlg) of DATUM with NEWVALUE))
		   (CardCache (fetch (CardObject CardCache) of DATUM)
			      (replace (CardObject CardCache) of DATUM with NEWVALUE))
		   (UserData (fetch (CardObject UserData) of DATUM)
			     (replace (CardObject UserData) of DATUM with NEWVALUE))
		   [Substance (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			           (AND \Cache (fetch (CardCache Substance) of \Cache)))
			      (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			           (COND
				     (\Cache (replace (CardCache Substance) of \Cache
						with NEWVALUE))
				     (T (replace (CardObject CardCache) of DATUM
					   with (create CardCache
							    Substance ← NEWVALUE))
					NEWVALUE]
		   [Links (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			       (AND \Cache (fetch (CardCache Links) of \Cache)))
			  (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			       (COND
				 (\Cache (replace (CardCache Links) of \Cache with NEWVALUE))
				 (T (replace (CardObject CardCache) of DATUM
				       with (create CardCache
							Links ← NEWVALUE))
				    NEWVALUE]
		   [FromLinks (LET ((\Cache (fetch (CardObject CardCache) of DATUM))
				    \Links)
			           (AND \Cache (SETQ \Links (fetch (CardCache Links)
								   of \Cache))
					  (fetch (LinksCache FromLinks) of \Links)))
			      (LET ([\Cache (OR (fetch (CardObject CardCache) of DATUM)
						  (replace (CardObject CardCache) of DATUM
						     with (create CardCache]
				    \Links)
			           (SETQ \Links (fetch (CardCache Links) of \Cache))
			           (COND
				     (\Links (replace (LinksCache FromLinks) of \Links
						with NEWVALUE))
				     (T (replace (CardCache Links) of \Cache
					   with (create LinksCache
							    FromLinks ← NEWVALUE))
					NEWVALUE]
		   [ToLinks (LET ((\Cache (fetch (CardObject CardCache) of DATUM))
				  \Links)
			         (AND \Cache (SETQ \Links (fetch (CardCache Links)
								 of \Cache))
					(fetch (LinksCache ToLinks) of \Links)))
			    (LET ([\Cache (OR (fetch (CardObject CardCache) of DATUM)
						(replace (CardObject CardCache) of DATUM
						   with (create CardCache]
				  \Links)
			         (SETQ \Links (fetch (CardCache Links) of \Cache))
			         (COND
				   (\Links (replace (LinksCache ToLinks) of \Links with 
											 NEWVALUE))
				   (T (replace (CardCache Links) of \Cache
					 with (create LinksCache
							  ToLinks ← NEWVALUE))
				      NEWVALUE]
		   [GlobalLinks (LET ((\Cache (fetch (CardObject CardCache) of DATUM))
				      \Links)
				     (AND \Cache (SETQ \Links (fetch (CardCache Links)
								     of \Cache))
					    (fetch (LinksCache GlobalLinks) of \Links)))
				(LET ([\Cache (OR (fetch (CardObject CardCache) of DATUM)
						    (replace (CardObject CardCache) of DATUM
						       with (create CardCache]
				      \Links)
				     (SETQ \Links (fetch (CardCache Links) of \Cache))
				     (COND
				       (\Links (replace (LinksCache GlobalLinks) of \Links
						  with NEWVALUE))
				       (T (replace (CardCache Links) of \Cache
					     with (create LinksCache
							      GlobalLinks ← NEWVALUE))
					  NEWVALUE]
		   [PropList (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			          (AND \Cache (fetch (CardCache PropList) of \Cache)))
			     (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			          (COND
				    (\Cache (replace (CardCache PropList) of \Cache with 
											 NEWVALUE))
				    (T (replace (CardObject CardCache) of DATUM
					  with (create CardCache
							   PropList ← NEWVALUE))
				       NEWVALUE]
		   [Region (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			        (AND \Cache (fetch (CardCache Region) of \Cache)))
			   (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			        (COND
				  (\Cache (replace (CardCache Region) of \Cache with NEWVALUE))
				  (T (replace (CardObject CardCache) of DATUM
					with (create CardCache
							 Region ← NEWVALUE))
				     NEWVALUE]
		   [SavedRegion (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				     (AND \Cache (fetch (CardCache SavedRegion) of \Cache)))
				(LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				     (COND
				       (\Cache (replace (CardCache SavedRegion) of \Cache
						  with NEWVALUE))
				       (T (replace (CardObject CardCache) of DATUM
					     with (create CardCache
							      SavedRegion ← NEWVALUE))
					  NEWVALUE]
		   [ItemDate (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			          (AND \Cache (fetch (CardCache ItemDate) of \Cache)))
			     (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			          (COND
				    (\Cache (replace (CardCache ItemDate) of \Cache with 
											 NEWVALUE))
				    (T (replace (CardObject CardCache) of DATUM
					  with (create CardCache
							   ItemDate ← NEWVALUE))
				       NEWVALUE]
		   [LinksDate (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			           (AND \Cache (fetch (CardCache LinksDate) of \Cache)))
			      (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			           (COND
				     (\Cache (replace (CardCache LinksDate) of \Cache
						with NEWVALUE))
				     (T (replace (CardObject CardCache) of DATUM
					   with (create CardCache
							    LinksDate ← NEWVALUE))
					NEWVALUE]
		   [TitleDate (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			           (AND \Cache (fetch (CardCache TitleDate) of \Cache)))
			      (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
			           (COND
				     (\Cache (replace (CardCache TitleDate) of \Cache
						with NEWVALUE))
				     (T (replace (CardObject CardCache) of DATUM
					   with (create CardCache
							    TitleDate ← NEWVALUE))
					NEWVALUE]
		   [PropListDate (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				      (AND \Cache (fetch (CardCache PropListDate) of \Cache)))
				 (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				      (COND
					(\Cache (replace (CardCache PropListDate) of \Cache
						   with NEWVALUE))
					(T (replace (CardObject CardCache) of DATUM
					      with (create CardCache
							       PropListDate ← NEWVALUE))
					   NEWVALUE]
		   [LinksDirtyFlg (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				       (AND \Cache (fetch (CardCache LinksDirtyFlg) of \Cache)))
				  (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				       (COND
					 (\Cache (replace (CardCache LinksDirtyFlg) of \Cache
						    with NEWVALUE))
					 (T (replace (CardObject CardCache) of DATUM
					       with (create CardCache
								LinksDirtyFlg ← NEWVALUE))
					    NEWVALUE]
		   [PropListDirtyFlg (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				          (AND \Cache (fetch (CardCache PropListDirtyFlg)
							   of \Cache)))
				     (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				          (COND
					    (\Cache (replace (CardCache PropListDirtyFlg)
						       of \Cache with NEWVALUE))
					    (T (replace (CardObject CardCache) of DATUM
						  with (create CardCache
								   PropListDirtyFlg ← NEWVALUE))
					       NEWVALUE]
		   [SubstanceDirtyFlg (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				           (AND \Cache (fetch (CardCache SubstanceDirtyFlg)
							    of \Cache)))
				      (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				           (COND
					     (\Cache (replace (CardCache SubstanceDirtyFlg)
							of \Cache with NEWVALUE))
					     (T (replace (CardObject CardCache) of DATUM
						   with (create CardCache
								    SubstanceDirtyFlg ← NEWVALUE))
						NEWVALUE]
		   [NewCardFlg (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				    (AND \Cache (fetch (CardCache NewCardFlg) of \Cache)))
			       (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				    (COND
				      (\Cache (replace (CardCache NewCardFlg) of \Cache
						 with NEWVALUE))
				      (T (replace (CardObject CardCache) of DATUM
					    with (create CardCache
							     NewCardFlg ← NEWVALUE))
					 NEWVALUE]
		   [BeingDeletedFlg (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				         (AND \Cache (fetch (CardCache BeingDeletedFlg)
							  of \Cache)))
				    (LET ((\Cache (fetch (CardObject CardCache) of DATUM)))
				         (COND
					   (\Cache (replace (CardCache BeingDeletedFlg)
						      of \Cache with NEWVALUE))
					   (T (replace (CardObject CardCache) of DATUM
						 with (create CardCache
								  BeingDeletedFlg ← NEWVALUE))
					      NEWVALUE]

          (* * Class variables of the card object {class == card type})


		   (SuperType (LET ((NoteCardType (fetch (Card Type) of DATUM)))
			           (NC.GetCardTypeField SuperType NoteCardType)))
		   (LinkDisplayMode (LET ((NoteCardType (fetch (Card Type) of DATUM)))
				         (NC.GetCardTypeField LinkDisplayMode NoteCardType)))
		   (DefaultWidth (LET ((NoteCardType (fetch (Card Type) of DATUM)))
				      (NC.GetCardTypeField DefaultWidth NoteCardType)))
		   (DefaultHeight (LET ((NoteCardType (fetch (Card Type) of DATUM)))
				       (NC.GetCardTypeField DefaultHeight NoteCardType)))
		   (LinkAnchorModesSupported (LET ((NoteCardType (fetch (Card Type) of DATUM)))
					          (NC.GetCardTypeField LinkAnchorModesSupported 
								       NoteCardType)))
		   (LinkIconAttachedBitMap (LET ((NoteCardType (fetch (Card Type) of DATUM)))
					        (NC.GetCardTypeField LinkIconAttachedBitMap 
								     NoteCardType)))
		   (LeftButtonMenuItems (LET ((NoteCardType (fetch (Card Type) of DATUM)))
					     (NC.GetCardTypeField LeftButtonMenuItems NoteCardType)))
		   (MiddleButtonMenuItems (LET ((NoteCardType (fetch (Card Type) of DATUM)))
					       (NC.GetCardTypeField MiddleButtonMenuItems 
								    NoteCardType)))

          (* * Methods of the card object {class == card type})


		   (MakeFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
			        (NC.GetCardTypeField MakeFn NoteCardType)))
		   (EditFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
			        (NC.GetCardTypeField EditFn NoteCardType)))
		   (QuitFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
			        (NC.GetCardTypeField QuitFn NoteCardType)))
		   (MakeReadOnlyFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
				        (NC.GetCardTypeField MakeReadOnlyFn NoteCardType)))
		   (MakeReadWriteFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
				         (NC.GetCardTypeField MakeReadWriteFn NoteCardType)))
		   (GetFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
			       (NC.GetCardTypeField GetFn NoteCardType)))
		   (PutFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
			       (NC.GetCardTypeField PutFn NoteCardType)))
		   (CopyFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
			        (NC.GetCardTypeField CopyFn NoteCardType)))
		   (MarkDirtyFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
				     (NC.GetCardTypeField MarkDirtyFn NoteCardType)))
		   (DirtyPFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
			          (NC.GetCardTypeField DirtyPFn NoteCardType)))
		   (CollectLinksFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
				        (NC.GetCardTypeField CollectLinksFn NoteCardType)))
		   (DeleteLinksFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
				       (NC.GetCardTypeField DeleteLinksFn NoteCardType)))
		   (UpdateLinkIconsFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
				           (NC.GetCardTypeField UpdateLinkIconsFn NoteCardType)))
		   (InsertLinkFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
				      (NC.GetCardTypeField InsertLinkFn NoteCardType)))
		   (TranslateWindowPositionFn (LET ((NoteCardType (fetch (Card Type) of DATUM)))
					           (NC.GetCardTypeField TranslateWindowPositionFn 
									NoteCardType)))

          (* * Methods inherited from the cards current NoteFile device)


		   (MarkCardDeletedFn (fetch (NoteFile MarkCardDeletedFn)
					 of (fetch (Card NoteFile) of DATUM)))
		   (GetCardInfoFn (fetch (NoteFile GetCardInfoFn) of (fetch (Card NoteFile)
									    of DATUM)))
		   (PutCardPartFn (fetch (NoteFile PutCardPartFn) of (fetch (Card NoteFile)
									    of DATUM)))
		   (GetCardPartFn (fetch (NoteFile GetCardPartFn) of (fetch (Card NoteFile)
									    of DATUM)))
		   (ObtainWritePermissionFn (fetch (NoteFile ObtainWritePermissionFn)
					       of (fetch (Card NoteFile) of DATUM)))
		   (ReleaseWritePermissionFn (fetch (NoteFile ReleaseWritePermissionFn)
						of (fetch (Card NoteFile) of DATUM)))
		   (CancelCacheSubscriptionFn (fetch (NoteFile CancelCacheSubscriptionFn)
						 of (fetch (Card NoteFile) of DATUM]
		  (CREATE (create CardObject))
		  (TYPE? (TYPE? CardObject DATUM)))
]
(DEFINEQ

(NC.EditNoteCard
  [LAMBDA (Card ReadOnly RegionOrPosition TypeSpecificArgs)
                                                             (* Randy.Gobbel " 4-Nov-87 13:53")

          (* * Bring the already created NoteCard specified by ID onto the screen at Region or Position specified by 
	  RegionOrPosition)



          (* * fgh 11/11/85: Updated to handle new Card object.)



          (* * fgh 2/5/86 Added call to NC.ApplyFn)



          (* * kirk 15May86 Added call to NC.AttachNoteFileName)



          (* * rht 7/13/86: Added TypeSpecificArgs arg.)



          (* * kef 7/16/86: Added NC.ObtainCardEditPermission.)



          (* * kef 8/7/86: Added check to make sure that applying the EditFn worked. If not, then release those write locks, 
	  thus keeping the writelock count consistent.)



          (* * fgh 8/30/86 Converted APPLY* to NC.ApplyFn.)



          (* * rht 10/6/86: Added checks before doing WINDOWPROP calls in case there was a recursive call to 
	  NC.EditNoteCard.)



          (* * rg 3/30/87 added NC.ProtectedCardOperation wrapper)



          (* * rht 5/13/87: Added call to new NC.InstallCopyButtonEventFn.)



          (* * rg 11/4/87 added ReadOnly arg)


    (DECLARE (GLOBALVARS NC.ShowNoteFileOnCards))
    (NC.ProtectedCardOperation Card "Edit NoteCard" NIL (RESETSAVE (CURSOR WAITINGCURSOR))
			       (PROG (NoteCardType Window Substance EditResult)
				       [COND
					 ((AND (NC.ActiveCardP Card)
						 (NC.ObtainEditPermission Card))
					   (SETQ Substance (NC.FetchSubstance Card)))
					 ((NC.ObtainEditPermission Card)
					   (NC.GetNoteCard Card)
					   (SETQ Substance (NC.FetchSubstance Card)))
					 (T (RETURN (NC.CardPartBusy Card
									 (QUOTE (SUBSTANCE TOLINKS 
										    GLOBALTOLINKS 
											 PROPLIST]
				       (SETQ NoteCardType (NC.RetrieveType Card))
				       (COND
					 ([AND (SETQ EditResult
						   (ERSETQ (NC.ApplyFn EditFn Card Substance 
									 RegionOrPosition 
									 TypeSpecificArgs)))
						 (WINDOWP (SETQ Window (CAR EditResult]
					   (WINDOWADDPROP Window (QUOTE CLOSEFN)
							    (FUNCTION NC.QuitCard)
							    (QUOTE FIRST))
					   (OR (NC.CardP (WINDOWPROP Window (QUOTE 
										   NoteCardObject)))
						 (WINDOWPROP Window (QUOTE NoteCardObject)
							       Card))
					   (NC.InstallCopyButtonEventFn Window)
					   (if NC.ShowNoteFileOnCards
					       then (NC.AttachNoteFileName Window)))
					 (T                  (* At this point, we've obtain the write locks but the
							     edit failed, so we'd better release them)
					    (for CardPart in (QUOTE (SUBSTANCE TOLINKS 
										    GLOBALTOLINKS 
										     PROPLIST))
					       do (NC.ApplyFn ReleaseWritePermissionFn Card 
								CardPart))
					    (RETURN)))
				       (if ReadOnly
					   then (NC.ApplyFn MakeReadOnlyFn Card))
				       (RETURN Window])

(NC.InstallTitleBarMiddleMenu
  [LAMBDA (Window CardType)                                  (* pmi: " 1-Apr-87 16:47")

          (* * Make a middle button title bar menu and install.)



          (* * pmi 4/1/87: Added NC.MenuFont to all menus)


    (DECLARE (GLOBALVARS NC.MenuFont))
    (WINDOWPROP Window (QUOTE TitleBarMiddleButtonMenu)
		  (create MENU
			    ITEMS ← (NC.GetCardTypeField MiddleButtonMenuItems CardType)
			    CENTERFLG ← T
			    MENUFONT ← NC.MenuFont
			    ITEMHEIGHT ← (IPLUS (FONTPROP NC.MenuFont (QUOTE HEIGHT))
						  1])

(NC.ShowLinks
  [LAMBDA (TextStream)                                       (* pmi: "19-Jun-87 17:02")
                                                             (* Open an inspector for the links for note card 
							     specified by TextStream above the window for the note 
							     card.)

          (* * fgh 11/13/85 Updated to handle Card object.)



          (* * fgh 5/2/86 Included calls to NC.InsureLinkDisplayMode to handle litatom link display modes.
	  Added InsdiePropListEditor and Reverse indicators to UserData field of Links in show links editor.
	  Also added ShowLinks property onto the editor window so other functions can detect that a window is a show links 
	  window.)



          (* * rht 8/11/86: Now passes non-nil ShowLinksFlg to NC.OpenPropListEditor.)



          (* * rg 4/6/87 removed NC.ProtectedCardOperation wrapper.)



          (* * pmi 6/19/87: Now places each link's UID on the corresponding link created for the inspector.
	  Checks for the validity of each link's source and destination cards and deletes links that are bad 
	  (half-links.))


    (LET [Links EditWindow (Card (NC.CoerceToCard (WINDOW.FROM.TEDIT.THING TextStream]
         [SETQ Links (NCONC [for Link in (NC.FetchToLinks Card)
				   when (if (NC.ValidCardP (fetch (Link DestinationCard)
								    of Link))
					      then         (* The link is good, include it in the show links 
							     window.)
						     T
					    else           (* The link is bad, delete it and don't include it in 
							     the show links window.)
						   (NC.DeleteLink Link)
						   NIL)
				   join (LIST (COND
						    ((EQ (fetch (Link AnchorMode) of Link)
							   (QUOTE GlobalGlobal))
						      "Global TO")
						    (T "TO"))
						  (LIST (create Link
							     using
							      Link DisplayMode ←
							      (create LINKDISPLAYMODE
								 copying
								  (NC.InsureLinkDisplayMode
								    (fetch (Link DisplayMode)
								       of Link))
								  SHOWTITLEFLG ← T SHOWLINKTYPEFLG ← 
								  T)
							      UserData ← (QUOTE (
InsidePropListEditor T))
							      UID ← (fetch (Link UID) of Link]
				(for Link in (NC.FetchFromLinks Card)
				   when (if (NC.ValidCardP (fetch (Link SourceCard)
								    of Link))
					      then         (* The link is good, include it in the show links 
							     window.)
						     T
					    else           (* The link is bad, delete it and don't include it in 
							     the show links window.)
						   (NC.DeleteLink Link)
						   NIL)
				   join (LIST "FROM"
						  (LIST (create Link
							     using
							      Link DisplayMode ←
							      (create LINKDISPLAYMODE
								 copying
								  (NC.InsureLinkDisplayMode
								    (fetch (Link DisplayMode)
								       of Link))
								  SHOWTITLEFLG ← T SHOWLINKTYPEFLG ← 
								  T)
							      SourceCard ← (fetch (Link 
										  DestinationCard)
									      of Link)
							      DestinationCard ← (fetch
								(Link SourceCard) of Link)
							      UserData ←
							      (QUOTE (InsidePropListEditor T 
											 Reversed T))
							      UID ← (fetch (Link UID) of Link]
         (WINDOWPROP (SETQ EditWindow (NC.OpenPropListEditor TextStream Links "List of Links" T 
								   T T))
		       (QUOTE ShowLinks)
		       T)
     EditWindow])

(NC.CardP
  [LAMBDA (Card)                                             (* rht: "15-Nov-85 16:54")

          (* * Return non-NIL if the arg is a Card object.)


    (type? Card Card])

(NC.FetchStatus
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:52")

          (* * Return the status of the card specified by Card)


    (fetch (Card Status) of Card])

(NC.FetchNewCardFlg
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:01")
                                                             (* Return the value of the new card flg of ID)

          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/11/85: Updated to handle Card object)


    (fetch (Card NewCardFlg) of Card])

(NC.FetchTitle
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:23")

          (* * Fetch the title from IDs cache)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (fetch (Card Title) of Card])

(NC.FetchType
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:24")

          (* * Fetch the note card type from IDs cache)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle card object.)


    (fetch (Card Type) of Card])

(NC.LinksCachedP
  [LAMBDA (Card)                                             (* rht: "16-May-87 00:06")

          (* * Does this card have links cahced?)



          (* * rht 5/16/87: Changed to also return non-nil if card is active and new.)


    (OR (fetch (Card Links) of Card)
	  (AND (NC.ActiveCardP Card)
		 (NC.FetchNewCardFlg Card])

(NC.ActiveCardP
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 18:41")

          (* * If the active card flg is set in the cache for ID, the return ID's type. Otherwise return NIL.)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (AND Card (fetch (Card ActiveFlg) of Card)
	   (NC.FetchType Card])

(NC.SetFromLinks
  [LAMBDA (Card Links)                                       (* fgh: "13-Nov-85 19:25")

          (* * Cache the from links for ID)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card FromLinks) of Card with Links])

(NC.SetLinksDirtyFlg
  [LAMBDA (Card Value)                                       (* fgh: "13-Nov-85 19:30")

          (* * Set the flag indicating the links cache is dirty)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card LinksDirtyFlg) of Card with Value])

(NC.FetchFromLinks
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:17")

          (* * Fetch ID's links from the cache)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card objects.)


    (fetch (Card FromLinks) of Card])

(NC.SetLinksDate
  [LAMBDA (Card Date)                                        (* fgh: "13-Nov-85 19:50")

          (* * Set the links date in the cache for card ID)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card LinksDate) of Card with (NC.InsureIntegerDate Date))
    Date])

(NC.SetToLinks
  [LAMBDA (Card Links)                                       (* fgh: "13-Nov-85 19:43")

          (* * Cache the to links for card ID)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card ToLinks) of Card with Links])

(NC.SetGlobalLinks
  [LAMBDA (Card GlobalLinks)                                 (* fgh: "13-Nov-85 19:25")

          (* * Cache the global links of ID)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card GlobalLinks) of Card with GlobalLinks])

(NC.CardNeedsFilingP
  [LAMBDA (Card)                                             (* rht: "26-Mar-87 19:30")

          (* * Returns non-nil if this card is filed in some not currently filed anywhere unless it's a top level card.
	  Assumes card is active.)



          (* * fgh 11/12/85 Updated to handle Card objects.)



          (* * rht 10/6/86: Now checks for card types that don't have to be filed. Also makes sure that there's at least one 
	  filing link that's within this notefile.)



          (* * rht 12/8/86: Now checks for individual cards that don't require filing.)



          (* * rg 12/18/86: Added check of FilingLinkTypeFlg prop.)



          (* * rht 3/26/87: Fixed check for crossfilelink card.)


    (LET ((NoteFile (fetch (Card NoteFile) of Card)))
         (AND (NOT (NC.TopLevelCardP Card))
		(NC.ForceFilingForCardTypeP (NC.FetchType Card))
		(NOT (NCP.CardProp Card (QUOTE Don'tRequireFilingFlg)))
		(for Link in (NC.FetchFromLinks Card)
		   never (AND (OR (FMEMB (fetch (Link Label) of Link)
						 (QUOTE (FiledCard SubBox)))
					(GETPROP (fetch (Link Label) of Link)
						   (QUOTE FilingLinkTypeFlg)))
				  (NOT (NC.CrossFileLinkCardP (fetch (Link SourceCard)
								     of Link])

(NC.TopLevelCardP
  [LAMBDA (Card)                                             (* rht: "13-Jul-86 17:35")

          (* * Is Card a top level card in its NoteFile?)


    (for TopLevelCard in (NC.FetchSpecialCards (fetch (Card NoteFile) of Card))
       thereis (NC.SameCardP Card TopLevelCard])

(NC.SetPropList
  [LAMBDA (Card PropList)                                    (* fgh: "13-Nov-85 19:32")

          (* * Cache the prop list of ID)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card PropList) of Card with PropList])

(NC.SetPropListDirtyFlg
  [LAMBDA (Card Value)                                       (* fgh: "13-Nov-85 19:45")

          (* * Set the prop list cache dirty flg)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card PropListDirtyFlg) of Card with Value])

(NC.FetchPropListDate
  [LAMBDA (Card DontConvertFlg)                              (* fgh: "13-Nov-85 19:48")

          (* * Fetch IDs prop list date from the cache and and convert to string format if necessary)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (LET ((Date (fetch (Card PropListDate) of Card)))
         (COND
	   ((ZEROP Date)
	     NIL)
	   (DontConvertFlg Date)
	   (T (GDATE Date])

(NC.SetPropListDate
  [LAMBDA (Card Date)                                        (* fgh: "13-Nov-85 19:49")

          (* * Set the prop list date in the cache for ID)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card PropListDate) of Card with (NC.InsureIntegerDate Date))
    Date])

(NC.FetchPropList
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:19")

          (* * fetych IDs prop list from the cache)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle card object.)


    (fetch (Card PropList) of Card])

(NC.SetRegion
  [LAMBDA (Card Region)                                      (* fgh: "13-Nov-85 19:32")

          (* * Cache the region of ID)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card Region) of Card with Region])

(NC.FetchSavedRegion
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:20")

          (* * fetch IDs saved region from the cache)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (fetch (Card SavedRegion) of Card])

(NC.FetchRegion
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:19")

          (* * fetch IDs region from the cache)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle card object.)


    (fetch (Card Region) of Card])

(NC.FetchDefaultWidth
  [LAMBDA (Card)                                             (* fgh: " 5-Feb-86 13:42")

          (* * Fetch the default width corresponding to Card)



          (* * fgh 2/5/86 First created.)


    (fetch (Card DefaultWidth) of Card])

(NC.FetchDefaultHeight
  [LAMBDA (Card)                                             (* fgh: " 5-Feb-86 13:43")

          (* * Fetch default height corresponding to Card)



          (* * fgh 2/5/86 First created.)


    (fetch (Card DefaultHeight) of Card])

(NC.FetchItemDate
  [LAMBDA (Card DontConvertFlg)                              (* fgh: "13-Nov-85 19:47")

          (* * Fetch IDs item date from the cache and and convert to string format if necessary)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (LET ((Date (fetch (Card ItemDate) of Card)))
         (COND
	   ((ZEROP Date)
	     NIL)
	   (DontConvertFlg Date)
	   (T (GDATE Date])

(NC.SetItemDate
  [LAMBDA (Card Date)                                        (* fgh: "13-Nov-85 19:49")

          (* * Set the item date in the cache for ID)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card ItemDate) of Card with (NC.InsureIntegerDate Date))
    Date])

(NC.SetType
  [LAMBDA (Card NoteCardType)                                (* fgh: "13-Nov-85 19:43")

          (* * Cache the type of ID)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card Type) of Card with NoteCardType])

(NC.FetchLinksDate
  [LAMBDA (Card DontConvertFlg)                              (* fgh: "13-Nov-85 19:48")

          (* * Fetch IDs links date from the cache and and convert to string format if necessary)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (LET ((Date (fetch (Card LinksDate) of Card)))
         (COND
	   ((ZEROP Date)
	     NIL)
	   (DontConvertFlg Date)
	   (T (GDATE Date])

(NC.FetchToLinks
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:24")

          (* * fetch the to links from IDs cache)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handl;e Card object.)


    (fetch (Card ToLinks) of Card])

(NC.FetchGlobalLinks
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:18")

          (* * Fetch IDs global links from the cache)



          (* * fgh 11/13/85 Updated to handle Card objects.)


    (fetch (Card GlobalLinks) of Card])

(NC.SetTitleDate
  [LAMBDA (Card Date)                                        (* fgh: "13-Nov-85 19:49")

          (* * Set the title date in the cahce for card ID)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card TitleDate) of Card with (NC.InsureIntegerDate Date))
    Date])

(NC.SetTitle
  [LAMBDA (Card Title)                                       (* fgh: "13-Nov-85 19:43")

          (* * Cache the title for card ID)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card Title) of Card with Title])

(NC.ReadOnlyCardP
  [LAMBDA (Card)                                             (* rht: " 4-Jul-86 18:53")

          (* * Return non-nil if card's notefile is open for read only. Someday it will get smarter.)


    (NC.ReadOnlyNoteFileP (fetch (Card NoteFile) of Card])

(NC.SetUserDataProp
  [LAMBDA (Card Prop Value)                                  (* fgh: "17-Nov-85 18:00")

          (* * Set a property on the USerData list)


    (LET ((UserDataPropList (fetch (Card UserData) of Card)))
         (COND
	   ((LISTP UserDataPropList)
	     (LISTPUT UserDataPropList Prop Value))
	   (T (replace (Card UserData) of Card with (LIST Prop Value])

(NC.SetSubstance
  [LAMBDA (Card Substance)                                   (* fgh: "13-Nov-85 19:41")

          (* * Set the cached substance of card ID to be substance)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card Substance) of Card with Substance])

(NC.MarkCardDirty
  [LAMBDA (Card ResetFlg)                                    (* fgh: " 6-Feb-86 22:03")
                                                             (* Mark card specified by ID as being DIRTY and 
							     needing to be writtent to the database)

          (* * rht 2/1/85: Now also sets/resets property on ID indicating substance dirty.)



          (* * fgh 11/13/85 Updated to handle Card object.)



          (* * fgh 2/5/86 Added call to NC.ApplyFn)


    (NC.ApplyFn MarkDirtyFn Card ResetFlg)
    (NC.SetSubstanceDirtyFlg Card (NOT ResetFlg])

(NC.SetSubstanceDirtyFlg
  [LAMBDA (Card Value)                                       (* fgh: "13-Nov-85 19:45")

          (* * Set the substance cahce dirty flg)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card SubstanceDirtyFlg) of Card with Value])

(NC.ActivateCard
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:02")

          (* * Set the active card flg for ID)



          (* * fgh 11/13/85 Updated to handle Card object)


    (replace (Card ActiveFlg) of Card with T])

(NC.FetchSubstance
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:23")

          (* * Return the substance of card ID)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handleCard object.)


    (fetch (Card Substance) of Card])

(NC.MakeNoteCard
  [LAMBDA (NoteCardType NoteFile Title NoDisplayFlg TypeSpecificArgs Card)
                                                             (* rht: "24-Jul-87 19:40")
                                                             (* Make a new note card of type NoteCardType.
							     If type note specified, ask the user.)

          (* * rht 2/1/85: Added call to NC.MarkCardDirty.)



          (* * fgh 10/15/85 Added extra DatabaseStream argument for use by caching mechanism)



          (* * fgh 11/11/85: Updated to handle new Card object.)



          (* * fgh 2/5/86 Added call to NC.ApplyFn)



          (* * kirk 15May86 Added call to NC.AttachNoteFileName)



          (* * rht 7/4/86: Now checks for read-only notefile before proceeding.)



          (* * kef 8/4/86: Updated to pass NoteCardType argument on to NC.GetNewCard.)



          (* * rht 7/24/87: Replaced WINDOWPROP thing with call to NC.InstallCopyButtonEventFn.)


    (if (NC.ReadOnlyNoteFileP NoteFile)
	then NIL
      else (LET (ReturnValue Window)
	          (COND
		    ([SETQ NoteCardType (OR NoteCardType (NC.AskNoteCardType
						  (fetch (NoteFile Menu) of NoteFile]
		      (SETQ Card (OR (PROGN (type? Card Card)
						  Card)
					 (NC.GetNewCard NoteFile NoteCardType)))
		      (NC.SetNewCardFlg Card T)
		      (NC.ActivateCard Card)
		      (NC.SetType Card NoteCardType)
		      [COND
			((OR [NULL (ERSETQ (SETQ ReturnValue (NC.ApplyFn MakeFn Card Title 
										 NoDisplayFlg 
										 TypeSpecificArgs]
			       (NULL ReturnValue))
			  (NC.SetStatus Card (QUOTE DELETED))
			  (NC.DeactivateCard Card T))
			(T (SETQ Window (WINDOWP ReturnValue))
			   [COND
			     ((NULL (NC.RetrieveTitle Card))
			       [SETQ Title (NC.SetTitle Card (SETQ Title
							      (COND
								((STRINGP Title)
								  Title)
								((AND Title (OR (LITATOM Title)
										    (NUMBERP Title))
									)
								  (MKSTRING Title))
								(T "Untitled"]
			       (AND Window (WINDOWPROP Window (QUOTE TITLE)
							   Title)))
			     (T (NC.SetTitle Card (MKSTRING (NC.RetrieveTitle Card]
			   (COND
			     (Window (WINDOWADDPROP Window (QUOTE CLOSEFN)
						      (FUNCTION NC.QuitCard)
						      (QUOTE FIRST))
				     (WINDOWPROP Window (QUOTE NoteCardObject)
						   Card)
				     (NC.InstallCopyButtonEventFn Window)))
			   (NC.SetTitleDirtyFlg Card T)    (* Reset the type in case of recursive calls change 
							     the type. Always want the highest level type in a 
							     recursive descent)
			   (NC.SetType Card NoteCardType)
                                                             (* Insure that a link ptr is set up during the first 
							     save)
			   (NC.SetLinksDirtyFlg Card T)
			   (NC.SetPropListDirtyFlg Card T)
                                                             (* Mark that substance is dirty.)
			   (NC.MarkCardDirty Card T)
			   (if NC.ShowNoteFileOnCards
			       then (NC.AttachNoteFileName Window]
		      ReturnValue])

(NC.SetNewCardFlg
  [LAMBDA (Card Value)                                       (* fgh: "13-Nov-85 19:00")
                                                             (* Set the new card flg of ID to Value)

          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/11/85: Updated to handle Card object.)


    (replace (Card NewCardFlg) of Card with Value])

(NC.DeactivateCard
  [LAMBDA (Card DeleteTypeAndTitleFlg)                       (* fgh: "30-Aug-86 00:11")

          (* * Remove all the information from the prop list of the NoteCard ID, except for the title which usually statys 
	  cached.)



          (* * rht 7/9/85: Now also removes the new date properties.)



          (* * fgh 10/15/85 altered to use new caching mechanism)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)



          (* * kef 7/16/86: Added the release of the write permission and cancel cache subscription.)



          (* * fgh 8/30/86 Converted APPLY* to NC.ApplyFn.)


    (replace (Card ActiveFlg) of Card with NIL)
    (replace (Card CardCache) of Card with NIL)
    (for CardPart in (QUOTE (SUBSTANCE TOLINKS GLOBALTOLINKS PROPLIST))
       do (NC.ApplyFn ReleaseWritePermissionFn Card CardPart)
	    (NC.ApplyFn CancelCacheSubscriptionFn Card CardPart))
    (if DeleteTypeAndTitleFlg
	then (replace (Card Type) of Card with NIL)
	       (replace (Card Title) of Card with NIL)
	       (NC.ApplyFn CancelCacheSubscriptionFn Card (QUOTE TITLE])

(NC.SetTitleDirtyFlg
  [LAMBDA (Card Value)                                       (* fgh: "13-Nov-85 19:44")

          (* * Set the title cahce is dirty flag)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card TitleDirtyFlg) of Card with Value])

(NC.QuitCard
  [LAMBDA (CardIdentifier CallCloseWFlg DontSaveFlg DontRecacheFlg InterestedWindow OperationMsg 
			  QuietFlg Don'tDeactivateFlg)       (* pmi: "16-Sep-87 10:21")

          (* * Force note card specified by ID to quit or stop)



          (* * rht 2/9/85: New arg DontSaveFlg prevents NC.CardSaveFn from being called. Used when aborting a card.
	  This is NOT equivalent to NC.QuitWithoutSaving.)



          (* * rht 6/25/85: Now moves card off screen before saving if NC.CloseCardsOffScreenFlg is non-nil.)



          (* * rht 6/25/85: Brought the insure proper filing check back here from NC.CardSaveFn. Bails out if user cancelled 
	  operation inside of NC.InsureProperFiling)



          (* * fgh 11/11/85: Updated to handle CardID and CardInfo objects.)



          (* * fgh 1/16/86 Put in code to insure that if one of the TopLevelCards is quit then it is reactivated immedialtely
	  to make sure it stays cached for fast access.)



          (* * fgh 2/5/86 Added call to NC.ApplyFn)



          (* * fgh 5/2/86 Added DontRecacheFlg arg)



          (* * fgh 6/9/86 Added code to check to make sure other operations are not in progress. And DontCheckOpInProgressFlg
	  arg to match)



          (* * fgh 6/26/86 Added InterestedWindow & OperationMsg arg.)



          (* * rht 7/2/86: Now bails out if notefile is readonly, user confirms, but we're supposed to write down changes.)



          (* * rht 7/13/86: Now takes QuietFlg arg.)



          (* * rht 7/14/86: Call NC.DeactivateCard from here instead of in card type QuitFn. Take a Don'tDeactivateFlg as 
	  well.)



          (* * rht 10/7/86: Now removes DELETEME imageobj's from card substance.)



          (* * rht 11/2/86: Now returns DON'T if operation in progress.)



          (* * rht 11/13/86: Now closes open proplist editor if any before saving.)



          (* * rg 3/4/87 rewritten to use new NC.ProtectedCardOperation, removed DontCheckOpInProgressFlg arg)



          (* * rht 3/24/87: Now calls NC.CoerceToInterestedWindow and passes InterestedWindow to NC.InsureProperFiling.)



          (* * rht 4/24/87: Fixed a vmem leak: when CallCloseWFlg is nil it doesn't clear CardObject windowprop.)



          (* * pmi 9/16/87: Undoes previous fix to this function. Needed to get NCLOGGER working. It depends on getting the 
	  CardObject off of the Window passed in as CardIdentifier.)


    (DECLARE (GLOBALVARS NC.RemoveDELETEMEImageObjsFromCardFlg))
    (LET ((Card (NC.CoerceToCard CardIdentifier))
	  Window ReadOnlyCardFlg)
         (NC.ProtectedCardOperation
	   Card "Close Card" InterestedWindow
	   (PROG NIL
	           (SETQ ReadOnlyCardFlg (NC.ReadOnlyCardP Card))
                                                             (* The window not being open should mean that it's 
							     shrunken. If so, expand it.)
	           (SETQ Window (NC.FetchWindow Card))
	           (OR InterestedWindow (SETQ InterestedWindow (NC.CoerceToInterestedWindow
			     Card)))
	           (COND
		     ((AND Window (NOT (OPENWP Window)))
		       (EXPANDW Window)))

          (* * if proper filing says don't quit then get out)


	           [OR DontSaveFlg ReadOnlyCardFlg (COND
			   ((EQ (NC.InsureProperFiling Card InterestedWindow)
				  (QUOTE DON'T))
			     (RETURN (QUOTE DON'T]

          (* * If card is readonly but we've made changes that we're supposed to save, then get user confirmation and bail 
	  out.)


	           (if [AND (NOT DontSaveFlg)
				(NOT Don'tDeactivateFlg)
				ReadOnlyCardFlg
				(NC.CardSomehowDirtyP Card)
				(NULL QuietFlg)
				(NOT (PROGN (NC.PrintMsg InterestedWindow T 
					       "Card has been changed, but notefile is readonly."
							       (CHARACTER 13))
						(NC.AskYesOrNo 
							"Want to quit anyway, flushing changes? "
								 NIL
								 (QUOTE Yes)
								 NIL InterestedWindow]
		       then (RETURN (QUOTE DON'T)))

          (* * Otherwise go ahead and quit)


	           (RETURN (PROGN                        (* Close open proplist editor if any.)
				      [AND Window (LET ((PropListEditorWindow (
									   NC.PropListEditorOpenP
										  Window)))
						         (AND PropListEditorWindow (CLOSEW 
									     PropListEditorWindow]
				      (COND
					((AND Window NC.CloseCardsOffScreenFlg)
					  [COND
					    ((NOT (NC.FetchSavedRegion Card))
					      (NC.SetSavedRegion Card (WINDOWPROP Window
										      (QUOTE REGION]
					  (MOVEW Window 1500 1500)))
				      (OR DontSaveFlg (if ReadOnlyCardFlg
							    then (NC.TurnOffDirtyFlgs Card)
							  else
							   (AND 
							    NC.RemoveDELETEMEImageObjsFromCardFlg
								  (
							       NC.RemoveDELETEMEImageObjsFromCard
								    Card
								    (FUNCTION NC.DELETEMEImageObjP))
								  )
							   (NC.CardSaveFn Card (OR 
									NC.CloseCardsOffScreenFlg 
										       QuietFlg)
									    InterestedWindow 
									    OperationMsg)))
				      (AND Window (WINDOWDELPROP Window (QUOTE CLOSEFN)
								     (FUNCTION NC.QuitCard)))
				      (PROG1 (NC.ApplyFn QuitFn Card)

          (* * (AND Window (WINDOWPROP Window (QUOTE NoteCardObject) NIL)))


					       (AND CallCloseWFlg Window (CLOSEW Window))
					       (OR Don'tDeactivateFlg (NC.DeactivateCard Card))

          (* * if this is one of the top level cards, then make sure it stays cached)


					       (if (AND (NC.TopLevelCardP Card)
							    (NULL DontRecacheFlg)
							    (NULL Don'tDeactivateFlg))
						   then (NCP.ActivateCards Card])

(NC.CardDirtyP
  [LAMBDA (Card)                                             (* fgh: " 5-Feb-86 20:01")

          (* * Return T if card ID has been changed.)



          (* * rht 2/1/85: Now also checks flag on prop list.)



          (* * fgh 11/13/85 Updated to handle Card object.)



          (* * fgh 2/5/86 Added call to NC.ApplyFn)


    (OR (NC.ApplyFn DirtyPFn Card)
	  (NC.FetchSubstanceDirtyFlg Card])

(NC.FetchSubstanceDirtyFlg
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:45")

          (* * fetch the substance cache dirty flag)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (fetch (Card SubstanceDirtyFlg) of Card])

(NC.FetchTitleDirtyFlg
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:44")

          (* * fetch the cached title dirty flag)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (fetch (Card TitleDirtyFlg) of Card])

(NC.FetchPropListDirtyFlg
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:44")

          (* * Fetch the prop liost list cache dirty flag)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (fetch (Card PropListDirtyFlg) of Card])

(NC.FetchLinksDirtyFlg
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:18")

          (* * fetch IDs links dirty flag fom the cache)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (fetch (Card LinksDirtyFlg) of Card])

(NC.SetSavedRegion
  [LAMBDA (Card Region)                                      (* rht: " 5-Jul-86 17:21")

          (* * Cache the saved region of card ID)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)



          (* * rht 7/5/86: Now makes sure region is on screen.)


    (replace (Card SavedRegion) of Card with (MAKEWITHINREGION (create REGION copying
											 Region])

(NC.FetchUserDataProp
  [LAMBDA (Card Prop)                                        (* fgh: "17-Nov-85 18:11")

          (* * Fetch a prop value from Card's UserData entry)


    (AND (fetch (Card UserData) of Card)
	   (LISTGET (fetch (Card UserData) of Card)
		      Prop])

(NC.CardSaveFn
  [LAMBDA (WindowOrID QuietFlg InterestedWindow OperationMsg)
                                                             (* Randy.Gobbel "20-May-87 13:48")

          (* * rht 2/1/85: New function for saving ANY kind of card. All strangenesses are handled in NC.CardDirtyP and 
	  NC.MarkCardDirty. Added print statements to show what is being saved. Lets NC.CardDirtyP take care of proper dirty 
	  checks.)



          (* * rht 2/8/85: Added InsureFilingFlg)



          (* * rht 6/25/85: Pulled out InsureFilingFlg. That check now done upstairs in NC.QuitCard.)



          (* * rht 9/20/85: Added QuietFlg.)



          (* * fgh 11/12/85 Updated to handle Card objects. Removed DatabaseStream object.)



          (* * kirk 29Jan86 replaced call on undefined NC.UpdateRegionData with NC.PutRegion)



          (* * fgh 6/13/86 Added operations in progress code and DontCheckForOpsInProgressFlg arg.)



          (* * fgh 6/26/86 Added InterestedWindow & OperationMsg arg.)



          (* * rht 7/4/86: Added check for readonly notefile.)



          (* * kef 7/22/86: Added something to obtain the write permission on the FROMLINKS if the links have been changed.
	  FROMLINKS aren't ordinarily obtained at edit time like the rest of the links are.)



          (* * kef 7/30/86: Modified to check for Client's concept of whether he owns the write lock or not, thus deciding 
	  whether or not to setup the release of the write lock afterwards.)



          (* * kef 7/30/86: Added a check to see if the NewCardFlg was on, then release TITLE and FROMLINKS writelocks.
	  This is needed since ordinary deactivation of cards won't do this; i.e., only new cards have their TITLE and 
	  FROMLINKS also writelocked.)



          (* * fgh 8/30/86 Changed APPLY* to NC.ApplyFn where possible.)



          (* * rht&pmi 11/21/86: Now calls WhenSavedFn for card type if any.)



          (* * rg 3/4/87 rewritten for new NC.ProtectedCardOperation, removed DontCheckForOpsInProgressFlg)



          (* * rht 3/23/87: Fixed weirdness with InterestedWindow/Window.)



          (* * Rht 3/24/87: Now calls NC.CoerceToInterestedWindow)



          (* * rht 3/30/87: No longer prints messages if nothing got written down.)



          (* * rg 3/31/87 fiddled w/ InterestedWindow stuff)



          (* * rg 5/20/87 added FORCEOUTPUT on stream after all writes done. WARNING! THIS IS A KLUDGE, AND WILL ONLY WORK 
	  FOR OLD-FASHIONED LOCAL NOTEFILES. For remote notefiles, we really need to add another operation to the protocol.)


    (LET ((Card (NC.CoerceToCard WindowOrID))
	  Window OldRegion NewRegion DoneAPutP)
         (NC.ProtectedCardOperation
	   Card "Save Card" InterestedWindow (LET [(WhenSavedFn (GETPROP (NC.FetchType Card)
									   (QUOTE WhenSavedFn]
					          (AND WhenSavedFn (APPLY* WhenSavedFn Card)))
	   (SETQ Window (NC.FetchWindow Card))
	   (OR InterestedWindow (SETQ InterestedWindow (NC.CoerceToInterestedWindow Card)))
	   (if (NC.CheckForNotReadOnly Card InterestedWindow "Can't save cards in ")
	       then (COND
			((OR (NC.CardDirtyP Card)
			       (NC.FetchNewCardFlg Card))
			  (OR QuietFlg (NC.PrintMsg InterestedWindow T (OR OperationMsg "")
							(NC.FetchTitle Card)
							": Saving ... "))
			  (OR QuietFlg (NC.PrintMsg InterestedWindow NIL "substance, "))
			  (NC.PutMainCardData Card T)
			  (SETQ DoneAPutP T)
			  (NC.MarkCardDirty Card (QUOTE RESET)))
			([AND (NOT (NC.FetchBeingDeletedFlg Card))
				Window
				(OR [NOT (EQUAL (fetch (REGION WIDTH) of (SETQ OldRegion
										     (NC.FetchRegion
										       Card)))
						      (fetch (REGION WIDTH)
							 of (SETQ NewRegion (WINDOWPROP
								  Window
								  (QUOTE REGION]
				      (NOT (EQUAL (fetch (REGION HEIGHT) of OldRegion)
						      (fetch (REGION HEIGHT) of NewRegion]
			  (OR DoneAPutP QuietFlg (NC.PrintMsg InterestedWindow T
								  (OR OperationMsg "")
								  (NC.FetchTitle Card)
								  ": Saving ... "))
			  (OR QuietFlg (NC.PrintMsg InterestedWindow NIL "region, "))
			  (NC.PutRegion Card)
			  (SETQ DoneAPutP T)))
		      (COND
			((NC.FetchTitleDirtyFlg Card)
			  (OR DoneAPutP QuietFlg (NC.PrintMsg InterestedWindow T
								  (OR OperationMsg "")
								  (NC.FetchTitle Card)
								  ": Saving ... "))
			  (OR QuietFlg (NC.PrintMsg InterestedWindow NIL "title, "))
			  (NC.PutTitle Card)
			  (SETQ DoneAPutP T)))
		      (COND
			((NC.FetchPropListDirtyFlg Card)
			  (OR DoneAPutP QuietFlg (NC.PrintMsg InterestedWindow T
								  (OR OperationMsg "")
								  (NC.FetchTitle Card)
								  ": Saving ... "))
			  (OR QuietFlg (NC.PrintMsg InterestedWindow NIL "proplist, "))
			  (NC.PutPropList Card)
			  (SETQ DoneAPutP T)))
		      [COND
			((NC.FetchLinksDirtyFlg Card)
			  (OR DoneAPutP QuietFlg (NC.PrintMsg InterestedWindow T
								  (OR OperationMsg "")
								  (NC.FetchTitle Card)
								  ": Saving ... "))
			  (OR QuietFlg (NC.PrintMsg InterestedWindow NIL "links, "))
                                                             (* Make sure that we have the FROMLINKS of this card.
							     Only necessary because all of the LINKS are written 
							     together.)
			  (RESETLST (until (NC.ApplyFn ObtainWritePermissionFn Card (QUOTE
							     FROMLINKS))
					 do (BLOCK)
					      (NC.PrintMsg InterestedWindow NIL 
						     "waiting for FROMLINKS write permission...."))
				      (RESETSAVE NIL (BQUOTE (APPLY* , (fetch (Card 
									 ReleaseWritePermissionFn)
										of Card)
									   , Card FROMLINKS)))
				      (NC.PutLinks Card)
				      (SETQ DoneAPutP T]   (* It's not a new card anymore.)
		      (FORCEOUTPUT (fetch (NoteFile Stream) of (fetch (Card NoteFile)
									of Card))
				     T)
		      (COND
			((NC.FetchNewCardFlg Card)

          (* If a new card, then make sure we release the FROMLINKS and TITLE. Necessary because DeactivateCard normally 
	  doesn't do this, because the FROMLINKS and TITLE aren't ordinarily owned on an active card.)


			  (NC.ApplyFn ReleaseWritePermissionFn Card (QUOTE FROMLINKS))
			  (NC.ApplyFn ReleaseWritePermissionFn Card (QUOTE TITLE))
			  (NC.SetNewCardFlg Card NIL)))
		      (OR QuietFlg (if DoneAPutP
					 then (NC.PrintMsg InterestedWindow NIL "Done."
							       (CHARACTER 13))
						(NC.ClearMsg InterestedWindow T])

(NC.FetchBeingDeletedFlg
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:46")

          (* * fetch IDs being deleted flag from the cache)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (fetch (Card BeingDeletedFlg) of Card])

(NC.FetchTitleDate
  [LAMBDA (Card DontConvertFlg)                              (* fgh: "13-Nov-85 19:47")

          (* * Fetch IDs title date from the cache and and convert to string format if necessary)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (LET ((Date (fetch (Card TitleDate) of Card)))
         (COND
	   ((ZEROP Date)
	     NIL)
	   (DontConvertFlg Date)
	   (T (GDATE Date])

(NC.AssignTitle
  [LAMBDA (CardIdentifier NoClearMsgFlg NewTitle InterestedWindow)
                                                             (* rht: "29-May-87 15:49")

          (* * Change the title of the card specified by the WindowOrTextStreamOrID)



          (* * rht 2/1/85: Changed from NC.PutTitle to NC.SetTitleDirtyFlg, unless card is not active.
	  We shouldn't be writing to the notefile until save time.)



          (* * fgh 11/11/85: Added support for CardID, CardInfo and noteFile objects. Also entered call to Nc.StoreTitle.)



          (* * fgh 6/9/86 Added code to check to make sure that another operation is not in progress on this card when this 
	  fn is called.)



          (* * fgh 6/13/86 Now spawns mouse in case called under MOUSE process.)



          (* * fgh 6/27/86 returns T if completed okay.)



          (* * rht 7/4/86: Added check for readonly card.)



          (* * kef 7/16/86: Added obtain write permission.)



          (* * kef 7/24/86: Doesn't release the write lock if this is a new card.)



          (* * kef 7/30/86: Modified to check for Client's concept of whether he owns the write lock or not, thus deciding 
	  whether or not to setup the release of the write lock afterwards.)



          (* * fgh 8/30/86 Converted to use NC.IfCardPartNotBusy.)



          (* * rg 3/3/87 Enlarged scope of NC.ProtectedCardOperation)



          (* * rht 3/23/87: Now takes InterestedWindow arg.)



          (* * rht 3/24/87: Now calls NC.CoerceToInterestedWindow)



          (* * rht 5/27/87: Now passes title through cross-file link card if dest notefile is open.)



          (* * rht 5/29/87: Now uncaches links if they weren't cached when we came in.)


    (ALLOW.BUTTON.EVENTS)
    (LET ((Card (NC.CoerceToCard CardIdentifier))
	  OldTitle Window)
         (NC.ProtectedCardOperation
	   Card "Assign Title" NIL
	   (NC.IfCardPartNotBusy Card (QUOTE TITLE)
				 (OR InterestedWindow (SETQ InterestedWindow (
					   NC.CoerceToInterestedWindow Card)))
				 (if (NC.CheckForNotReadOnly Card InterestedWindow 
							      "Can't change titles for cards in ")
				     then
				      (COND
					((SETQ NewTitle
					    (OR (STRINGP NewTitle)
						  (AND NewTitle (OR (LITATOM NewTitle)
									(NUMBERP NewTitle))
							 (MKSTRING NewTitle))
						  (NC.AskUser (CONCAT 
								  "Enter the title for this card"
									  (CHARACTER 13))
								"-->  "
								(COND
								  ((AND (STREQUAL (SETQ 
											OldTitle
											(
										 NC.RetrieveTitle
											  Card))
										      "Untitled")
									  (NC.FetchNewCardFlg
									    Card))
								    NIL)
								  (T OldTitle))
								(NULL NoClearMsgFlg)
								InterestedWindow)))
					  (NC.SetTitle Card NewTitle)

          (* * Now do a PutTitle so that anyone else coming along will pick up on the new title. The only exception is if 
	  this card hasn't been written to the NoteFile yet, which is true when the NewCardFlg is T. In that case, we can't 
	  put the title down yet, so just mark it dirty.)


					  (COND
					    ((fetch (Card NewCardFlg) of Card)
					      (NC.SetTitleDirtyFlg Card T))
					    (T (NC.PutTitle Card)
					       (NC.SetTitleDirtyFlg Card NIL)))
					  (AND (WINDOWP (SETQ Window (NC.FetchWindow Card)))
						 (WINDOWPROP Window (QUOTE TITLE)
							       NewTitle))
					  (LET ((LinksWereCachedFlg (NC.LinksCachedP Card)))
					       (if (NOT LinksWereCachedFlg)
						   then (NC.GetLinks Card))
					       [for FromLink in (NC.FetchFromLinks Card)
						  do (LET ((ContainingCard (fetch (Link 
										       SourceCard)
										of FromLink))
							     RemoteCrossFileLinkCard)
							    (if (AND (NC.CrossFileLinkCardP
									   ContainingCard)
									 (SETQ 
									  RemoteCrossFileLinkCard
									   (
								  NC.FetchRemoteCrossFileLinkCard
									     ContainingCard)))
								then (
								   NC.CheckCrossFileLinkCardTitle
									 RemoteCrossFileLinkCard Card)
							      else (AND (NC.ActiveCardP 
										   ContainingCard)
									    (WINDOWP (
										   NC.FetchWindow
											 
										   ContainingCard))
									    (NC.UpdateLinkImages
									      ContainingCard Card]
					       (if (NOT LinksWereCachedFlg)
						   then (NC.UncacheLinks Card)))
					  T))
				   else NIL])

(NC.CheckFiling
  [LAMBDA (Card InterestedWindow)                            (* rht: "26-Mar-87 19:43")
                                                             (* Check to make sure this card has a contents hook of
							     some sort. If not, hook it up to a contents card.)

          (* * rht 12/8/84: Now checks whether both cards *and* fileboxes have been filed.)



          (* * rht 12/9/84: Now files in orphan filebox if NC.ForceFiling flag is off, without bothering the user.)



          (* * rht 2/9/85: Added call to NC.CardNeedsFilingP)



          (* * fgh 11/12/85 Updated to handle Card and NoteFile objects.)



          (* * fgh 6/9/86 Updated to set operation in progress indicator.)



          (* * rg 1/28/87 Make sure we always return a useful value)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation)



          (* * rht 3/23/87: Now takes InterestedWindow arg.)



          (* * Rht 3/24/87: Now calls NC.CoerceToInterestedWindow)



          (* * rht 3/26/87: Changed msg slightly.)


    (NC.ProtectedCardOperation Card "Filing" NIL (COND
				 [(NC.CardNeedsFilingP Card)
				   (OR InterestedWindow (SETQ InterestedWindow (
					     NC.CoerceToInterestedWindow Card)))
				   (COND
				     (NC.ForceFilingFlg (NC.MakeFilingLinks Card
									      (CONCAT "This card ("
											(
										 NC.RetrieveTitle
											  Card)
											
					") is not currently filed in a FileBox in this notefile."
											(CHARACTER
											  13))
									      InterestedWindow))
				     (T (NC.PrintMsg InterestedWindow T "This card (" (
							 NC.RetrieveTitle Card)
						       ") is not currently filed in a FileBox."
						       (CHARACTER 13)
						       "It is being filed in the ToBeFiled FileBox."
						       (CHARACTER 13))
					(NC.HookToOrphanCard Card (fetch (NoteFile ToBeFiledCard)
								       of (fetch (Card NoteFile)
									       of Card]
				 (T T])

(NC.ObtainEditPermission
  [LAMBDA (Card)                                             (* Feuerman " 4-Aug-86 15:08")

          (* * Tries to get permission to edit the Card by obtaining write permission on the SUBSTANCE, TOLINKS and 
	  GLOBALTOLINKS of the Card. If any one of these fail, those that had been obtained so far are released and NIL is 
	  returns, otherwise T.)



          (* * kef 7/22/86: Added PROPLIST to the set of card parts that need to have their write locks owned.)



          (* * kef 8/4/86: Modified so that if a window already exists for the card, the write locks aren't re-obtained, thus
	  not messing up the write lock count.)


    (PROG [(WRITEPERMISSIONFN (fetch (NoteFile ObtainWritePermissionFn)
				   of (fetch (Card NoteFile) of Card)))
	     (WRITERELEASEFN (fetch (NoteFile ReleaseWritePermissionFn) of (fetch (Card 
											 NoteFile)
										  of Card]
	    (RETURN (OR (NC.FetchWindow Card)
			    (COND
			      ((APPLY* WRITEPERMISSIONFN Card (QUOTE SUBSTANCE))
				(COND
				  ((APPLY* WRITEPERMISSIONFN Card (QUOTE TOLINKS))
				    (COND
				      ((APPLY* WRITEPERMISSIONFN Card (QUOTE GLOBALTOLINKS))
					(COND
					  ((APPLY* WRITEPERMISSIONFN Card (QUOTE PROPLIST))
					    T)
					  (T (APPLY* WRITERELEASEFN Card (QUOTE GLOBALTOLINKS))
					     (APPLY* WRITERELEASEFN Card (QUOTE SUBSTANCE))
					     (APPLY* WRITERELEASEFN Card (QUOTE TOLINKS))
					     NIL)))
				      (T (APPLY* WRITERELEASEFN Card (QUOTE SUBSTANCE))
					 (APPLY* WRITERELEASEFN Card (QUOTE TOLINKS))
					 NIL)))
				  (T (APPLY* WRITERELEASEFN Card (QUOTE SUBSTANCE))
				     NIL)))
			      (T NIL])

(NC.RetrieveTypeAndTitle
  [LAMBDA (Card)                                             (* fgh: " 3-Sep-86 21:03")

          (* * Retrieve the type and title of a card using NC.GetCardInfo where possible to decrease Courier calls if using 
	  server.)



          (* * fgh 9/3/86 First created.)


    (LET (Type Title Info)
         (if (EQ (NC.FetchStatus Card)
		     (QUOTE ACTIVE))
	     then [if (SETQ Type (NC.FetchType Card))
			then [if (SETQ Title (NC.FetchTitle Card))
				   then NIL
				 else (NC.SetTitle Card (SETQ Title (NC.GetTitle Card]
		      else (if (SETQ Title (NC.FetchTitle Card))
				 then (NC.SetType Card (SETQ Type (NC.GetType Card)))
			       else [SETQ Info (NC.ApplyFn GetCardInfoFn Card
							       (QUOTE (TYPE TITLE]
				      [NC.SetTitle Card (SETQ Title (CDR (FASSOC
										 (QUOTE TITLE)
										 Info]
				      (NC.SetType Card (SETQ Type (CDR (FASSOC (QUOTE
											 TYPE)
										       Info]
		    (CONS Type Title])

(NC.FetchLinkDisplayMode
  [LAMBDA (Card)                                             (* fgh: " 5-Feb-86 13:40")

          (* * Fetch the default link display mode corresponding to Card)



          (* * fgh 2/5/86 First created.)


    (fetch (Card LinkDisplayMode) of Card])

(NC.DeleteNoteCardInternal
  [LAMBDA (Card QuietFlg InterestedWindow IgnoreLinksFlg)    (* rht: " 8-Jun-87 23:47")

          (* * Delete a single note card from a NoteFile)



          (* * rht 8/11/86 Now calls NC.DeleteReferencesToCardFromShowLinks to smash any link icons in show links menus 
	  pointing to this card.)



          (* * kef 7/28/86: Added code to obtain all of the write locks deemed necessary.)



          (* * kef 7/30/86: Modified to check for Client's concept of whether he owns the write lock or not, thus deciding 
	  whether or not to setup the release of the write lock afterwards.)



          (* * kef 7/31/86: Added the nesting of the obtaining writelocks with deactivating the card.)



          (* * fgh 8/30/86 Translated APPLY* to NC.ApplyFn. Made cosmetic changes in FOR loop concewrning WriteLocks.)



          (* * rht 1/16/87: Moved call to MarkCardDeletedFn after call to NC.QuitCard.)



          (* * rg 3/11/87 renamed)



          (* * rht 3/13/87: Added QuietFlg, InterestedWindow, and IgnoreLinksFlg args. The latter non-nil causes card 
	  deletion but no link cutting.)



          (* * rht 3/25/87: Now calls NC.CoerceToInterestedWindow.)



          (* * rht 5/27/87: Changed to match reduced functionality of NC.ValidLinkP, now checks that DestinationCard and 
	  SourceCard are valid cards.)



          (* * pmi 6/8/87: Moved call to NC.GreyCard to beginning of this function.)


    (RESETLST (RESETSAVE (CURSOR WAITINGCURSOR))
		(RESETSAVE NIL (BQUOTE (NC.SetBeingDeletedFlg , Card NIL)))
		(WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
			      (OR (OPENWP InterestedWindow)
				    (SETQ InterestedWindow (NC.CoerceToInterestedWindow Card)))
			      (LET ((WriteLocks (for CardPart
						   in (QUOTE (SUBSTANCE TITLE TOLINKS FROMLINKS 
									    GLOBALTOLINKS PROPLIST))
						   collect (CONS Card CardPart)))
				    ToLinks FromLinks Window BusyPart)
			           (NC.SetBeingDeletedFlg Card T)

          (* * First grey the card being deleted.)


			           (NC.GreyCard Card)
			           [if (NOT IgnoreLinksFlg)
				       then (SETQ ToLinks (NC.RetrieveToLinks Card))
					      (SETQ FromLinks (NC.RetrieveFromLinks Card))
					      [for ToLink in ToLinks
						 do (NCONC WriteLocks
							       (for CardPart
								  in (QUOTE (TOLINKS FROMLINKS 
										    GLOBALTOLINKS))
								  collect
								   (CONS (fetch (Link 
										  DestinationCard)
									      of ToLink)
									   CardPart]
					      (for FromLink in FromLinks
						 do (NCONC WriteLocks
							       (for CardPart
								  in (QUOTE (SUBSTANCE TOLINKS 
											FROMLINKS 
										    GLOBALTOLINKS))
								  collect
								   (CONS (fetch (Link SourceCard)
									      of FromLink)
									   CardPart]

          (* * The for... loop that follows is the condition that we can obtain all of the write locks on all of the card 
	  parts collected in WriteLocks. If we obtain a writelock, setup a RESETSAVE to release it upon exit.
	  Then finally, if we do obtain a write lock, return T so that the for loop's "always" condition is satisfied.
	  If we don't obtain a write lock for a given card part, save that one as a variable so we can report it to the user.
	  Then return NIL, so that the for loop's "always" condition is not satisfied, and we bump out of the for loop.)


			           (OR QuietFlg (NC.PrintMsg InterestedWindow T 
								 "Collecting write locks..."))
			           (COND
				     ((for WriteLock in WriteLocks bind WLCard WLCardPart
					 when (NC.ValidCardP (SETQ WLCard (CAR WriteLock)))
					 always (SETQ WLCardPart (CDR WriteLock))
						  (COND
						    ((NC.ApplyFn ObtainWritePermissionFn WLCard 
								 WLCardPart)
						      (RESETSAVE NIL
								   (BQUOTE
								     (APPLY* , (fetch
										 (Card 
									 ReleaseWritePermissionFn)
										    of WLCard)
									       , WLCard , WLCardPart))
								   )
						      T)
						    (T (SETQ BusyPart WriteLock)
						       NIL)))

          (* * Call off to the MarkCardDeletedFn specific to the NoteFile.)


				       (RESETSAVE (for CardPart
						       in (QUOTE (SUBSTANCE TOLINKS GLOBALTOLINKS 
										PROPLIST))
						       do (NC.ApplyFn ObtainWritePermissionFn Card 
									CardPart))
						    (BQUOTE (NC.DeactivateCard , Card T)))
				       (NC.ApplyFn MarkCardDeletedFn Card)
				       (NC.SetToLinks Card NIL)
				       (NC.SetFromLinks Card NIL)
				       (if (NOT IgnoreLinksFlg)
					   then (OR QuietFlg (NC.PrintMsg InterestedWindow NIL 
						      "Removing links to and from other cards..."))
						  (for ToLink in ToLinks bind DestCard
						     when [AND (NC.ValidLinkP ToLink)
								   (NC.ValidCardP
								     (SETQ DestCard
								       (fetch (Link DestinationCard)
									  of ToLink]
						     do (NC.DelFromLink ToLink)
							  (NC.DelReferencesToCardFromShowLinks
							    DestCard ToLink))
						  (for FromLink in FromLinks bind SourceCard
						     when [AND (NC.ValidLinkP FromLink)
								   (NC.ValidCardP
								     (SETQ SourceCard
								       (fetch (Link SourceCard)
									  of FromLink]
						     do (NC.DelToLink FromLink)
							  (NC.DelReferencesToCard SourceCard Card)
							  (NC.DelReferencesToCardFromShowLinks
							    SourceCard FromLink))
						  (OR QuietFlg (NC.PrintMsg InterestedWindow NIL 
										"..done.")))
				       (if (NC.ActiveCardP Card)
					   then (NC.TurnOffDirtyFlgs Card)
						  (NC.CloseAllPropListEditors Card)
						  (NC.QuitCard Card T T))
				       (NC.ApplyFn MarkCardDeletedFn Card)
				       (NC.SetNewCardFlg Card NIL))
				     (T (NC.CardPartBusy (CAR BusyPart)
							   (CDR BusyPart)
							   InterestedWindow])

(NC.SetBeingDeletedFlg
  [LAMBDA (Card Value)                                       (* fgh: "13-Nov-85 19:46")

          (* * Set the being deleted flag in the cache)



          (* * rht 11/10/85: Updated to handle CardID scheme and new version of NC.FetchCardCache.)



          (* * fgh 11/13/85 Updated to handle Card object.)


    (replace (Card BeingDeletedFlg) of Card with Value])

(NC.ClosePropListEditor
  [LAMBDA (Window SaveFlg)                                   (* rht: "24-Apr-87 16:49")

          (* Close the prop list editor, saving or not saving the edited prop list as specified by the SaveFlg or by the user
	  if SaveFlg is NIL)



          (* * fgh 11/13/85 Updated to handle Card object.)



          (* * fgh 6/8/86 Added call to RAPOSITIONATTACHEDWINDOWS)



          (* * rht 8/12/86 Now uses TEXTOBJ to get TextObj from window.)



          (* * kef 7/16/86: Added the call to release the write permission should the window property declare that it be 
	  necessary.)



          (* * kef 7/22/86: Now only releases the write permission if the card is inactive. The reason is that it was 
	  determined that a card being edited would update the property list upon being closed.)



          (* * fgh 8/30/86 Converted APPLY* to NC.ApplyFn. Added Card local var.)



          (* * rht 11/12/86: Now calls MAINWINDOW instead of WINDOWPROP to get Window's mainwindow and recovers card from a 
	  prop of Window.)



          (* * rht 1/16/87: Now checks that tedit stream has been modified before using user as to whether to save changes.
	  No longer puts up stupid save/cancel menu.)



          (* * rht&rg 4/24/87: Now smashes more windowprops to prevent storage leaks.)


    (DECLARE (GLOBALVARS NC.SavePropEditMenu))
    (PROG (TextObj Answered OldPropList NewPropList MainWindow Card)
	    (SETQ Card (WINDOWPROP Window (QUOTE SavedCardObject)))
	    (SETQ MainWindow (MAINWINDOW Window))
	    (DETACHWINDOW Window)
	    [SETQ TextObj (CAR (NLSETQ (TEXTOBJ Window]
	    (SETQ OldPropList (WINDOWPROP Window (QUOTE PROPERTYLIST.BEING.EDITED)))
	    [AND TextObj (COND
		     ((EQ SaveFlg (QUOTE NoSave)))
		     ((EQ (WINDOWPROP Window (QUOTE PropListEditor))
			    (QUOTE ShowOnly)))
		     ((OR (EQ SaveFlg (QUOTE Save))
			    (TEDIT.STREAMCHANGEDP TextObj))
		       (SETQ NewPropList (NC.ExtractPropList Window))
		       (NC.ProcessEditedPropList NewPropList OldPropList Card]
	    (WINDOWPROP Window (QUOTE TEDIT.MENU)
			  NIL)
	    (WINDOWPROP Window (QUOTE TEDIT.PROPS)
			  NIL)
	    (WINDOWPROP Window (QUOTE PropListEditor)
			  NIL)
	    (WINDOWPROP Window (QUOTE SavedCardObject)
			  NIL)
	    (WINDOWPROP Window (QUOTE PROPERTYLIST.BEING.EDITED)
			  NIL)
	    (WINDOWPROP Window (QUOTE PROPERTYLIST.PROPNAMES)
			  NIL)
	    (WINDOWDELPROP Window (QUOTE CLOSEFN)
			     (FUNCTION NC.ClosePropListEditor))
	    (COND
	      ((AND (WINDOWPROP Window (QUOTE ReleaseWritePermissionP))
		      (NOT (NC.ActiveCardP Card)))
		(NC.ApplyFn ReleaseWritePermissionFn Card (QUOTE PROPLIST))
		(WINDOWPROP Window (QUOTE ReleaseWritePermissionP)
			      NIL)))
	    [COND
	      (TextObj (replace (TEXTOBJ \DIRTY) of TextObj with NIL)
		       [\TEDIT.QUIT (CAR (MKLIST (fetch (TEXTOBJ \WINDOW) of TextObj]
		       (until (fetch (TEXTOBJ EDITFINISHEDFLG) of TextObj) do (BLOCK]
	    (ADD.PROCESS (BQUOTE (PROGN (until (NULL (OPENWP , Window)) do (BLOCK))
					      (REPOSITIONATTACHEDWINDOWS , MainWindow])

(NC.FetchLinkIconAttachedBitMap
  [LAMBDA (Card ScaledHeightToMatch Scale)                   (* rht: " 7-Aug-86 18:00")

          (* * Return the default link icon attached bit map corresponding to Card)



          (* * fgh 2/5/86 First created.)



          (* * rht 5/10/86: Now takes special action if BitMapVal is a list. In that case, it should be an ordered prop list 
	  of heights and bitmaps. We take the one closest in height to HeightToMatch.)



          (* * rht 8/7/86: Now converts single bitmap to list of bitmaps of different heights if necessary.
	  Also now takes Scale argument.)


    (LET ((BitMapVal (fetch (Card LinkIconAttachedBitMap) of Card)))
         [if (BITMAPP BitMapVal)
	     then (replace (NoteCardType LinkIconAttachedBitMap) of (NC.CardTypeRecord
									    (NC.FetchType Card))
		       with (SETQ BitMapVal (NC.MakeTypeIconBitMapSet BitMapVal 
							  NC.DefaultLinkIconAttachedBitMapHeights]
         (if (LISTP BitMapVal)
	     then (OR ScaledHeightToMatch (SETQ ScaledHeightToMatch 0))
		    (OR Scale (SETQ Scale 1))
		    (LET (BitMap)
		         [for X on BitMapVal by (CDDR X)
			    do (LET [(ScaledHeight (TIMES Scale (CAR X]
				      (if (OR (NULL BitMap)
						  (LEQ ScaledHeight ScaledHeightToMatch))
					  then (SETQ BitMap (CADR X))
					elseif (GREATERP ScaledHeight ScaledHeightToMatch)
					  then (RETURN]
		     BitMap])

(NC.FetchLinkAnchorModesSupported
  [LAMBDA (Card)                                             (* fgh: " 5-Feb-86 13:45")

          (* * Fetch the link anchor modes supported of Card)


    (fetch (Card LinkAnchorModesSupported) of Card])

(NC.DeleteNoteCard
  [LAMBDA (CardIdentifier DontClearFlg NoConfirmFlg QuietFlg InterestedWindow)
                                                             (* pmi: "27-Mar-87 16:22")

          (* * User interface level fn to delete a single note card from a NoteFile)



          (* * rht 3/25/87: Added a bunch of new args. Fixed InterestedWindow stuff.)



          (* * 3/26/87: Now clears InterestedWindow when done.)



          (* * pmi 3/27/87: Changed call of NC.SeverAllLinks to NC.SeverExternalLinks.)


    (LET ((Card (NC.CoerceToCard CardIdentifier)))
         (if (NC.ValidCardP Card)
	     then (OR InterestedWindow (SETQ InterestedWindow (NC.CoerceToInterestedWindow
			      Card)))
		    (NC.ProtectedCardOperation Card "Delete Note Card" InterestedWindow
					       (AND (if (NC.TopLevelCardP Card)
							  then (NC.PrintMsg InterestedWindow T 
								"You cannot delete this FileBox."
										(CHARACTER 13))
								 (DISMISS 1000)
								 (NC.ClearMsg InterestedWindow T)
								 NIL
							else T)
						      (NC.CheckForNotReadOnly Card InterestedWindow 
								     "Can't delete cards from a ")
						      (OR NoConfirmFlg
							    (PROG1 (NC.AskYesOrNo 
							  "Are you sure you want to delete this?"
										      " -- " "Yes"
										      (NULL 
										     DontClearFlg)
										      
										 InterestedWindow NIL 
										      NIL)
								     (NC.ClearMsg InterestedWindow 
										    T)))
						      (PROGN 

          (* * Mark UID of card about to be deleted.)


							       (NC.UIDPutProp (fetch
										  (Card UID)
										   of Card)
										(QUOTE 
									      AboutToBeDeletedFlg)
										T)

          (* * Sever all links into and out of Card)


							       (NC.SeverExternalLinks (LIST
											  Card)
											QuietFlg 
										 InterestedWindow)

          (* * Now delete the card)


							       (PROG1 (NC.DeleteNoteCardInternal
									  Card QuietFlg 
									  InterestedWindow)
									(OR QuietFlg
									      (NC.ClearMsg 
										 InterestedWindow T])

(NC.FetchRegionViewed
  [LAMBDA (Card)                                             (* fgh: "13-Nov-85 19:21")

          (* * For sketch cards -- fetch from the UserData prop list the region viewed property)



          (* * fgh 11/12/85 Updated to handle Card objects.)


    (LISTGET (fetch (Card UserData) of Card)
	       (QUOTE RegionViewed])

(NC.FetchSlotNum
  [LAMBDA (Card)                                             (* kirk: " 9-Sep-86 08:55")

          (* * compute card's slot number in the notefile)


    (ADD1 (QUOTIENT [DIFFERENCE (fetch (Card IndexLoc) of Card)
				      (CONSTANT (fetch (NoteFileVersion NoteFileHeaderSize)
						     of (NCLocalDevice.CurrentVersion]
			(CONSTANT (fetch (NoteFileVersion NoteFileIndexWidth) of (
								     NCLocalDevice.CurrentVersion])

(NC.SetUserDataPropList
  [LAMBDA (Card PropList)                                    (* rht: "19-Dec-85 16:51")

          (* * Replace the user data prop list of Card.)


    (replace (Card UserData) of Card with PropList])

(NC.AddParents
  [LAMBDA (WindowOrTextStream)                               (* Randy.Gobbel " 2-Apr-87 15:38")

          (* Add a subtopic link from a contents card specified by the user to the contents card specified by 
	  WindowOrTextStream. But first check to make sure that this would not introduce any circularities in the contents 
	  lattice.)



          (* * rht 12/8/84: Massive shaving. Now calls NC.MakeChildLink to do the tough work.)



          (* * rht 10/3/85: No longer prints final, annoying, slow-to-disappear message in prompt window if nothing 
	  selected.)



          (* * fgh 11/13/85 Updated to handle Card object.)



          (* * fgh 6/9/86 Added code to check to make sure that another operation is not in progress on this card when this 
	  fn is called.)



          (* * rht 7/5/86: Now checks for readonly cards.)



          (* * rht&pmi 11/24/86: Surrounded call to NC.MakeChildLink with NC.ActivateCardAndDo so that ParentCard will be 
	  active for duration of the call.)



          (* * pmi 12/5/86: Modified message to NC.SelectNoteCards to mention SHIFT-selection.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 1/28/87: Took out call to NC.ActivateCardAndDo. Need to make sure ParentCard gets saved after getting link
	  if wasn't active originally.)



          (* * rg 3/3/87 Enlarged scope of NC.ProtectedCardOperation)



          (* * rg 3/18/87 added NC.CardSelectionOperation wrapper)



          (* * rg 4/2/87 changed NC.CardSelectionOperation to NCP.WithLockedCards)


    (NCP.WithLockedCards (LET (Card NewParents (Window (WINDOW.FROM.TEDIT.THING WindowOrTextStream))
				    )
			      (SETQ Card (NC.CoerceToCard Window))
			      (NC.ProtectedCardOperation
				Card "Designate FileBoxes" NIL
				(if (NC.CheckForNotReadOnly Card Window "Can't do filing in ")
				    then (SETQ NewParents (NC.SelectNoteCards
					       NIL
					       (FUNCTION NC.FileBoxP)
					       NC.SelectingParentsMenu Card 
					       " Please shift-select the new parent FileBox(es)."))
					   (AND NewParents Card
						  (for ParentCard in NewParents bind OneHook
						     when [LET ((WasActiveFlg (NC.ActiveCardP
										  ParentCard)))
							         (OR WasActiveFlg (NC.GetNoteCard
									 ParentCard))
							         (PROG1 (NC.MakeChildLink Card 
										       ParentCard 
											   Window)
									  (OR WasActiveFlg
										(NC.QuitCard 
										       ParentCard NIL 
											      NIL NIL 
											      NIL NIL 
											       T]
						     do (SETQ OneHook T) finally (RETURN
											 OneHook])

(NC.SeverExternalLinks
  [LAMBDA (ListOfCards QuietFlg InterestedWindow)            (* pmi: " 8-Jun-87 09:44")

          (* * Delete all links in ListOfCards to or from cards not in ListOfCards. Furthermore, do it efficiently by caching
	  an external card only long enough to delete all the links between it and ListOfCards. Note that we depend on the 
	  fact that every card in ListOfCards has its AboutToBeDeletedFlg set.)



          (* * rht&pmi 5/29/87: Now passes non-nil LeaveCachedFlg to NC.RetrieveToLinks and NC.RetrieveFromLinks.
	  Not sure if this is really necessary.)



          (* * pmi 6/8/87: Added call to NC.GreyCard to grey cards being deleted before deleting all of their links.)


    (LET (LinksToSever NumLinksToSever)
         (OR QuietFlg (NC.PrintMsg InterestedWindow T "Gathering external links of "
				       (LENGTH ListOfCards)
				       " cards."))
         [SETQ LinksToSever (NC.UnionListsOfLinks
	     (for Card in ListOfCards
		join                                       (* Grey the cards being deleted.)
		       (NC.GreyCard Card)
		       (for Link in (NC.RetrieveToLinks Card T)
			  unless (NC.UIDGetProp (fetch (Card UID) of (fetch (Link 
										  DestinationCard)
										of Link))
						    (QUOTE AboutToBeDeletedFlg))
			  collect Link))
	     (for Card in ListOfCards join (for Link in (NC.RetrieveFromLinks Card T)
						    unless (NC.UIDGetProp
							       (fetch (Card UID)
								  of (fetch (Link SourceCard)
									  of Link))
							       (QUOTE AboutToBeDeletedFlg))
						    collect Link]

          (* * Now sort links so that links with same external anchor card are grouped together. Furthermore, the links 
	  having that anchor card has source card are grouped before the ones having that card as destination card.)


         (OR QuietFlg (NC.PrintMsg InterestedWindow T "Sorting " (SETQ NumLinksToSever
					 (LENGTH LinksToSever))
				       " links prior to severing."))
         [SORT LinksToSever (FUNCTION (LAMBDA (Link1 Link2)
		     (LET (DestCard1 DestCard2 ExtCard1 ExtCard2 Link1SourceIsExtFlg)
		          (SETQ ExtCard1 (if (NC.UIDGetProp (fetch (Card UID)
								     of (SETQ DestCard1
									    (fetch (Link 
										  DestinationCard)
									       of Link1)))
								  (QUOTE AboutToBeDeletedFlg))
					       then (SETQ Link1SourceIsExtFlg T)
						      (fetch (Link SourceCard) of Link1)
					     else DestCard1))
		          (SETQ ExtCard2 (if (NC.UIDGetProp (fetch (Card UID)
								     of (SETQ DestCard2
									    (fetch (Link 
										  DestinationCard)
									       of Link2)))
								  (QUOTE AboutToBeDeletedFlg))
					       then (fetch (Link SourceCard) of Link2)
					     else DestCard2))
		          (if (NC.SameCardP ExtCard1 ExtCard2)
			      then Link1SourceIsExtFlg
			    else (LESSP (fetch (Card IndexLoc) of ExtCard1)
					    (fetch (Card IndexLoc) of ExtCard2]

          (* * Now walk down the list of links one by one activating the external anchor cards as needed.)


         (OR QuietFlg (NC.PrintMsg InterestedWindow T "Severing links: 1 out of " NumLinksToSever 
				       " ..."))
         (for Link in LinksToSever as i from 1 bind PreviousExtCard WasNotActiveFlg 
							      PreviousExtCardIsSourceFlg
	    eachtime (BLOCK) when (NC.ValidLinkP Link)
	    do (OR QuietFlg (if (ZEROP (REMAINDER i 10))
				    then (NC.PrintMsg InterestedWindow T "Severing links: " i 
							  " out of "
							  NumLinksToSever " ...")))
		 (LET (ExtCard ExtCardIsSourceFlg)
		      (SETQ ExtCard (if (NC.UIDGetProp (fetch (Card UID)
								of (fetch (Link DestinationCard)
									of Link))
							     (QUOTE AboutToBeDeletedFlg))
					  then (SETQ ExtCardIsSourceFlg T)
						 (fetch (Link SourceCard) of Link)
					else (fetch (Link DestinationCard) of Link)))
		      [if (NOT (NC.SameCardP ExtCard PreviousExtCard))
			  then                             (* Write down changes to previous external card's 
							     substance.)
				 (if WasNotActiveFlg
				     then (if PreviousExtCardIsSourceFlg
						then       (* Have to call NC.CardSaveFn first and then 
							     NC.QuitCard with Don'tSaveFlg to avoid 
							     insureProperFiling check.)
						       (NC.CardSaveFn PreviousExtCard T)
						       (NC.QuitCard PreviousExtCard NIL T NIL NIL 
								      NIL T)
					      else (NC.PutLinks PreviousExtCard)))
                                                             (* If ExtCard not active, then cache.)
				 (if (SETQ WasNotActiveFlg (NOT (NC.ActiveCardP ExtCard)))
				     then (if ExtCardIsSourceFlg
						then       (* Cache whole card if it's the link's source.)
						       (NC.GetNoteCard ExtCard)
					      else         (* Else only need the links since we're deleting the 
							     from link.)
						     (NC.GetLinks ExtCard]
                                                             (* Delete the appropriate half of the link.)
		      (if ExtCardIsSourceFlg
			  then (NC.DeleteToLink Link)
			else (NC.DeleteFromLink Link))
		      (replace (Link UID) of Link with -1)
		      (SETQ PreviousExtCard ExtCard)
		      (SETQ PreviousExtCardIsSourceFlg ExtCardIsSourceFlg))
	    finally (if (AND WasNotActiveFlg (NC.ValidCardP PreviousExtCard))
			  then (if PreviousExtCardIsSourceFlg
				     then                  (* Have to call NC.CardSaveFn first and then 
							     NC.QuitCard with Don'tSaveFlg to avoid 
							     insureProperFiling check.)
					    (NC.CardSaveFn PreviousExtCard T)
					    (NC.QuitCard PreviousExtCard NIL T NIL NIL NIL T)
				   else (NC.PutLinks PreviousExtCard])

(NC.DeleteNoteCards
  [LAMBDA (CardIdentifiers NoIndividualConfirmFlg DontClearFlg InterestedWindow QuietFlg 
			   NoGroupConfirmFlg)                (* Randy.Gobbel " 2-Apr-87 16:05")
                                                             (* Delete note cards. If no card specified then get a 
							     list of note cards to be deleted.
							     Then delete these cards.)

          (* * fgh 11/11/85: Updated to handle new Card objects. Also split off main work of deleteing a single note card 
	  into NC.DeleteNoteCard function.)



          (* * kirk 21Feb86 Added InterestedWindow)



          (* * kirk 29Apr86 Now returns CardIdentifiers)



          (* * fgh 6/9/86 Added checks to see if other operations are in progress)



          (* * rht 7/4/86: Now checks that card is not read-only.)



          (* * kirk 18Aug86 Added main window for windowless cards.)



          (* * rht 8/29/86: Reorganized and added call to NC.SeverAllLinks to make deleting more efficient.
	  Added QuietFlg, NoGroupConfirmFlg and Don'tPutToBeDeletedCardsFlg args.)



          (* * rht 9/5/86: Now forces NoGroupConfirmFlg to be non-nil if NoIndividualConfirmFlg is NIL and only one card to 
	  delete.)



          (* * pmi 12/5/86: Modified message to NC.SelectNoteCards to mention SHIFT-selection.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 12/16/86: Removed obsolete Don'tPutToBeDeletedCardsFlg arg.)



          (* * rht 3/9/87: Changed NC.DeleteSelectingMenu to NC.SelectingCardsMenu.)



          (* * rg 3/9/87 added NC.ProtectedSessionOperation wrapper)



          (* * rg 3/11/87 changed call of NC.DeleteNoteCard to NC.DeleteNoteCardInternal)



          (* * rg 3/18/87 changed NC.ProtectedSessionOperation to NC.CardSelectionOperation)



          (* * rht 3/30/87: Now calls NC.SeverExternalLinks rather than NC.SeverAllLinks.)



          (* * rg 3/31/87 now protects cards passed in in list)


    (DECLARE (GLOBALVARS NC.SelectingCardsMenu))
    (NCP.WithLockedCards
      (NC.IfAllCardsFree (NC.LockListOfCards (MKLIST CardIdentifiers)
					       "Delete Note Cards")
			 (OR CardIdentifiers (SETQ CardIdentifiers
				 (NC.SelectNoteCards NIL NIL NC.SelectingCardsMenu InterestedWindow 
					      "Please shift-select the Note Cards to be deleted.")))

          (* * Kludge in case args are nil, say, when we're called from a card's menu.)


			 (if (AND (NULL NoIndividualConfirmFlg)
				      (NULL NoGroupConfirmFlg)
				      (EQ (LENGTH (MKLIST CardIdentifiers))
					    1))
			     then (SETQ NoGroupConfirmFlg T)
				    (SETQ QuietFlg T))

          (* * First collect cards that are deletable.)


			 (LET ((CardsToDelete (for CardIdentifier in (MKLIST CardIdentifiers)
						 bind Card eachtime (BLOCK)
						 when
						  [AND (SETQ Card (NC.CoerceToCard 
										   CardIdentifier))
							 (if (NOT (NC.TopLevelCardP Card))
							   else (NC.PrintMsg (NC.FetchWindow
										   Card)
										 T 
								"You cannot delete this FileBox."
										 (CHARACTER 13))
								  (DISMISS 1000)
								  (NC.ClearMsg (NC.FetchWindow
										   Card)
										 T)
								  NIL)
							 (NC.CheckForNotReadOnly Card (
										   NC.FetchWindow
										     Card)
										   
								     "Can't delete cards from a ")
							 (OR NoIndividualConfirmFlg
							       (PROG1 (NC.AskYesOrNo
									  
							  "Are you sure you want to delete this?"
									  " -- " "Yes" (NULL 
										     DontClearFlg)
									  (OR (NC.FetchWindow
										  Card)
										InterestedWindow)
									  NIL NIL)
									(NC.ClearMsg]
						 collect Card))
			       (NumSpecified (LENGTH (MKLIST CardIdentifiers)))
			       NumToDelete)
			      (SETQ NumToDelete (LENGTH CardsToDelete))
			      (if [AND (GREATERP NumToDelete 0)
					   (if (EQUAL NumToDelete NumSpecified)
					       then (OR NoGroupConfirmFlg
							    (PROG1 (NC.AskYesOrNo
								       (CONCAT "You've specified " 
										 NumToDelete 
									      " cards to delete."
										 (CHARACTER 13)
										 
							 "Are you sure you want to delete them? ")
								       NIL "Yes" (NULL DontClearFlg)
								       InterestedWindow)
								     (NC.ClearMsg)))
					     else (PROG1 (NC.AskYesOrNo (CONCAT "Out of " 
										     NumSpecified 
									     " cards specified, "
											(DIFFERENCE
											  
										     NumSpecified 
										      NumToDelete)
											
									    " are not deletable."
											(CHARACTER
											  13)
											
								  "Want to delete the remaining "
											NumToDelete 
										       " cards? ")
									      NIL "Yes" (NULL
										DontClearFlg)
									      InterestedWindow)
							     (NC.ClearMsg]
				  then 

          (* * Mark UIDs of cards about to be deleted.)


					 (for Card in CardsToDelete
					    do (NC.UIDPutProp (fetch (Card UID) of Card)
								  (QUOTE AboutToBeDeletedFlg)
								  T))

          (* * Sever all links into and out of CardsToDelete)


					 (NC.SeverExternalLinks CardsToDelete QuietFlg 
								  InterestedWindow)

          (* * Now delete the cards one at a time.)


					 (OR QuietFlg (NC.PrintMsg InterestedWindow T 
								      "Deleting cards: 1 out of "
								       NumToDelete " ..."))
					 (for Card in CardsToDelete as i from 1
					    eachtime (BLOCK)
					    do (OR QuietFlg
						       (if (ZEROP (REMAINDER i 10))
							   then (NC.PrintMsg InterestedWindow T 
									       "Deleting cards: "
										 i " out of " 
										 NumToDelete " ...")))
						 (NC.DeleteNoteCardInternal Card QuietFlg 
									      InterestedWindow T))
					 (OR QuietFlg (NC.ClearMsg InterestedWindow T))
					 CardIdentifiers])

(NC.QuitWithoutSaving
  [LAMBDA (CardIdentifier)                                   (* Randy.Gobbel "16-Mar-87 18:25")

          (* Quit from a note card without saving its contents on the database. But must make sure that any updates that 
	  would have been done to this card even if it had been on the database are carried out on the old image currently on
	  the database)



          (* * rht 2/1/85: Now only writes out links if it has to. Also resets dirty flags and calls normal quit procedure.
	  I think we've still got possible problems with recently changed titles, both ours and those of cards we point to.)



          (* * rht 2/3/85: Now handles title changes properly. Also fixed so that changes to from links will force links to 
	  be written.)



          (* * rht 2/9/85: Now accepts IDs as arg.)



          (* * fgh 11/12/85: Updated to handle Card objects. Removed DatabaseStream argument.)



          (* * fgh 6/4/86 No longer asks for confirmation if no changes have been made.)



          (* * kef 8/7/86: Now compares ToLinks by NC.SameUIDP rather than EQ. Situation comes up in Server, when the same 
	  UIDs may not be EQ. Also, now obtains write lock on FROMLINKS before deleting FROMLINKS on the DestinationCard of a
	  changed FROMLINK.)



          (* * fgh 8/30/86 Converted to use NC.WithWrotePermission macro.)



          (* * rht 10/16/86: Changed NC.ProtectedCardOperation wrapper placement so that card deletion could still happen for
	  new cards.)



          (* * rg 3/3/87 Rewrote NC.ProtectedCardOperation wrapping)



          (* * rg 3/16/87 Now uses NC.DeleteNoteCard instead of NC.DeleteNoteCards)


    (LET (Window Card NewFromLinks ToLinks DeletedLinks Process TextObj MadeNewLinksP 
		 ChangedFromLinksP OldFromLinks OldToLinks)
         (SETQ Card (NC.CoerceToCard CardIdentifier))
         (NC.ProtectedCardOperation Card "Close w/o Saving" NIL (SETQ Window (NC.FetchWindow
					Card))
				    (SETQ ToLinks (NC.FetchToLinks Card))
				    (SETQ NewFromLinks (NC.FetchFromLinks Card))
				    (if (OR (NULL (OR (NC.CardDirtyP Card)
							      (NC.FetchLinksDirtyFlg Card)
							      (NC.FetchTitleDirtyFlg Card)
							      (NC.FetchPropListDirtyFlg Card)))
						(NC.AskYesOrNo 
						   "Are you sure you want to flush your changes?"
								 " -- " "Yes" T Window NIL NIL))
					then

          (* * EIther no changes have been made or the user has confirmed.)


					 (if (EQ (fetch (Card Status) of Card)
						     (QUOTE ACTIVE))
					     then          (* Read old card parts off notefile.)
					      (NC.GetNoteCard Card) 
                                                             (* If from links have changed then we'll have to write
							     the new ones out.)
					      (SETQ OldFromLinks (NC.FetchFromLinks Card))
					      (if (NOT (NC.SameLinksP NewFromLinks OldFromLinks)
							   )
						  then (NC.SetFromLinks Card NewFromLinks)
							 (SETQ ChangedFromLinksP T))
                                                             (* Delete the back links from all links that are not 
							     in the old to link set.)
					      (SETQ OldToLinks (NC.FetchToLinks Card))
					      [for ToLink in ToLinks
						 unless (for Link in OldToLinks
							     eachtime (BLOCK)
							     thereis (NC.SameLinkP Link ToLink))
						 do (LET ((DestinationCard (fetch (Link 
										  DestinationCard)
										of ToLink)))
                                                             (* Grab the writelock on the FROMLINKS before trying 
							     to write out the change.)
						           (NC.WithWritePermission DestinationCard
										   (QUOTE FROMLINKS)
										   (NC.DelFromLink
										     ToLink)
										   (SETQ 
										    MadeNewLinksP T]
                                                             (* Check to make sure none of the old To links point 
							     to a deleted card. If so, replace with a deleted 
							     marker.)
					      (SETQ DeletedLinks
						(bind DestinationCard for Link in OldToLinks
						   eachtime (BLOCK)
						   when [PROGN (SETQ DestinationCard
								     (fetch (Link DestinationCard)
									of Link))
								   (AND (NOT (NC.ActiveCardP
										   DestinationCard))
									  (EQ (QUOTE DELETED)
										(NC.FetchStatus
										  DestinationCard]
						   collect (NC.DelReferencesToCard Card 
										  DestinationCard)
							     Link))
					      (NC.SetToLinks Card (LDIFFERENCE OldToLinks 
										   DeletedLinks))
                                                             (* Mark links dirty if we had to delete any to links 
							     or if the from links changed.)
					      (NC.SetLinksDirtyFlg Card (OR DeletedLinks 
										ChangedFromLinksP))
                                                             (* Mark the substance dirty if had to delete any to 
							     links.)
					      (if DeletedLinks
						  then (NC.MarkCardDirty Card)
						else (NC.MarkCardDirty Card (QUOTE RESET)))
					      (NC.SetPropListDirtyFlg Card NIL)
					      (if (NC.FetchTitleDirtyFlg Card)
						  then 

          (* If we've changed title and any of the cards pointing to this one are up on the screen, then we need to update 
	  their images.)


							 (for FromLink in OldFromLinks
							    bind SourceCard eachtime (BLOCK)
							    when
							     (AND (NC.ActiveCardP
								      (SETQ SourceCard
									(fetch (Link SourceCard)
									   of FromLink)))
								    (WINDOWP (NC.FetchWindow
										 SourceCard)))
							    do (NC.UpdateLinkImages SourceCard 
											Card))
							 (NC.SetTitleDirtyFlg Card NIL))
					      (NC.QuitCard Card T)
					   else            (* If the card has never been written to the database 
							     quit w/o saving is equivalent to deleting the card.)
						  (NC.PrintMsg Window T 
								"This card has never been saved."
								 (CHARACTER 13)
								 
							  "It will be deleted from the database."
								 (CHARACTER 13))
						  (NC.DeleteNoteCard Card T])

(NC.UnfileNoteCard
  [LAMBDA (WindowOrTextStream)                               (* Randy.Gobbel " 2-Apr-87 15:38")
                                                             (* Take a notecard out of a file box.
							     Called fom title bar menu.)

          (* * fgh 11/12/85 Updated to handle Card objects.)



          (* * fgh 6/9/86 Added code to check to make sure that another operation is not in progress on this card when this 
	  fn is called.)



          (* * pmi 12/5/86: Modified message to NC.SelectNoteCards to mention SHIFT-selection.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 2/2/87: Fixed bug %#418: Trashed all the stuff about opening PropListEditor on the fromlinks.
	  Now just uses SelectNoteCards to choose the fileboxes to delete from.)



          (* * rg 3/4/87 rewritten for new NC.ProtectedCardOperation)



          (* * rg 3/18/87 added NC.CardSelectionOperation wrapper)



          (* * RG 4/2/87 changed NC.CardSelectionOperation to NCP.WithLockedCards)


    (DECLARE (GLOBALVARS NC.SelectingParentsMenu))
    (NCP.WithLockedCards (LET ((Card (NC.CoerceToCard WindowOrTextStream)))
			      (NC.ProtectedCardOperation
				Card "Unfile" NIL (LET* [(FromLinks (NC.FetchFromLinks Card))
							 (Parents (for FromLink in FromLinks
								     when
								      (FMEMB (fetch (Link Label)
										  of FromLink)
									       (QUOTE (FiledCard
											  SubBox)))
								     collect (fetch (Link 
										       SourceCard)
										  of FromLink]
						        (for Box
							   in (NC.SelectNoteCards
								  NIL
								  [FUNCTION (LAMBDA (Box)
								      (AND (NC.FileBoxP Box)
									     (FMEMB Box Parents]
								  NC.SelectingParentsMenu Card 
			  "Please shift-select the file box(es) from which to remove this card. ")
							   do (for FromLink in FromLinks
								   when (NC.SameCardP
									    Box
									    (fetch (Link SourceCard)
									       of FromLink))
								   do (NC.DeleteLink FromLink T])

(NC.CollectReferences
  [LAMBDA (Card CheckAndDeleteFlg ReturnLinkIconsFlg ReturnLocationsFlg)
                                                             (* fgh: " 5-Feb-86 19:54")

          (* * Collect all the links in a card specified by ID. RETURNS the CONS of a list of link identifiers {described 
	  below} and a dirtyflg that is non-NIL if the Substance of ID has been modified {i.e., when a non-valid link is 
	  found and CheckAndDeleteFlg is NIL}. IF CheckAndDeleteFlg is non-NIL checks for valid links and deletes those that 
	  are not valid. If ReturnLinkIconsFlg is NIL, returns link icons. Otherwise, returns links. If ReturnLinkIconsFlg is
	  NIL, returns just the links/link icons. Otherwise, returns the CONS of link/link icon and the type-specific 
	  location of the link icon in the card.)



          (* * fgh 11/12/85 Updated to handle Card objects.)



          (* * rht 12/19/85: Fixed to handle types with no CollectReferencesFn defined.)



          (* * fgh 2/5/86 Added call to NC.ApplyFn)


    (COND
      ((NC.ActiveCardP Card)
	(NC.ApplyFn CollectLinksFn Card CheckAndDeleteFlg ReturnLinkIconsFlg ReturnLocationsFlg))
      (T (NC.ReportError "NC.CollectReferences" (CONCAT "Attempt to call with inactive card:  " 
							    Card])

(NC.EditProperties
  [LAMBDA (TextStream)                                       (* Randy.Gobbel " 1-Apr-87 12:25")
                                                             (* Open a property list editor for the card 
							     corresponding to TextStream.
							     Called from Title bar menus.)

          (* * fgh 11/13/85 Updated to handle Card object.)



          (* * rht 4/11/86: No longer sticks dates and Updates in property list. Only user-defined stuff.)



          (* * kef 7/22/86: Added call to card's obtain write permission function for the PROPLIST.)



          (* * fgh 8/30/86 Converted APPLY* to NC.ApplyFn.)



          (* * rht 1/16/87: Now uses NC.SystemCardPropNames globalvar.)



          (* * rg 4/1/87 added NC.ProtectedCardOperation wrapper)


    (DECLARE (GLOBALVARS NC.SystemCardPropNames))
    (LET ((Card (NC.CoerceToCard (WINDOW.FROM.TEDIT.THING TextStream)))
	  PropList PropEditorWindow)
         (NC.ProtectedCardOperation Card "Edit Properties" NIL (SETQ PropList (NC.FetchPropList
					Card))
				    (COND
				      ((NC.ApplyFn ObtainWritePermissionFn Card (QUOTE PROPLIST))
					(WINDOWPROP (SETQ PropEditorWindow
							(NC.OpenPropListEditor
							  TextStream
							  (for SubList on PropList
							     by (CDDR SubList)
							     when (NOT (FMEMB (CAR SubList)
										    
									   NC.SystemCardPropNames))
							     join (LIST (CAR SubList)
									    (CADR SubList)))
							  "Edit Property List"))
						      (QUOTE ReleaseWritePermissionP)
						      T)
					PropEditorWindow)
				      (T (NC.CardPartBusy Card (QUOTE PROPLIST])

(NC.OpenPropListEditor
  [LAMBDA (WindowOrTextStream PropList Title ShowOnlyFlg MakeImageObjFlg ShowLinksFlg)
                                                             (* rht: "11-Dec-86 12:26")
                                                             (* Open a property list editor above the card 
							     specified by TextStream , which is either a TextStream
							     or a Window)

          (* * rht 8/11/86: Now takes ShowLinksFlg arg and passes to NC.PropListEditorOpenP so that we don't bail out if 
	  there's an open proplist not of our type.)



          (* * rht 11/13/86: Now hangs Card object off prop list editor's window so that we can get to the card from the 
	  proplist editor at close time.)



          (* * rht 12/11/86: Now only breaks out list if we're under ShowLinks.)


    (PROG ((Window (WINDOW.FROM.TEDIT.THING WindowOrTextStream))
	     (SystemProperties (QUOTE (ID Updates ItemDate LinksDate PropsDate TitleDate)))
	     EditWindow CardUID Card)                        (* Make sure there is no prop list editor already 
							     there)
	    (AND (NC.PropListEditorOpenP Window ShowLinksFlg)
		   (RETURN))
	    [SETQ CardUID (fetch (Card UID) of (SETQ Card (NC.CoerceToCard Window]
                                                             (* FOR each prop/value pair with LISTP value.
							     Make a series of individual prop/value pairs 
							     corresponding to the elements of the LISTP)
	    [SETQ PropList (for Item on PropList by (CDDR Item)
				join (COND
					 ((AND (LISTP (CADR Item))
						 (type? Link (CAADR Item)))
					   (for Element in (CADR Item)
					      collect (create PropListItem
								  PropertyName ← (CAR Item)
								  Value ← Element
								  OriginalListFlg ← T
								  AllowEditFlg ← NIL
								  AllowSelectFlg ← NIL
								  ButtonFn ← NIL)))
					 (T (LIST (create PropListItem
							      PropertyName ← (CAR Item)
							      Value ← (CADR Item)
							      OriginalListFlg ← NIL
							      AllowEditFlg ← NIL
							      AllowSelectFlg ← NIL
							      ButtonFn ← NIL]
                                                             (* If specified, translate all NOTECARDLINK values 
							     into Image Objects for display.)
	    [AND MakeImageObjFlg (for Item in PropList bind LinkIcon
				      when (type? Link (fetch (PropListItem Value)
							      of Item))
				      do (replace (PropListItem Value) of Item
					      with (SETQ LinkIcon (NC.MakeLinkIcon
							 (fetch (PropListItem Value) of Item)))
						     (IMAGEOBJPROP LinkIcon (QUOTE 
									     InsidePropListEditor)
								     T]
                                                             (* Indicate which properties can be edited by user.)
	    [for Item in PropList do (COND
					     ((FMEMB (fetch (PropListItem PropertyName)
							  of Item)
						       SystemProperties)
					       (replace (PropListItem AllowEditFlg) of Item
						  with T)
					       (replace (PropListItem AllowSelectFlg) of Item
						  with T))
					     (ShowOnlyFlg (replace (PropListItem AllowEditFlg)
							     of Item with NIL)
							  (replace (PropListItem AllowSelectFlg)
							     of Item with T))
					     (T (replace (PropListItem AllowEditFlg) of Item
						   with NIL)
						(replace (PropListItem AllowSelectFlg)
						   of Item with NIL]
                                                             (* Call the prop list editor)
	    (ATTACHWINDOW (SETQ EditWindow (CREATEW (CREATEREGION 1000 2000 100 100)
							  (OR Title "Edit Property List")
							  NIL T))
			    Window
			    (QUOTE TOP)
			    (QUOTE JUSTIFY)
			    (QUOTE LOCALCLOSE))
	    (WINDOWADDPROP EditWindow (QUOTE CLOSEFN)
			     (FUNCTION FREEATTACHEDWINDOW)
			     T)
	    (WINDOWPROP EditWindow (QUOTE PropListEditor)
			  (COND
			    (ShowOnlyFlg (QUOTE ShowOnly))
			    (T T)))
	    (WINDOWPROP EditWindow (QUOTE SavedCardObject)
			  Card)
	    (NC.EditPropList PropList EditWindow ShowOnlyFlg)
	    (RETURN EditWindow])

(NC.CardOrCardHolderFromUID
  [LAMBDA (CardUID NoteFileUID)                              (* kirk: "16-May-86 16:21")

          (* * Get the CardObject specified by CardUID and NoteFIleUID. This will have to be expanded a great deal when there
	  are crosslinked NFs.)



          (* * fgh 5/7/86 Added card holder notion. If NF does not exists send back a new card object holding just the given 
	  ID's)



          (* * kirk 16May86 fixed above to work if NoteFile exists but is closed)


    (LET (NoteFile)
         (if (AND (SETQ NoteFile (NC.NoteFileFromNoteFileUID NoteFileUID))
		      (NC.CardFromUID CardUID NoteFile))
	   else (create Card
			    UID ← CardUID
			    NoteFile ← NoteFileUID])
)
(* * changes to NCLINKS)

(DEFINEQ

(NC.TraverseLink
  [LAMBDA (LinkIcon Window)                                  (* Randy.Gobbel " 4-Nov-87 13:57")

          (* * Follow the link to the card at the other end. For now, amounts to editing the destination card.)



          (* * pmi&rht 6/19/87: Now checks for valid destination card before trying to edit it. Prints message to prompt 
	  window and changes link icon to "Deleted" if card is invalid.)



          (* * rg 11/4/87 calls NC.EditNoteCard w/ ReadOnly TRUE if NoteFile is read-only)


    (DECLARE (GLOBALVARS NC.MsgDelay))
    (LET ((Link (NC.FetchLinkFromLinkIcon LinkIcon))
	  (InterestedWindow (NC.CoerceToInterestedWindow (MAINWINDOW Window)))
	  Card OldTitle)
         (SETQ Card (fetch (Link DestinationCard) of Link))
         (if (NC.ValidCardP Card)
	     then (SETQ OldTitle (NC.RetrieveTitle Card))
		    (NC.EditNoteCard Card (fetch (NoteFile ReadOnlyFlg)
					       of (fetch (Card NoteFile) of Card)))

          (* * We're under TEdit, so if title was changed by EditFn, then be sure link icon gets redisplayed.)


		    (if (STREQUAL OldTitle (NC.RetrieveTitle Card))
			then (QUOTE DON'T)
		      else (QUOTE CHANGED))
	   else 

          (* * The link is bad -
	  tell the user and change it to "Deleted")


		  (NC.PrintMsg InterestedWindow T 
				 "This is a bad link - the destination card is invalid."
				 (CHARACTER 13))
		  (DISMISS NC.MsgDelay)
		  (NC.ClearMsg InterestedWindow T)
		  (NC.DeleteBadLink Link LinkIcon Window])

(NC.DeleteBadLink
  [LAMBDA (Link ImageObj ImageStream StreamType TextStream Scale)
                                                             (* pmi: "19-Jun-87 15:04")

          (* * pmi&rht 6/19/87: Deletes a bad link when it is discovered at display time. If the link icon being displayed is
	  in the Show Links window, then find its corresponding real link and delete it. Otherwise, just delete the link.)


    (LET (Card)
         (if (LISTGET (fetch (Link UserData) of Link)
			  (QUOTE InsidePropListEditor))
	     then (SETQ Card (fetch (Link SourceCard) of Link))
		    (for RealLink in (NC.FetchFromLinks Card) when (NC.SameLinkP RealLink 
											   Link)
		       do (NC.DeleteLink RealLink))
		    (for RealLink in (NC.FetchToLinks Card) when (NC.SameLinkP RealLink 
											 Link)
		       do (NC.DeleteLink RealLink))
		    (QUOTE DON'T)
	   else (NC.DeleteLink Link NIL T)
		  (NC.ReplaceWithDeletedLinkImageObj ImageObj)
		  (APPLY* (IMAGEOBJPROP ImageObj (QUOTE DISPLAYFN))
			    ImageObj ImageStream StreamType TextStream Scale)
		  (QUOTE CHANGED])

(NC.SameLinkP
  [LAMBDA (Link1 Link2)                                      (* rht: "15-Nov-85 15:45")
                                                             (* Compare two link UIDs)
    (NC.SameUIDP (fetch (Link UID) of Link1)
		   (fetch (Link UID) of Link2])

(NC.ValidLinkP
  [LAMBDA (Link)                                             (* rht: "27-May-87 12:13")
                                                             (* Check Link to see if it is a valid NOTECARDLINK, 
							     incvluding check that the NoteCard specified by 
							     DESTINATIONID is an active card.)

          (* * kirk 15Nov85: deleted use of DatabaseStream)



          (* * rht 7/18/86: Was actually reading in the destination card from notefile! No more.)



          (* * rht 5/27/87: Took out checks for valid source and destination cards.)


    (LET (DestinationCard)
         (AND (type? Link Link)
		(NEQ (fetch (Link UID) of Link)
		       -1])

(NC.DeleteLink
  [LAMBDA (Link NoOrphanHookFlg Don'tDelLinkIconFlg)         (* pmi: "19-Jun-87 10:33")

          (* * Delete a link with the option of not putting an orphan hook in case of last filing link.
	  Also option of not deleting link icon from the source card's substance.)



          (* * fgh 5/2/86 Included calls to NC.DelReferencesToCardFromShowLinks in order to clean up ShowLinks windows when 
	  links are deleted.)



          (* * kef 7/17/86: Added the requirement that the write permissions be obtained for the TOLINKS of the Source Card 
	  and the FROMLINKS of the Destination Card.)



          (* * kef 7/22/86: Puts the links for the Destination Card now right away while we are still holding onto the write 
	  lock for the FROMLINKS.)



          (* * kef 7/30/86: Modified to check for Client's concept of whether he owns the write lock or not, thus deciding 
	  whether or not to setup the release of the write lock afterwards.)



          (* * fgh 8/30/86 Adpated to use NC.IfCardPartNotBusy. Note use of ERROR!. Unfortunately, it appears that the only 
	  way to keep TEDIT from deleting the Link's Image Object is to bail out but good. The control structure here works 
	  because NC.IfCardPartNotBusy returns NIL if the CardPart is busy. The Ts at the end as the last SExpr in each call 
	  to NC.IfCardPartNotBusy insure that NC.IfCardPartNotBusy returns non-NIL otherwise.)



          (* * rht 9/29/86: Removed the call to NC.PutFromLinks. Looks to me like it'll get called anyway by NC.DelFromLink 
	  if necessary.)



          (* * rht 10/6/86: Delete crossfilelink cards when their links are deleted.)



          (* * rht 11/4/86: Now takes Don'tCreateDeletedImageObjFlg arg.)



          (* * rht 11/13/86: Undid my change of 11/4/86.)



          (* * rg 3/11/87 changed call of NC.DeleteNoteCard to NC.DeleteNoteCardInternal)



          (* * rht 3/13/87: Broke out code into the NC.DeleteFromLink and NC.DeleteToLink functions.)



          (* * rht 5/26/87: Changed to match reduced functionality of NC.ValidLinkP, now checks that DestinationCard and 
	  SourceCard are valid cards.)



          (* * rht 6/9/87: Slight modification of previous fix; moved check for valid source and destination card to be 
	  around the relevant calls to NC.DeleteFromLink and NC.DeleteToLink.)



          (* * pmi 6/19/87: Leave the check for valid source and destination card for NC.DeleteFromLink and NC.DeleteToLink.)


    (AND (NC.ValidLinkP Link)
	   (LET ((SourceCard (fetch (Link SourceCard) of Link))
		 (DestinationCard (fetch (Link DestinationCard) of Link)))
	        (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of SourceCard))
			      (OR (NC.IfCardPartNotBusy DestinationCard (QUOTE FROMLINKS)
							  (OR (NC.IfCardPartNotBusy
								  DestinationCard
								  (QUOTE TOLINKS)
								  (NC.DeleteFromLink Link 
										  NoOrphanHookFlg)
								  (NC.DeleteToLink Link 
									      Don'tDelLinkIconFlg)
								  (replace (Link UID) of Link
								     with -1)
								  T)
								(ERROR!))
							  T)
				    (ERROR!])

(NC.DeleteFromLink
  [LAMBDA (Link NoOrphanHookFlg)                             (* rht: "27-May-87 14:40")

          (* * This is part of what used to be the innards of NC.DeleteLink.)



          (* * rht 3/26/87: Changed to call NC.DeleteNoteCardInternal with QuietFlg on.)



          (* * rht 5/26/87: Changed to match reduced functionality of NC.ValidLinkP, now checks that DestinationCard is a 
	  valid card. Now calls NC.DeleteCrossFileLinkCard which tries to delete other end of cross-file link if that 
	  notefile is open.)


    (AND (NC.ValidLinkP Link)
	   (LET ((DestinationCard (fetch (Link DestinationCard) of Link)))
	        (AND (NC.ValidCardP DestinationCard)
		       (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of DestinationCard)
							)
				     (NC.DelFromLink Link NoOrphanHookFlg)
				     (NC.DelReferencesToCardFromShowLinks DestinationCard Link)

          (* * Delete cross file link cards when their links are deleted.)


				     (if (NC.CrossFileLinkCardP DestinationCard)
					 then (NC.DeleteCrossFileLinkCard DestinationCard])

(NC.DelFromLink
  [LAMBDA (Link NoOrphanHookFlg)                             (* Randy.Gobbel "15-Jul-87 18:21")

          (* * Delete a FromLink from its destination card Hook card to orphan if this is the last link.)



          (* * rht 11/15/84: Changed decision as to when to orphanize a card. Now must have deleted its last link 
	  (not just last subbox or filedcard link). Also checks that link doesn't point from card to itself.)



          (* * rht 12/1/84: Now doesn't do any work unless ID is valid, i.e. not DELETED or FREE.)



          (* * kirk: 13Nov85: deleted of use of DatabaseStream and changed to call CachedDelFromLink.)



          (* * kirk 29Jan86 Changed to a direct recursive call eliminating CachedDelFromLink. Added NC.FileInOrphanBox.)



          (* * rht 2/14/86: Now calls NC.UncacheLinks instead of two calls to NC.SetToLinks and NC.SetFromLinks.)



          (* * kef 7/30/86: Modified so that it only puts the FROMLINKS in the case of an inactiveP card.)



          (* * rg 5/8/87 check for active card should have been check for links cached ; fixed)



          (* * rg 7/15/87 now waits to call NC.PutFromLinks until after NC.FileInOrphanBox)


    (LET ((DestinationCard (fetch (Link DestinationCard) of Link)))
         (COND
	   ((NC.ValidCardP DestinationCard)
	     (COND
	       ((NC.LinksCachedP DestinationCard)
		 (NC.CachedDelFromLink Link DestinationCard)
		 (OR NoOrphanHookFlg (NC.FileInOrphanBox Link DestinationCard)))
	       (T (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of DestinationCard))
				(NC.GetLinks DestinationCard)
				(NC.CachedDelFromLink Link DestinationCard)
				(OR NoOrphanHookFlg (NC.FileInOrphanBox Link DestinationCard))
				(NC.PutFromLinks DestinationCard)
				(NC.UncacheLinks DestinationCard))
		  Link])

(NC.FileInOrphanBox
  [LAMBDA (Link DestinationCard)                             (* rht: "29-May-87 01:00")

          (* * Hook card to orphan if this is the last link.)



          (* * rht 7/4/86: Changed to call NC.FetchSpecialCards so that RegistryCard, etc. won't have to be filed somewhere.)



          (* * rg 11/18/86 Added globalvars declaration)



          (* * rht 4/20/87: Changed to work on new cards unless they're displayed on screen. Also removed reference to 
	  long-demised NC.OrphansID.)



          (* * rht 5/28/87: Now calls NC.CardNeedsFilingP, i.e. card should need filing before we gripe.)


    (LET ((SourceCard (fetch (Link SourceCard) of Link)))
         [AND (NC.CardNeedsFilingP DestinationCard)
		(NOT (NC.SameCardP SourceCard DestinationCard))
		(NOT (AND (NC.FetchNewCardFlg DestinationCard)
			      (NC.FetchWindow DestinationCard)))
		[NOT (NC.SameCardP SourceCard (fetch (NoteFile OrphansCard)
						     of (fetch (Card NoteFile) of SourceCard]
		(COND
		  ((OR (NULL (NC.FetchFromLinks DestinationCard))
			 (for FromLink in (NC.FetchFromLinks DestinationCard)
			    always (NC.SameCardP (fetch (Link SourceCard) of FromLink)
						     DestinationCard)))
		    (NC.PrintMsg NIL T "You have just removed the last link to " (NC.RetrieveTitle
				     DestinationCard)
				   "."
				   (CHARACTER 13)
				   "It is being filed in the Orphan FileBox.")
		    (NC.HookToOrphanCard DestinationCard))
		  ([for FromLink in (NC.FetchFromLinks DestinationCard)
		      never (FMEMB (fetch (Link Label) of FromLink)
				       (QUOTE (SubBox FiledCard]
		    (NC.PrintMsg NIL T "You have just unfiled " (NC.RetrieveTitle DestinationCard)
				   " from its last filebox."
				   (CHARACTER 13)
				   "It is being filed in the Orphan FileBox.")
		    (NC.HookToOrphanCard DestinationCard]
     Link])

(NC.HookToOrphanCard
  [LAMBDA (Card OrphansCard)                                 (* Randy.Gobbel "19-Feb-87 16:57")
                                                             (* The last reference to the card has just been 
							     deleted. Hook this card to the orphan card so it 
							     doesn't get lost forever)

          (* * kirk: 14Nov85: deleted use of DatabaseStream and changed EQs to NC.Same*Ps)



          (* * kef 7/29/86: Took out the calls to NC.PutMainCardData, NC.PutLinks, and NC.DeactivateCard after 
	  NC.MakeFilingLink. The reason is that this is done within NC.InsertLinkBeforeMarker or NC.InsertLinkInOrdering, 
	  which are called by NC.MakeFilingLink. Therefore, don't do this twice.)



          (* * rg 2/19/87 Return parent as value)


    (DECLARE (GLOBALVARS NC.FiledCardLinkLabel NC.SubBoxLinkLabel))
    (LET ((NoteFile (fetch (Card NoteFile) of Card)))
         (OR OrphansCard (SETQ OrphansCard (fetch (NoteFile OrphansCard) of NoteFile)))
         (COND
	   ((NC.ActiveCardP OrphansCard)
	     (COND
	       ((NC.MakeFilingLink OrphansCard Card (if (NC.FileBoxP Card T)
							  then NC.SubBoxLinkLabel
							else NC.FiledCardLinkLabel))
		 OrphansCard)))
	   (T (WITH.MONITOR (NC.FetchMonitor NoteFile)
			    (NC.GetNoteCard OrphansCard)   (* These no longer needed expressions used to go after
							     the NC.MakeFilingLink below: 
							     (NC.PutMainCardData OrphansCard) 
							     (NC.PutLinks OrphansCard) (NC.DeactivateCard 
							     OrphansCard))
			    (COND
			      ((NC.MakeFilingLink OrphansCard Card (if (NC.FileBoxP Card T)
									 then NC.SubBoxLinkLabel
								       else NC.FiledCardLinkLabel))
				OrphansCard])

(NC.MakeFilingLink
  [LAMBDA (SourceCard DestinationCard LinkType)              (* rht: "13-Oct-86 12:09")

          (* Make a link from FileBox to DestinationCard If card is a regular card, insert link at end of contents card.
	  If card is a supercontents of contents card then insert just before the subcontents marker 
	  (i.e., at end of super contents list). If card is a subcontents card then insert just before note cards marker 
	  (i.e., at end of subcontents list))



          (* * rht 10/25/85: Now checks if card's window is shrunken. If so, shrink it back at the end.)



          (* * kirk: 14Nov85: deleted use of of DatabaseStream)



          (* * fgh 11/15/85 Adapted from and intended to replace NC.MakeAContentsHook)



          (* * kirk 11Apr86 took out hard coded link display mode)



          (* * rht 10/13/86: Totally overhauled. Now calls NC.CachedMakeFilingLink which does both inserting before markers 
	  and inserting in ordering.)


    (if (NC.ActiveCardP SourceCard)
	then [NC.IfMultipleCardPartsNotBusy SourceCard (SUBSTANCE TOLINKS FROMLINKS GLOBALTOLINKS)
					      (LET ((ShrunkenFlg (NC.GetShrunkenWin SourceCard)))
					           (PROG1 (NC.CachedMakeFilingLink SourceCard 
										  DestinationCard 
										       LinkType)
							    (AND ShrunkenFlg (SHRINKW
								     (NC.FetchWindow SourceCard]
      else (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of SourceCard))
			   (NC.IfMultipleCardPartsNotBusy
			     SourceCard
			     (SUBSTANCE TOLINKS FROMLINKS GLOBALTOLINKS)
			     (if (NC.CardP (NC.GetNoteCard SourceCard))
				 then 

          (* * This next set of obtain write locks is only to make sure that we come out even when NC.DeactivateCard releases
	  the write locks. Note that the SourceCard will be deactivated upon exit of the RESETLST, as set up by the 
	  RESETSAVE.)


					(RESETSAVE (for CardPart
							in (QUOTE (SUBSTANCE TOLINKS 
										 GLOBALTOLINKS 
										 PROPLIST))
							do (APPLY* (fetch (Card 
									  ObtainWritePermissionFn)
									  of SourceCard)
								       SourceCard CardPart))
						     (BQUOTE (NC.DeactivateCard , SourceCard)))
					(PROG1 (NC.CachedMakeFilingLink SourceCard 
									    DestinationCard LinkType)
						 (NC.PutMainCardData SourceCard)
						 (NC.PutLinks SourceCard])

(NC.MakeLink
  [LAMBDA (Window LinkLabel DestinationCard SourceCard DisplayMode AnchorMode Message NoDisplayFlg 
		  LinkToInsertAfter CrossFileLinksMode)      (* rht: "28-May-87 13:39")

          (* * Make a link from (OR Window SourceCard) to DestinationCard with linklabel of LinkLabel)



          (* * rht 1/12/85: If need to create a new card, then now shows card type menu near window of SourceID.)



          (* * rht 1/13/85: Added extra args Message and NoDisplayFlg.)



          (* * rht 3/26/85: Added LinkToInsertAfter arg which should be NIL or a link to insert the new To link after.
	  If NIL, then insert at front of ToLinks.)



          (* * kirk 9/23/85: took out GETPROMPTWINDOW call for asknotecardtype)



          (* * kirk: 14Nov85: changed NC.CoerceToID to to NC.CoerceToCard)



          (* * fgh 11/16/85 Changed from PROG to LET and used COND to contyrol returnmed value.)



          (* * fgh 2/5/86 Changed call DefaultLinkDisplayMode to FetchLinkDisplayMode)



          (* * fgh 6/5/86 Now calls AskLinkLabel if LinkLabel arg is NIL)



          (* * rht 7/4/86: Added check for readonly card.)



          (* * kef 7/17/86: Added calls to grab the write permission on the appropriate card parts.)



          (* * kef 7/22/86: Saves the links on the Destination Card now right away, while still holding onto the FROMLINKS 
	  write lock.)



          (* * fgh 8/30/86 Adpated to use NC.IfCardPartNotBusy.)



          (* * rht 9/29/86: Tossed Ken's call to NC.PutFromLinks; It was the cause of too many nasty breaks.
	  Also made syntactic fixes.)



          (* * rht 10/4/86: Now handles cross file links. New arg CrossFileLinksMode determines whether cross-file link will 
	  be two-way, i.e. will destination card know it's being linked to.)



          (* * rht 11/10/86: Now creates new crossfile link if Destination card is a CrossFileLink card that we didn't just 
	  create.)



          (* * rht 11/14/86: Now checks if non-nil DestinationCard before trying to do cross-filelink stuff.)



          (* * pmi 12/5/86: Modified message to NC.SelectNoteCards to mention SHIFT-selection.)



          (* * rht 12/9/86: Throws out JustCreatedFlg marker stuff.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 12/16/86: Fixed bug whereby electing not to open notefile containing crossfilelink dest card caused 
	  break.)



          (* * rht 12/16/86: Now passes Window down to NC.GetCrossFileLinkDestCard.)



          (* * rg 3/18/87 added NCP.WithLockedCards wrapper)



          (* * rht 5/25/87: No longer tries to make two way cross-file links when dest notefile is open read-only.
	  Also assumes that CrossFileLinksMode is one of TWOWAY, ONEWAY or ASK. Now fills in the new 
	  RemoteCrossFileLinkCardUID field of cross file link cards.)


    (DECLARE (GLOBALVARS NC.SelectingSingleCardMenu NC.NewCrossFileLinksMode))
    (OR SourceCard (SETQ SourceCard (NC.CoerceToCard Window)))
    (AND
      (NC.CheckForNotReadOnly SourceCard Window "Can't make links in ")
      (NCP.WithLockedCards
	(LET (Link Type)
	     (OR Window (SETQ Window (NC.FetchWindow SourceCard)))
	     (OR Message (SETQ Message "Please shift-select the Card or Box to be linked to."))
	     (OR LinkLabel (SETQ LinkLabel (NC.AskLinkLabel Window NIL NIL T NIL)))
	     (OR DestinationCard (SETQ DestinationCard (NC.SelectNoteCards
		       T
		       [FUNCTION (LAMBDA (Card)
			   (COND
			     ((NOT (NC.SameCardP Card SourceCard))
			       T)
			     (T (NC.PrintMsg Window T "A Card/Box cannot link to itself. "
					       (CHARACTER 13)
					       "Selection ignored."
					       (CHARACTER 13))
				NIL]
		       NC.SelectingSingleCardMenu SourceCard Message)))
	     [if (EQ DestinationCard (QUOTE *New% Card*))
		 then (SETQ DestinationCard (AND (SETQ Type (NC.AskNoteCardType
							   (WINDOWREGION Window)))
						       (NC.CoerceToCard (NC.MakeNoteCard
									    Type
									    (fetch (Card NoteFile)
									       of SourceCard)
									    NIL NoDisplayFlg]

          (* * If we're trying to link to a CrossFileLink card, then check whether card was just created.
	  If so, then it's the first link, otherwise we make a new CrossFileLink.)


	     (AND DestinationCard (NC.CrossFileLinkCardP DestinationCard)
		    (SETQ DestinationCard (NC.GetCrossFileLinkDestCard DestinationCard Window))
		    (NC.SetUserDataProp DestinationCard (QUOTE JustCreatedFlg)
					  NIL))
	     (if DestinationCard
		 then
		  (NC.IfCardPartNotBusy
		    DestinationCard
		    (QUOTE FROMLINKS)
		    (NC.IfCardPartNotBusy
		      SourceCard
		      (QUOTE TOLINKS)

          (* * If have cross-file link, then make two new crossfilelink cards, one per notefile. Make global link over there 
	  from crossfilelink card to DestinationCard and local link here from SourceCard to crossfilelink card.)


		      [if (NOT (NC.SameNoteFileP (fetch (Card NoteFile) of SourceCard)
						       (fetch (Card NoteFile) of DestinationCard))
				   )
			  then (LET ([CrossFileLinksTwoWayFlg
					 (OR (EQ CrossFileLinksMode (QUOTE TWOWAY))
					       (AND (NULL CrossFileLinksMode)
						      (EQ NC.NewCrossFileLinksMode (QUOTE TWOWAY))
						      )
					       (AND [OR (EQ CrossFileLinksMode (QUOTE ASK))
							    (AND (NULL CrossFileLinksMode)
								   (EQ NC.NewCrossFileLinksMode
									 (QUOTE ASK]
						      (NC.AskCrossFileLinkMode DestinationCard 
										 Window]
				       RemoteSourceCard)
				      (if CrossFileLinksTwoWayFlg
					  then (AND (SETQ RemoteSourceCard
							  (NC.CreateCrossFileLinkCard 
										  DestinationCard 
										       SourceCard T))
							(NC.MakeGlobalLink Window LinkLabel 
									     DestinationCard 
									     RemoteSourceCard 
									     DisplayMode)))
				      (SETQ DestinationCard (NC.CreateCrossFileLinkCard 
										       SourceCard 
										  DestinationCard 
									  CrossFileLinksTwoWayFlg))
				      (if RemoteSourceCard
					  then             (* Make the two crossfile link cards know about each 
							     other's UIDs.)
						 (replace (CrossFileLinkSubstance 
								       RemoteCrossFileLinkCardUID)
						    of (NC.FetchSubstance RemoteSourceCard)
						    with (fetch (Card UID) of DestinationCard))
						 (replace (CrossFileLinkSubstance 
								       RemoteCrossFileLinkCardUID)
						    of (NC.FetchSubstance DestinationCard)
						    with (fetch (Card UID) of RemoteSourceCard]
		      [SETQ Link (create Link
					     UID ← (NC.MakeUID)
					     SourceCard ← SourceCard
					     DestinationCard ← DestinationCard
					     AnchorMode ← AnchorMode
					     Label ← LinkLabel
					     DisplayMode ← (OR DisplayMode (
								   NC.FetchLinkDisplayMode 
										       SourceCard]
		      (NC.AddToLink Link LinkToInsertAfter)
		      (NC.AddFromLink Link)
		      Link))
	       else NIL])

(NC.UpdateLinkImages
  [LAMBDA (SourceWindowOrCard DestinationCard)               (* fgh: " 5-Feb-86 20:01")

          (* * Update the Link Image Objects in SourceCard that point to DestinationID)



          (* * rht 10/2/85: Now checks if card's window was shrunk. If so, unshrink, modify and reshrink.)



          (* * fgh 11/17/85 Updated to handle card objects.)



          (* * fgh 2/5/86 Addeed call to NC.ApplyFn)


    (LET (SourceWindow SourceCard NoteCardType ShrunkenWin)
         (COND
	   ((WINDOWP SourceWindowOrCard)
	     (SETQ SourceWindow SourceWindowOrCard)
	     (SETQ SourceCard (NC.CoerceToCard SourceWindowOrCard)))
	   (T (SETQ SourceWindow (NC.FetchWindow SourceWindowOrCard))
	      (SETQ SourceCard SourceWindowOrCard)))
         (COND
	   ((SETQ ShrunkenWin (NC.GetShrunkenWin SourceWindow))
	     (EXPANDW ShrunkenWin)))
         (SETQ NoteCardType (NC.RetrieveType SourceCard))
         (NC.ApplyFn UpdateLinkIconsFn SourceCard DestinationCard)
         (COND
	   (ShrunkenWin (SHRINKW SourceWindow)))
     NIL])

(NC.UncacheLinks
  [LAMBDA (Card)                                             (* rht: "14-Feb-86 15:06")

          (* * Throw away the links cache for this card.)


    (replace (Card Links) of Card with NIL])

(NC.MakeFilingLinks
  [LAMBDA (Card Msg InterestedWindow)                        (* Randy.Gobbel " 2-Apr-87 15:38")
                                                             (* Hooks card specified by Card to all of the current 
							     contents cards by a Contents link)

          (* * rht 8/1/84: Changed the NC.PrintMsg2 call for "No FileBox has been specified." to use NIL as second arg rather
	  than T. This prevents erasure of previous error messages.)



          (* * rht 12/8/84: Massive rewrite. Now calls NC.MakeChildLink. And always orphanizes if no parent specified.
	  This is because it's currently called only by NC.InsureProperFiling.)



          (* * rht 6/25/85: Now returns NewParents and checks if CANCELLED comes back from NC.SelectNoteCards so can abort 
	  the calling operation.)



          (* * Fgh 11/15/85 Adapted from and intended to replace NC.MakeContentsHooks)



          (* * fgh 8/6/86 Updated to use NC.AttachPromptWindow and added Msg arg)



          (* * pmi 12/5/86: Modified message to NC.SelectNoteCards to mention SHIFT-selection.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rg 2/19/87 Make sure NewParents always has the real value)



          (* * rg 3/18/87 added NC.CardSelectionOperation wrapper)



          (* * rht 3/23/87: Changed so that message will fit on one less line.)



          (* * rht 3/23/87: Now takes InterestedWindow arg.)



          (* * Rht 3/24/87: Now calls NC.CoerceToInterestedWindow)



          (* * rht 3/26/87: No longer allows selection of boxes in foreign notefiles.)



          (* * rg 4/1/87 changed CANCELLED to DON'T)


    (DECLARE (GLOBALVARS NC.SelectingContentsMenu))
    (NCP.WithLockedCards (PROG ((NoteFile (fetch (Card NoteFile) of Card))
				  OneHook NewParents)
			         (OR InterestedWindow (SETQ InterestedWindow (
					   NC.CoerceToInterestedWindow Card)))
			         (SETQ NewParents (NC.SelectNoteCards
				     NIL
				     [FUNCTION (LAMBDA (SelectedCard)
					 (AND (NC.FileBoxP SelectedCard)
						(NC.SameNoteFileP NoteFile (fetch (Card NoteFile)
										of SelectedCard]
				     NC.SelectingContentsMenu Card (CONCAT (OR Msg "")
									     
						"('Done' with no selections files in ToBeFiled.)")
				     T))
			         [COND
				   ([NOT (OR (EQ NewParents (QUOTE DON'T))
						 (AND NewParents
							(for ParentCard in NewParents
							   bind OneHook
							   when (NC.MakeChildLink Card ParentCard 
										 InterestedWindow)
							   do (SETQ OneHook T)
							   finally (RETURN OneHook]
				     (NC.PrintMsg InterestedWindow NIL 
						    "No FileBox has been specified."
						    (CHARACTER 13)
						    "This card will be filed in the ToBeFiled Box."
						    (CHARACTER 13))
				     (SETQ NewParents (NC.HookToOrphanCard Card
									       (fetch (NoteFile
											  
										    ToBeFiledCard)
										  of NoteFile)))
				     (COND
				       ((NC.AttachPromptWindow InterestedWindow NIL NIL NIL T)
					 (SPAWN.MOUSE)
					 (DISMISS 2000)
					 (NC.ClearMsg InterestedWindow T]
			         (RETURN NewParents])

(NC.AddToLink
  [LAMBDA (Link LinkToInsertAfter BeingMovedFlg)             (* rht: "11-Aug-86 21:39")

          (* * Add Link to the ToLinks of the source card)



          (* * rht 3/26/85: Added LinkToInsertAfter arg which is either NIL, ATEND, or a link after which to insert new link.
	  If NIL, then insert at front of list. If ATEND then insert at end.)



          (* * kirk: 13Nov85: deleted second parameter (DatabaseSTream) and changed to call NC.CachedAddToLink.)



          (* * rht 2/14/86: Now calls NC.UncacheLinks instead of two calls to NC.SetToLinks and NC.SetFromLinks.)



          (* * rht 8/11/86: Added BeingMovedFlg. If non-nil, then delete instance of Link from ToLinks before inserting it in
	  new spot.)


    [LET ((SourceCard (fetch (Link SourceCard) of Link)))
         (COND
	   ((NC.ActiveCardP SourceCard)
	     (NC.CachedAddToLink Link SourceCard LinkToInsertAfter BeingMovedFlg))
	   (T (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of SourceCard))
			    (NC.GetLinks SourceCard)
			    (NC.CachedAddToLink Link SourceCard LinkToInsertAfter BeingMovedFlg)
			    (NC.PutLinks SourceCard)
			    (NC.UncacheLinks SourceCard]
    Link])

(NC.AddFromLink
  [LAMBDA (Link)                                             (* Randy.Gobbel "15-Jul-87 17:54")

          (* * Add Link to the FromLinks of the appropraite card on DatbaseStream)



          (* * kirk: 14Nov85: deleted use of of DatabaseStream)



          (* * rht 2/14/86: Now calls NC.UncacheLinks instead of two calls to NC.SetToLinks and NC.SetFromLinks.)



          (* * kef 7/22/86: Now only calls NC.PutFromLinks instead of NC.PutLinks because we can't be certain of owning the 
	  write locks on all of the Link parts.)



          (* * rg 5/15/87 now calls NC.LinksCachedP instead of NC.ActiveCardP)


    (LET ((Card (fetch (Link DestinationCard) of Link)))
         [COND
	   ((NC.LinksCachedP Card)
	     (NC.SetFromLinks Card (CONS Link (NC.FetchFromLinks Card)))
	     (NC.SetLinksDirtyFlg Card T))
	   (T (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
			    (NC.GetLinks Card)
			    (NC.SetFromLinks Card (CONS Link (NC.FetchFromLinks Card)))
			    (NC.PutFromLinks Card)
			    (NC.UncacheLinks Card]
     Link])

(NC.DelToLink
  [LAMBDA (Link)                                             (* Randy.Gobbel "15-May-87 16:54")

          (* * Delete ToLink spoecified by Link from cards on DatabasseStream)



          (* * rht 12/1/84: Now doesn't do any work unless SourceCard is valid, i.e. not DELETED or FREE.)



          (* * kirk: 13Nov85: changed to use NoteFile from card from link instead of DatabaseStream)



          (* * rht 2/14/86: Now calls NC.UncacheLinks instead of two calls to NC.SetToLinks and NC.SetFromLinks.)



          (* * rg 5/15/87 now calls NC.LinksCachedP instead of NC.ActiveCardP)


    (PROG ((SourceCard (fetch (Link SourceCard) of Link)))
	    (COND
	      ((NOT (NC.ValidCardP SourceCard)))
	      ((NC.LinksCachedP SourceCard)
		(NC.SetToLinks SourceCard (DREMOVE (for OldLink in (NC.FetchToLinks 
										       SourceCard)
							  thereis (AND (NC.SameLinkP Link 
											  OldLink)
									   OldLink))
						       (NC.FetchToLinks SourceCard)))
		(NC.SetLinksDirtyFlg SourceCard T))
	      (T (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of SourceCard)
						  "NC.AddFromLink")
			       (NC.GetLinks SourceCard)
			       (NC.SetToLinks SourceCard (DREMOVE (for OldLink
									 in (NC.FetchToLinks
										SourceCard)
									 thereis
									  (AND (NC.SameLinkP
										   Link OldLink)
										 OldLink))
								      (NC.FetchToLinks SourceCard)))
			       (NC.SetLinksDirtyFlg SourceCard T)
			       (NC.PutLinks SourceCard))
		 (NC.UncacheLinks SourceCard)))
	    (RETURN Link])

(NC.DelReferencesToCard
  [LAMBDA (SourceCard LinkOrDestinationCard Don'tCreateDeletedImageObjFlg)
                                                             (* rht: " 9-Jun-87 18:16")
                                                             (* The card specified by DestinationID is being 
							     deleted. Remove all references to it from the card 
							     specified by SourceCard)

          (* * kirk: 13Nov85: deleted use of DatabaseStream)



          (* * fgh 2/5/86 Added call to NC.ApplyFn)



          (* * kef 7/31/86: Added wrapping of write lock grabbing so that deactivating the card preserves the nesting of 
	  write lock ownership.)



          (* * kef 8/5/86: Added putting of Main Card data in ActiveP case. This is so that if subsequent other people bring 
	  up the card, they will see the fact that link card was deleted.)



          (* * kef 8/7/86: Now requires that the card is being edited rather than just Active to thwart direct write through 
	  to NoteFile.)



          (* * rht 8/11/86 Added ShrunkenFlg so that SourceCard is reshrunk afterwards if necessary.)



          (* * fgh 8/30/86 Changed APPLY* to NC.ApplyFn. Appears there might be trouble here since we don't appear to wait if
	  we can't get all the write permission locks. I am assuming for now that this is being taken care of at a higher 
	  level.)



          (* * rht 9/19/86: It was testing NC.BeingEditedP to decide whether had to obtain write permission, etc. I think 
	  NC.ActiveCardP is enough. NC.BeingEditedP is bogus anyway as it doesn't work on card's whose editors don't have 
	  processes like graph cards.)



          (* * rht 11/4/86: Now takes Don'tCreateDeletedImageObjFlg arg.)



          (* * rht 3/19/87: Undo Ken's server-related fix of 8/5/86, i.e. ripped out call to NC.PutMainCardData when card is 
	  active.)



          (* * rht 6/9/87: Now marks card dirty after calling DeleteLinksFn.)


    (LET ((ShrunkenFlg (NC.GetShrunkenWin SourceCard))
	  NoteCardType Substance)
         [COND
	   ((NC.ActiveCardP SourceCard)
	     (SETQ NoteCardType (NC.RetrieveType SourceCard))
	     (SETQ Substance (NC.FetchSubstance SourceCard))
	     (NC.ApplyFn DeleteLinksFn SourceCard LinkOrDestinationCard Don'tCreateDeletedImageObjFlg)
	     (NC.MarkCardDirty SourceCard))
	   (T (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of SourceCard))
			    (if (NC.ValidCardP (NC.GetNoteCard SourceCard))
				then (RESETLST (RESETSAVE (for CardPart
								   in (QUOTE (SUBSTANCE TOLINKS 
										    GLOBALTOLINKS 
											 PROPLIST))
								   do (NC.ApplyFn 
									  ObtainWritePermissionFn 
										    SourceCard 
										    CardPart))
								(BQUOTE (NC.DeactivateCard , 
										       SourceCard)))
						   (SETQ NoteCardType (NC.RetrieveType SourceCard)
						     )
						   (SETQ Substance (NC.FetchSubstance SourceCard))
						   (NC.ApplyFn DeleteLinksFn SourceCard 
							       LinkOrDestinationCard 
							       Don'tCreateDeletedImageObjFlg)
						   (NC.PutMainCardData SourceCard]
         (NC.DelReferencesToCardFromGlobalList SourceCard LinkOrDestinationCard)
         (AND ShrunkenFlg (SHRINKW (NC.FetchWindow SourceCard])

(NC.DelReferencesToCardFromGlobalList
  [LAMBDA (SourceCard LinkOrDestinationCard)                 (* rht: " 5-Jun-87 14:56")

          (* * LinkOrDestinationCard is being deleted. Remove all references to it from the global links list of SourceCard)



          (* * rht 11/19/84: Fixed a naming typo changing ID to SourceCard everywhere. Also fixed DestinationID arg to be 
	  LinkOrDestinationID.)



          (* * kirk: 14Nov85: deleted use of of DatabaseStream and LinkID and changed EQs to NC.Same*Ps)



          (* * rg 5/15/87 now calls NC.LinksCachedP instead of NC.ActiveCardP)



          (* * rht&pmi 6/5/87: Added call to NC.UncacheLinks.)


    (COND
      ((NC.LinksCachedP SourceCard)
	(NC.SetGlobalLinks SourceCard (for Link in (NC.FetchGlobalLinks SourceCard)
					   when (if (NC.CardP LinkOrDestinationCard)
						      then (NOT (NC.SameCardP
								      LinkOrDestinationCard
								      (fetch (Link DestinationCard)
									 of Link)))
						    else (NOT (NC.SameLinkP 
									    LinkOrDestinationCard 
										  Link)))
					   collect Link)))
      (T (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of SourceCard))
		       (NC.GetLinks SourceCard)
		       (NC.SetGlobalLinks SourceCard
					    (for Link in (NC.FetchGlobalLinks SourceCard)
					       when (if (NC.CardP LinkOrDestinationCard)
							  then (NOT (NC.SameCardP
									  LinkOrDestinationCard
									  (fetch (Link 
										  DestinationCard)
									     of Link)))
							else (NOT (NC.SameLinkP 
									    LinkOrDestinationCard 
										      Link)))
					       collect Link))
		       (NC.PutLinks SourceCard)
		       (NC.UncacheLinks SourceCard])

(NC.DeleteToLink
  [LAMBDA (Link Don'tDelLinkIconFlg)                         (* rht: "27-May-87 14:40")

          (* * This is part of what used to be the innards of NC.DeleteLink.)



          (* * rht 3/26/87: Changed to call NC.DeleteNoteCardInternal with QuietFlg on.)



          (* * rht 5/27/87: Changed to match reduced functionality of NC.ValidLinkP, now checks that SourceCard is valid 
	  card. Now calls NC.DeleteCrossFileLinkCard which tries to delete other end of cross-file link if that notefile is 
	  open.)


    (AND (NC.ValidLinkP Link)
	   (LET ((SourceCard (fetch (Link SourceCard) of Link)))
	        (AND (NC.ValidCardP SourceCard)
		       (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of SourceCard))
				     (OR Don'tDelLinkIconFlg (NC.DelReferencesToCard SourceCard 
											 Link))
				     (NC.DelToLink Link)
				     (NC.DelReferencesToCardFromShowLinks SourceCard Link)

          (* * Delete cross file link cards when their links are deleted.)


				     (if (NC.CrossFileLinkCardP SourceCard)
					 then (NC.DeleteCrossFileLinkCard SourceCard])

(NC.ChangeLinkDisplayMode
  [LAMBDA (LinkOrLinkIcon Window NewDisplayMode)             (* Randy.Gobbel "15-May-87 16:39")

          (* * Change the display mode of the NOTECARDLINK defined by LinkOrLinkIcon. Have the user choose the new display 
	  mode.)



          (* * NOTE: assumes that the SourceID card of the link is active, i.e., the substance and links are cached for this 
	  card.)



          (* * rht 2/1/85: Now doesn't do all the work if new display mode is same as the old one. Or if user doesn't make a 
	  selection from the menu.)



          (* * kef 8/8/86: Now does the write through to the NoteFile even if the card is active, but not being edited.
	  Also, in the case of doing the write through, puts only the from links.)



          (* * fgh 8/30/86 Adapted to call NC.IfCardPartNotBusy.)



          (* * rht 9/29/86: Changed Ken's call to NC.CardBeingEditedP to NC.ActiveCardP and other minor changes.)



          (* * rht 2/18/87: Added check for readonly notefile to fix bug %#376.0)



          (* * rg 5/15/87 now calls NC.LinksCachedP instead of NC.ActiveCardP when changing FromLinks)


    (LET (Card DestinationCard Link LinkIcon GlobalLinkFlg OldDisplayMode)
         [if (NC.LinkIconImageObjP LinkOrLinkIcon)
	     then (SETQ Link (NC.FetchLinkFromLinkIcon LinkOrLinkIcon))
		    (SETQ LinkIcon LinkOrLinkIcon)
	   else (SETQ Link LinkOrLinkIcon)
		  (OR (SETQ GlobalLinkFlg (NC.GlobalLinkP Link))
			(SETQ LinkIcon (NC.FetchLinkIconForLink Link]
         (SETQ Card (fetch (Link SourceCard) of Link))
         (SETQ OldDisplayMode (fetch (Link DisplayMode) of Link))
         (if (NC.CheckForNotReadOnly Card Window "Can't change display mode for links in ")
	     then [COND
		      ((WINDOWP Window))
		      ((NC.ActiveCardP Card)
			(SETQ Window (NC.FetchWindow Card]

          (* * Get new display mode from user)


		    (SETQ DestinationCard (fetch (Link DestinationCard) of Link))
		    (NC.IfCardPartNotBusy
		      DestinationCard
		      (QUOTE FROMLINKS)
		      [if (NOT NewDisplayMode)
			  then (SETQ NewDisplayMode
				   (NC.DisplayModeFromStylesheetSelections
				     (STYLESHEET (CREATE.STYLE (QUOTE ITEMS)
								   [LIST
								     (create MENU
									       ITEMS ←
									       (QUOTE (Yes No Float)
											))
								     (create MENU
									       ITEMS ←
									       (QUOTE (Yes No Float)
											))
								     (create MENU
									       ITEMS ←
									       (QUOTE (Yes No Float]
								   (QUOTE ITEM.TITLES)
								   (QUOTE (Title?%  LinkType?%  
										    AttachBitmap?))
								   (QUOTE ITEM.TITLE.FONT)
								   (FONTCOPY MENUFONT (QUOTE
										 WEIGHT)
									       (QUOTE BOLD))
								   (QUOTE SELECTIONS)
								   (
							   NC.StylesheetSelectionsFromDisplayMode
								     OldDisplayMode)
								   (QUOTE NEED.NOT.FILL.IN)
								   NIL
								   (QUOTE TITLE)
								   (QUOTE Display% Mode?)
								   (QUOTE POSITION)
								   (create POSITION
									     XCOORD ← LASTMOUSEX
									     YCOORD ← LASTMOUSEY]
		      (if (OR (NULL NewDisplayMode)
				  (EQUAL NewDisplayMode OldDisplayMode))
			  then 

          (* * If new display mode is same as old, then bail out.)


				 NIL
			else 

          (* * Update link in LinkIcon or in global links list)


			       (if GlobalLinkFlg
				   then (for GlobalLink in (NC.FetchGlobalLinks Card)
					     when (NC.SameLinkP Link GlobalLink)
					     do (replace (Link DisplayMode) of GlobalLink
						     with NewDisplayMode))
					  (NC.SetLinksDirtyFlg Card T)
				 else (replace (Link DisplayMode) of (NC.FetchLinkFromLinkIcon
									     LinkIcon)
					   with NewDisplayMode)
					(NC.MarkCardDirty Card))

          (* * Update link in ToLinks List of Source card)


			       (for ToLink in (NC.FetchToLinks Card) when (NC.SameLinkP
										    Link ToLink)
				  do (replace (Link DisplayMode) of ToLink with 
										   NewDisplayMode))
			       (NC.SetLinksDirtyFlg Card T) 

          (* * Update Link in FromLinks list of Destination card)


			       (if (NC.LinksCachedP DestinationCard)
				   then (for FromLink in (NC.FetchFromLinks DestinationCard)
					     when (NC.SameLinkP Link FromLink)
					     do (replace (Link DisplayMode) of FromLink
						     with NewDisplayMode))
					  (NC.SetLinksDirtyFlg DestinationCard T)
				 else (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile)
									    of DestinationCard))
						      (NC.GetLinks DestinationCard)
						      (for FromLink in (NC.FetchFromLinks
									     DestinationCard)
							 when (NC.SameLinkP Link FromLink)
							 do (replace (Link DisplayMode)
								 of FromLink with NewDisplayMode))
						      (NC.PutFromLinks DestinationCard)
						      (NC.UncacheLinks DestinationCard)))

          (* * Update the image in any active window for Card)


			       (if [AND (WINDOWP Window)
					    (NOT (NC.TEditBasedP (NC.RetrieveType Card]
				   then (NC.UpdateLinkImages Window (fetch (Link 
										  DestinationCard)
									   of Link)))
                                                             (* This causes tedit to redisplay the screen.)
			       (QUOTE CHANGED])

(NC.FetchLinkIconForLink
  [LAMBDA (Link)                                             (* fgh: " 5-Feb-86 19:52")

          (* * Find the Link Icon corresponding to Link)



          (* * kirk 14Nov85: deleted use of LinkID and PSA.Database)



          (* * fgh 2/5/86 Added call to NC.ApplyFn)


    (LET ((SourceCard (fetch (Link SourceCard) of Link)))
         (for LinkIcon in (CAR (NC.ApplyFn CollectLinksFn SourceCard NIL T))
	    thereis (if (NC.SameLinkP Link (NC.FetchLinkFromLinkIcon LinkIcon))
			  then LinkIcon])

(NC.RelabelLink
  [LAMBDA (LinkOrLinkIcon Window NewLinkLabel ForceRedisplayFlg)
                                                             (* pmi: "11-Sep-87 21:39" pp pp)
                                                             (* Relabel a NoteCard link.
							     Ask user for new label. Update all the proper 
							     references to this link.)

          (* * rht 11/19/84: Fixed so that Card is defined before first use.)



          (* * kirk 14Nov85: deleted use of and LinkID)



          (* * kef 8/8/86: Added obtaining write lock and NC.PutFromLinks.)



          (* * fgh 8/30/86 Adapted to NC.IfCardPartNotBusy)



          (* * rht 9/29/86: Changed Ken's call to NC.CardBeingEditedP to NC.ActiveCardP and other minor mod's.)



          (* * rg 5/15/87 now calls NC.LinksCachedP instead of NC.ActiveCardP)



          (* * rht 5/27/87: Now passes new label through cross file link if its dest notefile is open.)



          (* * pmi 9/11/87: Fixes bug 692 -
	  can no longer change link label when notefile is open read-only.)


    (LET (Link LinkIcon Card DestinationCard OldLabel NoteCardType GlobalLinkFlg)
         [if (NC.LinkIconImageObjP LinkOrLinkIcon)
	     then (SETQ Link (NC.FetchLinkFromLinkIcon LinkOrLinkIcon))
		    (SETQ LinkIcon LinkOrLinkIcon)
	   else (SETQ Link LinkOrLinkIcon)
		  (OR (SETQ GlobalLinkFlg (NC.GlobalLinkP Link))
			(SETQ LinkIcon (NC.FetchLinkIconForLink Link]
         (SETQ Card (fetch (Link SourceCard) of Link))
         (if (NC.CheckForNotReadOnly Card Window "Can't change link type of links in ")
	     then [COND
		      ((WINDOWP Window))
		      ((NC.ActiveCardP Card)
			(SETQ Window (NC.FetchWindow Card]
		    (SETQ DestinationCard (fetch (Link DestinationCard) of Link))
		    (NC.IfCardPartNotBusy DestinationCard (QUOTE FROMLINKS)
					  (COND
					    ((NC.SystemLinkLabelP (fetch (Link Label)
								       of Link))
					      (NC.PrintMsg Window T 
							   "This is a system maintained pointer."
							     (CHARACTER 13)
							     "You cannot change its label."
							     (CHARACTER 13))
					      (SPAWN.MOUSE)
					      (DISMISS 1500)
					      (NC.ClearMsg Window T))
					    ((SETQ NewLinkLabel
						(OR NewLinkLabel (NC.AskLinkLabel Window NIL NIL 
										      T T)))
					      (SETQ NoteCardType (NC.RetrieveType Card))

          (* * Put new label in Link Icon or global links list)


					      (if GlobalLinkFlg
						  then (for GlobalLink in (NC.FetchGlobalLinks
										  Card)
							    when (NC.SameLinkP GlobalLink Link)
							    do (replace (Link Label)
								    of GlobalLink with 
										     NewLinkLabel)
								 (NC.SetLinksDirtyFlg Card T)
								 (RETURN))
						else (replace (Link Label) of (
									 NC.FetchLinkFromLinkIcon
										      LinkIcon)
							  with NewLinkLabel)
						       (NC.MarkCardDirty Card))

          (* * Update ToLink list of the SourceCard card)


					      (for ToLink in (NC.FetchToLinks Card)
						 when (NC.SameLinkP ToLink Link)
						 do (replace (Link Label) of ToLink
							 with NewLinkLabel)
						      (NC.SetLinksDirtyFlg Card T)
						      (RETURN))

          (* * Update FromLink list of DestinationCard card)


					      (if (NC.LinksCachedP DestinationCard)
						  then (for FromLink in (NC.FetchFromLinks
										DestinationCard)
							    when (NC.SameLinkP FromLink Link)
							    do (replace (Link Label)
								    of FromLink with NewLinkLabel)
								 (NC.SetLinksDirtyFlg 
										  DestinationCard T)
								 (RETURN))
						else (WITH.MONITOR (NC.FetchMonitor
								       (fetch (Card NoteFile)
									  of DestinationCard))
								     (NC.GetLinks DestinationCard)
								     (for FromLink
									in (NC.FetchFromLinks
									       DestinationCard)
									when (NC.SameLinkP 
											 FromLink 
											     Link)
									do (replace (Link Label)
										of FromLink
										with NewLinkLabel)
									     (NC.SetLinksDirtyFlg
									       DestinationCard T)
									     (RETURN))
								     (NC.PutFromLinks 
										  DestinationCard)
								     (NC.UncacheLinks 
										  DestinationCard)))

          (* * Pass change through cross-file link to other notefile if open.)


					      [if (NC.CrossFileLinkCardP Card)
						  then (LET ((RemoteCrossFileLinkCard (
								  NC.FetchRemoteCrossFileLinkCard
											  Card)))
							      (AND RemoteCrossFileLinkCard
								     (NC.CheckCrossFileLinkType
								       RemoteCrossFileLinkCard Card 
								       Link]
					      [if (NC.CrossFileLinkCardP DestinationCard)
						  then (LET ((RemoteCrossFileLinkCard (
								  NC.FetchRemoteCrossFileLinkCard
											  
										  DestinationCard)))
							      (AND RemoteCrossFileLinkCard
								     (NC.CheckCrossFileLinkType
								       RemoteCrossFileLinkCard 
								       DestinationCard Link]

          (* * Update images in SourceCard window)


					      (COND
						((AND (NULL ForceRedisplayFlg)
							(NC.TEditBasedP NoteCardType))
						  (QUOTE CHANGED))
						((WINDOWP Window)
						  (NC.UpdateLinkImages Window (fetch
									   (Link DestinationCard)
										   of Link))
						  NIL)
						(T NIL])

(NC.ChangeCardTitleFromLinkIcon
  [LAMBDA (LinkIcon Window)                                  (* rht: "18-Feb-87 11:34")

          (* * From a link icon sitting in Window, change the title of the link's destination card.)



          (* * kirk 14Nov85: deleted use of PSA.Database)



          (* * fgh 6/4/86 Fixed so that moves card back to original location if moved to be on screen.
	  This fixes a bug in TEdit that'll mess up the screen if a window is mived under a ImageObj ButtonEventInFn.)



          (* * kef 7/16/86: Added mechanism for grabbing the write permission on the TITLE of the destination card.)



          (* * kef 7/30/86: Modified to check for Client's concept of whether he owns the write lock or not, thus deciding 
	  whether or not to setup the release of the write lock afterwards.)



          (* * fgh 8/30/86 Adpated to use NC.IfCardPartNotBusy.)



          (* * rht 11/13/86: Now checks for crossfile links and bails out.)



          (* * rht 2/18/87: Added check for readonly notefile to fix bug %#376.0)


    (LET (Link Card DestinationCard OldTitle NewTitle)
         (RESETLST [RESETSAVE NIL (BQUOTE (MOVEW , Window , (LOWERLEFT (WINDOWPROP
										   Window
										   (QUOTE REGION]
		     (if (NC.LinkIconImageObjP LinkIcon)
			 then
			  (SETQ Link (NC.FetchLinkFromLinkIcon LinkIcon))
			  (SETQ Card (fetch (Link SourceCard) of Link))
			  (SETQ DestinationCard (fetch (Link DestinationCard) of Link))
			  (if (NC.CheckForNotReadOnly Card Window 
							  "Can't change titles for cards in ")
			      then
			       (if (NC.CrossFileLinkCardP DestinationCard)
				   then (NC.PrintMsg Window T 
					    "Can't change card title from a cross notefile link.")
					  (DISMISS 1500)
					  (NC.ClearMsg Window T)
					  NIL
				 else (NC.IfCardPartNotBusy
					  DestinationCard
					  (QUOTE TITLE)
					  (if (SETQ NewTitle
						  (NC.AskUser (CONCAT 
							  "Enter new title for card with title '"
									  (NC.RetrieveTitle 
										  DestinationCard)
									  "'"
									  (CHARACTER 13))
								"-->  "
								(if (AND (STREQUAL
									       (SETQ OldTitle
										 (NC.RetrieveTitle
										   DestinationCard))
									       "Untitled")
									     (NC.FetchNewCardFlg
									       DestinationCard))
								    then NIL
								  else OldTitle)
								T Window))
					      then (NC.AssignTitle DestinationCard NIL NewTitle)
						     (QUOTE CHANGED])

(NC.LinkIconWhenDeletedFn
  [LAMBDA (ImageObject Stream)                               (* rht: "26-Mar-87 19:10")

          (* * When deleting a link icon image object from a card, make sure the link information on the source and 
	  destinmation cards get updated. When deleting a link image object from a prop list editor, just inform the user 
	  that this is a useless operation.)



          (* * rht 11/19/84: Now handles the case when a move is in progress. True if the old link is cached on the ImageObj.
	  Also changed so that SourceID is computed from ImageObject rather than from Stream. Similarly for the window.)



          (* * kirk 14Nov85: deleted use of PSA.Database)



          (* * fgh 5/2/86 Added code to handle deleting of links from ShowLinks editors.)



          (* * fgh 6/4/86 Added KLUDGE to take care of case when this is called under TEDIT.UNDO.MOVE)



          (* * rht 7/4/86: Now checks for readonly cards. Also passes checks for deleting from orphan card when calling 
	  NC.DeleteLink.)



          (* * fgh 7/14/86 Now deletes link icon directly, rather than depending on DeleteLink to do it.
	  Sets the Don'tDeleteLinkIconFlg in the call to DeleteLink to do so.)



          (* * rht 8/11/86: Now computes InsideShowLinksP and lets that determine value of Don'tDelLinkIcon flg in call to 
	  NC.DeleteLink.)



          (* * rht&pmi 12/8/86: Now checks whether we're called by TEDIT.MOVE. If so, don't cause orphan hook under 
	  NC.DelFromLink.)



          (* * rht 3/26/87: Now passes non-nil NoOrphanHookFlg to NC.DeleteLink in case we're deleting a cross-file link.)


    (DECLARE (GLOBALVARS NC.DeletedLinkImageObject))
    (LET ((Link (NC.FetchLinkFromLinkIcon ImageObject))
	  LinkType OldLink StkPtr SourceCard DestinationCard InsideShowLinksP)
         (COND
	   [(NC.CheckForNotReadOnly (fetch (Link SourceCard) of Link)
				      NIL "Can't delete links in ")
	     (COND
	       ((IMAGEOBJPROP ImageObject (QUOTE LinkBeingMovedWithinCard))
                                                             (* TEdit is trying to delete the old link imageobj 
							     after moving within a card.)
		 (IMAGEOBJPROP ImageObject (QUOTE LinkBeingMovedWithinCard)
				 NIL))
	       ((SETQ OldLink (IMAGEOBJPROP ImageObject (QUOTE LinkBeingMoved)))
                                                             (* Pass non-nil NoOrphanHookFlg arg to NC.DelFromLink 
							     if we are under a TEDIT.MOVE call.)
		 [NC.DelFromLink OldLink (RELSTK (STKPOS (QUOTE TEDIT.MOVE]
		 (NC.DelToLink OldLink)
		 (replace (Link UID) of OldLink with -1)
		 (IMAGEOBJPROP ImageObject (QUOTE LinkBeingMoved)
				 NIL))
	       ((SETQ StkPtr (STKPOS (QUOTE TEDIT.UNDO.MOVE)))

          (* * Called from TEDIT.UNDO.MOVE, don't relly want to delete the links. KLUDGE because TEDIT will not call the 
	  LinkIconInsertFn later on.)


		 (RELSTK StkPtr)
		 NIL)
	       (T 

          (* * if this is reversed source/dest {i.e., a From link} inside the show links editor, then return it to its 
	  original direction)


		  [COND
		    ((AND (SETQ InsideShowLinksP (IMAGEOBJPROP ImageObject (QUOTE 
									     InsidePropListEditor)))
			    (LISTGET (fetch (Link UserData) of Link)
				       (QUOTE Reversed)))
		      (SETQ Link (create Link using Link SourceCard ← (fetch (Link 
										  DestinationCard)
									       of Link)
							  DestinationCard ← (fetch (Link SourceCard)
									       of Link]

          (* * Then just delete the link)


		  (NC.CheckForOrphanDelete (SETQ SourceCard (fetch (Link SourceCard)
								   of Link))
					     (SETQ DestinationCard (fetch (Link DestinationCard)
									of Link)))
		  (NC.DeleteLink Link (OR (NC.SameCardP SourceCard (fetch (NoteFile 
										      OrphansCard)
									    of (fetch
										   (Card NoteFile)
										    of SourceCard)))
					      (NC.CrossFileLinkCardP DestinationCard)
					      (NC.CrossFileLinkCardP SourceCard))
				   (NOT InsideShowLinksP))
		  (create IMAGEOBJ smashing ImageObject OBJECTDATUM ← (fetch (IMAGEOBJ 
										      OBJECTDATUM)
									     of 
									NC.DeletedLinkImageObject)
						IMAGEOBJPLIST ← (fetch (IMAGEOBJ IMAGEOBJPLIST)
								   of NC.DeletedLinkImageObject)
						IMAGEOBJFNS ← (fetch (IMAGEOBJ IMAGEOBJFNS)
								 of NC.DeletedLinkImageObject))
		  (replace (Link UID) of Link with -1]
	   (T (ERROR!])

(NC.CheckForOrphanDelete
  [LAMBDA (SourceCard DestinationCard SourceWindow)          (* Randy.Gobbel "15-May-87 16:40")

          (* Check to make sure we are not deleteing the last reference to a note card from the orphan card.
	  Last references are okay to delete it since they will be put in the orphan card. But deleting last reference from 
	  the orphan card is very, very bad. Warn the user.)



          (* * kirk: 14Nov85: changed EQs to NC.Same*Ps)



          (* * rht 7/4/86: Brought up to date with 1.3k. E.g. took out mention of NC.OrphansID)



          (* * rg 5/15/87 now calls NC.LinksCachedP instead of NC.ActiveCardP)


    (LET [(FilingLinks (LIST NC.SubBoxLinkLabel NC.FiledCardLinkLabel))
	  (OrphansCard (fetch (NoteFile OrphansCard) of (fetch (Card NoteFile) of SourceCard]
         (AND (NC.SameCardP SourceCard OrphansCard)
		(for Link in (COND
				   ((NC.LinksCachedP DestinationCard)
				     (NC.FetchFromLinks DestinationCard))
				   (T (NC.GetLinks DestinationCard)
				      (NC.FetchFromLinks DestinationCard)))
		   when (FMEMB (fetch (Link Label) of Link)
				   FilingLinks)
		   unless (NC.SameCardP (fetch (Link SourceCard) of Link)
					    OrphansCard)
		   never Link)
		(NC.PrintMsg (NC.FetchWindow SourceCard)
			       T "You have just deleted the last filing link to " (NC.RetrieveTitle
				 DestinationCard)
			       (CHARACTER 13)
			       "The Search operation can be used to find it."])

(NC.InsertLinkBeforeMarker
  [LAMBDA (SourceCard DestinationCard LinkLabel DisplayMode Marker# NoSpacerFlg)
                                                             (* fgh: " 1-Sep-86 13:21")
                                                             (* Insert a link to DestinationCard in SourceCard just
							     before the Marker#'th place marker object)

          (* * rht 12/7/84: Now returns the newly created link.)



          (* * rht 9/13/85: When card is inactive, there won't be a current cursor position. So if no marker# is specified, 
	  then insert at end.)



          (* * kirk: 14Nov85: deleted use of of DatabaseStream)



          (* * kef 7/28/86: Added call to obtain write locks on SUBSTANCE and all LINKS in the case when the card is not 
	  NC.ActiveCardP.)



          (* * kef 7/31/86: Added "balancing" of write lock ownership with NC.DeactivateCard.)



          (* * kef 8/7/86: Now cached changes only occur if the card is currently being edited.)



          (* * fgh 8/30/86 Adpated to NC.IfCardPartsNotBusy)



          (* * fgh 9/1/86 Rescinded kef's change of 8/7/86. This causes active but nit visible cards to be written over even 
	  if they are dirty.)


    (LET (Objects TextStream TextObject (Spacer (CONCAT (CHARACTER 13)))
		  Link BusyPart)
         [COND
	   [(NC.ActiveCardP SourceCard)
	     (NC.IfMultipleCardPartsNotBusy SourceCard (SUBSTANCE TOLINKS FROMLINKS GLOBALTOLINKS)
					    [SETQ TextObject (TEXTOBJ (SETQ TextStream
									    (NC.FetchSubstance
									      SourceCard]
					    [COND
					      [[AND (FIXP Marker#)
						      (SETQ Objects (TEDIT.LIST.OF.OBJECTS
							  TextObject
							  (FUNCTION NC.PlaceMarkerP]
						(COND
						  ((EQ Marker# 0)
						    (TEDIT.SETSEL TextStream 1 0 (QUOTE LEFT)))
						  ((IGREATERP Marker# (FLENGTH Objects))
						    (TEDIT.SETSEL TextStream
								    (ADD1 (fetch (TEXTOBJ
										       TEXTLEN)
									       of TextObject))
								    0
								    (QUOTE RIGHT)))
						  (T (TEDIT.SETSEL TextStream
								     (CADAR (FNTH Objects Marker#)
									      )
								     0
								     (QUOTE LEFT]
					      (NC.MarkersInFileBoxesFlg (TEDIT.SETSEL TextStream
											(GETEOFPTR
											  TextStream)
											0
											(QUOTE
											  RIGHT]
					    (SETQ Link (NC.InsertLinkInText TextStream LinkLabel 
										DestinationCard 
										SourceCard 
										DisplayMode))
					    (COND
					      ((NULL NoSpacerFlg)
						(TEDIT.INSERT TextStream Spacer]
	   (T (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of SourceCard))
			    (NC.IfMultipleCardPartsNotBusy
			      SourceCard
			      (SUBSTANCE TOLINKS FROMLINKS GLOBALTOLINKS)
			      (COND
				((NC.CardP (NC.GetNoteCard SourceCard))

          (* * This next set of obtain write locks is only to make sure that we come out even when NC.DeactivateCard releases
	  the write locks. Note that the SourceCard will be deactivated upon exit of the RESETLST, as set up by the 
	  RESETSAVE.)


				  (RESETSAVE (for CardPart in (QUOTE (SUBSTANCE TOLINKS 
										    GLOBALTOLINKS 
											PROPLIST))
						  do (APPLY* (fetch (Card 
									  ObtainWritePermissionFn)
								    of SourceCard)
								 SourceCard CardPart))
					       (BQUOTE (NC.DeactivateCard , SourceCard)))
				  [SETQ TextObject (TEXTOBJ (SETQ TextStream (
								    NC.FetchSubstance SourceCard]
				  [COND
				    [[AND (FIXP Marker#)
					    (SETQ Objects (TEDIT.LIST.OF.OBJECTS
						TextObject
						(FUNCTION NC.PlaceMarkerP]
				      (COND
					((EQ Marker# 0)
					  (TEDIT.SETSEL TextStream 1 0 (QUOTE LEFT)))
					((IGREATERP Marker# (FLENGTH Objects))
					  (TEDIT.SETSEL TextStream (ADD1 (fetch (TEXTOBJ
											TEXTLEN)
										of TextObject))
							  0
							  (QUOTE RIGHT)))
					(T (TEDIT.SETSEL TextStream (CADAR (FNTH Objects 
										       Marker#))
							   0
							   (QUOTE LEFT]
				    (T                       (* Cursor has no position in closed Tedit win, so just
							     set selection to end.)
				       (TEDIT.SETSEL TextStream (ADD1 (fetch (TEXTOBJ TEXTLEN)
									     of TextObject))
						       0
						       (QUOTE RIGHT]
				  (SETQ Link (NC.InsertLinkInText TextStream LinkLabel 
								      DestinationCard SourceCard 
								      DisplayMode))
				  (COND
				    ((NULL NoSpacerFlg)
				      (TEDIT.INSERT TextStream Spacer)))
				  (NC.PutMainCardData SourceCard)
				  (NC.PutLinks SourceCard]
     Link])

(NC.AddGlobalLinksToCard
  [LAMBDA (CardIdentifier SingleLinkFlg)                     (* pmi: "21-May-87 15:42")

          (* * Called from card's menu to add some global links.)



          (* * rht 11/24/85: Fixed bugs. It was calling NC.CoerceToID.)



          (* * fgh 6/9/86 Added chack for other interaction operations already in progress.)



          (* * pmi 12/5/86: Modified message to NC.SelectNoteCards to mention SHIFT-selection.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation)



          (* * rg 3/18/87 added NC.CardSelectionOperation wrapper)



          (* * rg 3/31/87 fixed bug in NC.ProtectedCardOperation wrapper)



          (* * pmi 5/21/87: Changed NC.CardSelectionOperation to NCP.WithLockedCards)


    (NC.ProtectedCardOperation (NC.CoerceToCard CardIdentifier)
			       "Add Global Link(s)" NIL
			       (NCP.WithLockedCards
				 (LET (Window SourceCard DestinationCards Label)
				      (SETQ SourceCard (NC.CoerceToCard CardIdentifier))
				      (SETQ Window (NC.FetchWindow SourceCard))
				      (SETQ Label (NC.AskLinkLabel Window NIL NIL T T))
				      (AND Label
					     (if SingleLinkFlg
						 then (NC.MakeGlobalLink Window Label NIL 
									     SourceCard)
							(NC.ClearMsg Window T)
					       else (SETQ DestinationCards
							(NC.SelectNoteCards
							  NIL
							  [FUNCTION (LAMBDA (Card)
							      (COND
								((NEQ Card SourceCard)
								  T)
								(T (NC.PrintMsg Window T 
							    "A Card/Box cannot point to itself. "
										  (CHARACTER 13)
										  
									     "Selection ignored."
										  (CHARACTER 13))
								   NIL]
							  NC.SelectingMultipleCardsMenu SourceCard 
				       "Please shift-select the Cards or Boxes to be pointed to."))
						      (NC.ClearMsg Window T)
						      (for DestinationCard in DestinationCards
							 do (NC.MakeGlobalLink Window Label 
										  DestinationCard 
										   SourceCard])

(NC.AddLinkToCard
  [LAMBDA (CardIdentifier LinkOrLinkLabel DestinationCard)   (* Randy.Gobbel " 4-Mar-87 14:15")

          (* * Add a link to card designated by CardIdentifier. Rest of args can be NIL. Currently, this dispatches on card 
	  type. Should eventually call something like an InsertLinkFn.)



          (* * fgh 6/9/86 Added code to check to make sure that another operation is not in progress on this card when this 
	  fn is called.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation)


    (LET ((Card (NC.CoerceToCard CardIdentifier))
	  CardType Window)
         (NC.ProtectedCardOperation Card "Insert Link" NIL (SETQ Window (NC.FetchWindow Card))
				    (SETQ CardType (NC.FetchType Card))
				    (OR LinkOrLinkLabel (SETQ LinkOrLinkLabel
					    (NC.AskLinkLabel Window NIL NIL T T)))
				    (AND LinkOrLinkLabel (COND
					     ((NC.IsSubTypeOfP CardType (QUOTE Text))
					       (NC.InsertLinkInText (NC.FetchSubstance Card)
								      LinkOrLinkLabel DestinationCard 
								      Card))
					     ((NC.IsSubTypeOfP CardType (QUOTE Graph))
					       (NC.AddLinkToGraphCard Window LinkOrLinkLabel 
									DestinationCard))
					     ((NC.IsSubTypeOfP CardType (QUOTE Sketch))
					       (NC.AddLinkToSketchCard Window LinkOrLinkLabel 
									 DestinationCard])

(NC.AddLinksToCard
  [LAMBDA (CardIdentifier LinkLabel DestinationCards)        (* Randy.Gobbel " 2-Apr-87 15:38")

          (* * Adds multiple links to card designated by CardIdentifier. Rest of args can be NIL.)



          (* * fgh 6/9/86 Added Checks to make sure other interaction operation not in porgress.)



          (* * rht 9/23/86: Fixed bug in function passed to NC.SelectNoteCards.)



          (* * pmi 12/5/86: Modified message to NC.SelectNoteCards to mention SHIFT-selection.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation)



          (* * rg 3/18/87 added NC.CardSelectionOperation wrapper)



          (* * RG 4/2/87 changed NC.CardSelectionOperation to NCP.WithLockedCards)


    (LET ((SourceCard (NC.CoerceToCard CardIdentifier))
	  CardType Window OperationInProgress)
         (NC.ProtectedCardOperation SourceCard "Insert Links" NIL
				    (NCP.WithLockedCards
				      (SETQ Window (NC.FetchWindow SourceCard))
				      (SETQ CardType (NC.FetchType SourceCard))
				      (OR LinkLabel (SETQ LinkLabel
					      (NC.AskLinkLabel Window NIL NIL T T)))
				      (if LinkLabel
					  then (OR DestinationCards
						       (SETQ DestinationCards
							 (NC.SelectNoteCards
							   NIL
							   [FUNCTION (LAMBDA (SelectedCard)
							       (COND
								 ((NOT (NC.SameCardP SelectedCard 
										       SourceCard))
								   T)
								 (T (NC.PrintMsg (NC.FetchWindow
										     SourceCard)
										   T 
							    "A Card/Box cannot point to itself. "
										   (CHARACTER
										     13)
										   
									     "Selection ignored."
										   (CHARACTER
										     13))
								    NIL]
							   NC.SelectingMultipleCardsMenu SourceCard 
				       "Please shift-select the Cards or Boxes to be pointed to.")))
						 (NC.ClearMsg Window T)
						 (for DestinationCard in DestinationCards
						    do (NC.AddLinkToCard CardIdentifier LinkLabel 
									     DestinationCard])
)
(* * changes to NCPROGINT)

(DEFINEQ

(NCP.OpenCard
  [LAMBDA (Card ReadOnly Region/Position TypeSpecificArgs)   (* Randy.Gobbel " 4-Nov-87 18:26")

          (* * Cache this card, if necessary, and display on the screen.)



          (* * rht 11/16/86: Changed call to NCP.ReportError)


    (if (NC.ValidCardP Card)
	then [LET ((OldProc (TTY.PROCESS)))
		    (PROG1 (NC.EditNoteCard Card (OR ReadOnly (fetch (NoteFile ReadOnlyFlg)
								       of (fetch (Card NoteFile)
									       of Card)))
						Region/Position TypeSpecificArgs)
			     (AND (PROCESSP OldProc)
				    (TTY.PROCESS OldProc]
      else (NCP.ReportError (QUOTE NCP.OpenCard)
				(CONCAT Card " not an existing card or box."])

(NCP.DisplayCard
  [LAMBDA (Card ReadOnly Region/Position TypeSpecificArgs)   (* Randy.Gobbel " 4-Nov-87 14:10")

          (* * display Card on the screen.)



          (* * rht 11/16/86: Changed call to NCP.ReportError)



          (* * rg 11/4/87 added ReadOnly)


    (if (NC.ValidCardP Card)
	then (if (NCP.CardCachedP Card)
		   then [LET ((OldProc (TTY.PROCESS)))
			       (PROG1 (NC.EditNoteCard Card (OR ReadOnly
								      (fetch (NoteFile ReadOnlyFlg)
									 of (fetch (Card NoteFile)
										 of Card)))
							   Region/Position TypeSpecificArgs)
					(AND (PROCESSP OldProc)
					       (TTY.PROCESS OldProc]
		 else (NCP.ReportError (QUOTE NCP.DisplayCard)
					   (CONCAT Card 
					     " must be cached before displayed: NCP.DisplayCard.")))
      else (NCP.ReportError (QUOTE NCP.DisplayCard)
				(CONCAT Card " not an existing card or box."])

(NCP.CardTypeLinkDisplayMode
  [LAMBDA (Type)                                             (* rht: " 2-Mar-87 21:59")

          (* * Return the link display mode for this type.)



          (* * rht 11/16/86: Changed call to NCP.ReportError)


    (if (NCP.CardTypeP Type)
	then (NC.GetCardTypeField LinkDisplayMode Type)
      else (NCP.ReportError (QUOTE NCP.CardTypeLinkDisplayMode)
				(CONCAT Type " is not a loaded NoteCard type."))
	     NIL])

(NCP.CardTypeSuper
  [LAMBDA (Type)                                             (* rht: " 2-Mar-87 21:59")

          (* * Return the super type for this type.)



          (* * rht 11/16/86: Changed call to NCP.ReportError)


    (if (NCP.CardTypeP Type)
	then (NC.GetCardTypeField SuperType Type)
      else (NCP.ReportError (QUOTE NCP.CardTypeSuper)
				(CONCAT Type " is not a loaded NoteCard type."))
	     NIL])

(NCP.RemoveSpecialCard
  [LAMBDA (Card)                                             (* rht: "20-Nov-86 15:07")

          (* * Removes this card from list of special cards hung off notefile's "SpecialCards" user data prop.)


    (NC.NoteFileDelProp (fetch (Card NoteFile) of Card)
			  (QUOTE SpecialCards)
			  Card
			  (FUNCTION NC.SameCardP])

(NCP.NoteFileFromCard
  [LAMBDA (Card)                                             (* rht: "12-Jul-86 16:22")

          (* * Get the card's notefile.)


    (AND (NC.ValidCardP Card)
	   (fetch (Card NoteFile) of Card])

(NCP.CardNoteFile
  [LAMBDA (Card)                                             (* rht: "12-Jul-86 16:22")

          (* * Get the card's notefile.)


    (AND (NC.ValidCardP Card)
	   (fetch (Card NoteFile) of Card])

(NCP.LocalGlobalLink
  [LAMBDA (LinkType SourceCard DestinationCard FromLoc DisplayMode)
                                                             (* rht: "27-May-87 11:12")

          (* * Create a link from within the text of the SourceCard card to the DestinationCard card.)



          (* * rht 4/1/85: Changed to handle old-style link display modes.)



          (* * rht 11/17/85: Updated to handle new card and notefile objects.)



          (* * rht 8/25/86: Now passes non-nil QuietFlg to NCP.UncacheCards.)



          (* * rht 11/16/86: Changed call to NCP.ReportError)



          (* * rht 5/27/87: Changed call to NCP.CoerceToLinkDisplayMode slightly.)


    (PROG ((CoercedDisplayMode (NCP.CoerceToLinkDisplayMode (OR DisplayMode SourceCard)))
	     WasActive NoteFile)
	    (if (NULL CoercedDisplayMode)
		then (NCP.ReportError (QUOTE NCP.LocalGlobalLink)
					  (CONCAT DisplayMode " is invalid link display mode."
						    (CHARACTER 13)
						    "No link created."))
		       (RETURN NIL))
	    (if (EQ LinkType NC.FiledCardLinkLabel)
		then (if (AND (NOT (NCP.FileBoxP DestinationCard))
				    (NCP.FileBoxP SourceCard))
			   then (OR (SETQ WasActive (NCP.CardCachedP SourceCard))
					(NCP.CacheCards SourceCard))
				  (NCP.ChangeLoc SourceCard FromLoc)
				  (NCP.FileCards DestinationCard SourceCard)
				  [RETURN (PROG1 (CAR (NCP.GetLinks SourceCard 
									    DestinationCard 
									    NC.FiledCardLinkLabel))
						     (OR WasActive (NCP.UncacheCards SourceCard T]
			 else (NCP.ReportError (QUOTE NCP.LocalGlobalLink)
						   (CONCAT 
						   "FiledCard link must be from a box to a card."
							     (CHARACTER 13)
							     "No link created."))
				(RETURN NIL)))
	    (if (EQ LinkType NC.SubBoxLinkLabel)
		then (if (AND (NCP.FileBoxP DestinationCard)
				    (NCP.FileBoxP SourceCard))
			   then (OR (SETQ WasActive (NCP.CardCachedP SourceCard))
					(NCP.CacheCards SourceCard))
				  (NCP.ChangeLoc SourceCard FromLoc)
				  (NCP.FileCards DestinationCard SourceCard)
				  [RETURN (PROG1 (CAR (NCP.GetLinks SourceCard 
									    DestinationCard 
									    NC.SubBoxLinkLabel))
						     (OR WasActive (NCP.UncacheCards SourceCard T]
			 else (NCP.ReportError (QUOTE NCP.LocalGlobalLink)
						   (CONCAT 
						       "SubBox link must be from a box to a box."
							     (CHARACTER 13)
							     "No link created."))
				(RETURN NIL)))             (* Inserting non-hierarchical link into a filebox.)
	    (if (NCP.FileBoxP SourceCard)
		then (NCP.ReportError (QUOTE NCP.LocalGlobalLink)
					  (CONCAT 
				 "Local links from fileboxes must be either SubBox or FiledCard."
						    (CHARACTER 13)
						    "No link created."))
		       (RETURN NIL))
	    (if [NOT (FMEMB LinkType (NCP.LinkTypes (SETQ NoteFile (fetch (Card NoteFile)
										of SourceCard]
		then (if (NC.AskYesOrNo (CONCAT 
						   "That link type hasn't been used in NoteFile "
							(fetch (NoteFile FullFileName)
							   of NoteFile)
							(CHARACTER 13)
							"Want to create a new link type: " LinkType 
							"? ")
					      "--" NIL T (NC.AttachPromptWindow
						(WFROMMENU (fetch (NoteFile Menu) of NoteFile)))
					      NIL NIL)
			   then (NCP.CreateLinkType LinkType NoteFile)
			 else (RETURN NIL)))
	    (OR (SETQ WasActive (NCP.CardCachedP SourceCard))
		  (NCP.CacheCards SourceCard))
	    (AND FromLoc (NCP.ChangeLoc SourceCard FromLoc))
	    (RETURN (PROG1 (NC.InsertLinkInText (NC.FetchSubstance SourceCard)
						      LinkType DestinationCard SourceCard 
						      CoercedDisplayMode)
			       (OR WasActive (NCP.UncacheCards SourceCard T])

(NCP.GlobalGlobalLink
  [LAMBDA (LinkType FromCard ToCard)                         (* rht: " 2-Mar-87 22:04")

          (* * This builds a global link of type LinkType between FromCard and ToID. Complains if link type is system-defined
	  with restricted semantics. If LinkType is brand new, then asks if user wants to create a new label by that name.)



          (* * rht 11/18/85: Updated to handle new notefile and card object formats.)



          (* * kirk 23Jan86 Changed to use NC.AskYesOrNo)



          (* * rht 11/16/86: Changed call to NCP.ReportError)


    (LET ((NoteFile (fetch (Card NoteFile) of FromCard))
	  LinkTypes)
         (SETQ LinkTypes (NCP.UserLinkTypes NoteFile))
         (COND
	   ((OR (EQ LinkType NC.SourceLinkLabel)
		  (FMEMB LinkType LinkTypes))

          (* * LinkType type is okay so create the link.)


	     (NC.MakeGlobalLink NIL LinkType ToCard FromCard))
	   ((FMEMB (U-CASE LinkType)
		     NC.UCASESystemLinkLabels)
	     (NCP.ReportError (QUOTE NCP.GlobalGlobalLink)
				(CONCAT "Can't make a global-to-global link of type " LinkType "."))
	     NIL)
	   ((NC.AskYesOrNo (CONCAT "That link type hasn't been used in this NoteFile."
				       (CHARACTER 13)
				       "Want to create a new link type: " LinkType "? ")
			     "--" NIL T (NC.AttachPromptWindow (WFROMMENU (fetch (NoteFile
											 Menu)
										 of NoteFile)))
			     NIL NIL)
	     (NCP.CreateLinkType LinkType NoteFile)

          (* * LinkType type is okay so create the link.)


	     (NC.MakeGlobalLink NIL LinkType ToCard FromCard))
	   (T NIL])

(NCP.LinkType
  [LAMBDA Args                                               (* rht: " 2-Mar-87 22:05")

          (* * Takes either 1 or 2 args. The first is a link, the second an optional new label. Return old label in any case;
	  change label if the second arg is present.)



          (* * rht 2/8/85: Now makes sure source card of link is active before calling NC.RelabelLink.)



          (* * rht 8/25/86: Now passes non-nil QuietFlg to NCP.UncacheCards.)


    (LET (Link NewLinkType SourceCard NoteFile)
         (COND
	   ((AND (NEQ Args 1)
		   (NEQ Args 2))
	     (NCP.ReportError (QUOTE NCP.LinkType)
				(CONCAT "Improper number of args: " Args))
	     NIL)
	   [(NCP.ValidLink (SETQ Link (ARG Args 1)))
	     (PROG1 (fetch (Link Label)
			       Link)
		      (if (EQ Args 2)
			  then (COND
				   ((FMEMB (SETQ NewLinkType (ARG Args 2))
					     NC.SystemLinkLabels)
				     (NCP.ReportError (QUOTE NCP.LinkType)
							(CONCAT 
							 "Can't change label to a system label: "
								  NewLinkType)))
				   ((OR [FMEMB NewLinkType (NCP.LinkTypes
						     (SETQ NoteFile (fetch (Card NoteFile)
									 of (SETQ SourceCard
										(fetch
										  (Link SourceCard)
										   of Link]
					  (AND (NC.AskYesOrNo (CONCAT 
					      "That link type hasn't been used in this NoteFile."
									    (CHARACTER 13)
									    
							       "Want to create a new link type: "
									    NewLinkType "? ")
								  "--" NIL T NIL NIL NIL)
						 (NCP.CreateLinkType NewLinkType NoteFile)))
				     (if (NCP.CardCachedP SourceCard)
					 then (NC.RelabelLink Link NIL NewLinkType T)
				       else (NCP.CacheCards SourceCard)
					      (NC.RelabelLink Link NIL NewLinkType T)
					      (NCP.UncacheCards SourceCard T]
	   (T (NCP.ReportError (QUOTE NCP.LinkType)
				 (CONCAT Link " is not a valid link."))
	      NIL])
)
(* * changes to NCCROSSFILELINKS)

(DEFINEQ

(NC.CrossFileLinkEditFn
  [LAMBDA (Card Substance ReadOnly RegionOrPosition TypeSpecificArgs)
                                                             (* Randy.Gobbel " 4-Nov-87 14:12")

          (* * Given a CrossFileLink Substance, try to find the corresponding destination card in the destination notefile 
	  and bring it up.)



          (* * rht 11/13/86: Now updates title of crossfile link card to be the same as destination card if necessary.)



          (* * rht 5/27/87: Now calls NC.CheckCrossFileLinkCardTitle.)



          (* * rg 11/4/87 added ReadOnly)


    (LET ((DestinationCard (NC.GetCrossFileLinkDestCard Card))
	  DestinationCardTitle)
         (if DestinationCard
	     then (NC.CheckCrossFileLinkCardTitle Card DestinationCard)
		    (NC.EditNoteCard DestinationCard (OR ReadOnly (fetch (NoteFile ReadOnlyFlg)
									 of (fetch (Card NoteFile)
										 of Card)))
				       RegionOrPosition TypeSpecificArgs])

(NC.GetCrossFileLinkDestCard
  [LAMBDA (CrossFileLinkCard InterestedWindow Don'tOpenDestNoteFileFlg)
                                                             (* pmi: " 8-Sep-87 17:41")

          (* * Find the notefile corresponding to this crossfilelink and try to open it if not already open.
	  Then look for the card in there having the given UID. Return NIL if failed for any reason.)



          (* * rht 11/10/86: Make sure CrossFileLinkCard is cached before fetching substance.)



          (* * rht 11/19/86: Now rips off version number from destination notefile hint.)



          (* * rht 12/11/86: Now checks that destination card is not deleted.)



          (* * rht 12/16/86: Now takes InterestedWindow argument.)



          (* * rht 3/25/87: Now calls NC.CoerceToInterestedWindow.)



          (* * rht 3/27/87: Now calls NC.OpenCrossFileLinkDestNoteFile.)



          (* * rht 5/27/87: New arg Don'tOpenDestNoteFileFlg. If non-nil, then destination notefile has to be already open.)



          (* * rht 6/4/87: Now passes CrossFileLinkCard to NC.OpenCrossFileLinkDestNoteFile.)



          (* * rht 6/8/87: Now computes WasOpenPromptWindowFlg)



          (* * pmi 8/7/87: Now gets a filename if it has to loop and ask for another notefile to try.)



          (* * pmi 9/8/87: Now sets Don'tOpenDestNoteFileFlg to the results of NC.OpenCrossFileLinkDestNoteFile)


    (LET ((Title (NC.FetchTitle CrossFileLinkCard))
	  (SourceNoteFile (fetch (Card NoteFile) of CrossFileLinkCard))
	  Substance DestNoteFileUID DestFileHint DestCardUID DestNoteFile DestFileName Card 
	  WasOpenPromptWindowFlg)
         (OR InterestedWindow (SETQ InterestedWindow (NC.CoerceToInterestedWindow 
										   SourceNoteFile)))
         (SETQ WasOpenPromptWindowFlg (NC.PromptWindowOpenP InterestedWindow))
         (if (NOT (NC.ActiveCardP CrossFileLinkCard))
	     then (NC.GetNoteCard CrossFileLinkCard))
         (SETQ Substance (NC.FetchSubstance CrossFileLinkCard))
         (SETQ DestCardUID (fetch (CrossFileLinkSubstance CrossFileLinkDestCardUID) of 
											Substance))
         (SETQ DestNoteFileUID (fetch (CrossFileLinkSubstance CrossFileLinkDestNoteFileUID)
				    of Substance))
         (SETQ DestFileHint (fetch (CrossFileLinkSubstance CrossFileLinkDestFileHint)
				 of Substance))
         (SETQ DestNoteFile (NC.NoteFileFromNoteFileUID DestNoteFileUID))
         (SETQ DestFileName (OR (AND (type? NoteFile DestNoteFile)
					   (fetch (NoteFile FullFileName) of DestNoteFile))
				    DestFileHint))
         (for while [if Don'tOpenDestNoteFileFlg
			    then (NCP.OpenNoteFileP DestNoteFile)
			  else [SETQ Don'tOpenDestNoteFileFlg
				   (NULL (SETQ DestNoteFile (NC.OpenCrossFileLinkDestNoteFile
					       DestNoteFile DestFileName InterestedWindow 
					       CrossFileLinkCard]
				 (SETQ DestFileName (OR DestFileName (AND (type? NoteFile 
										     DestNoteFile)
										(fetch
										  (NoteFile 
										     FullFileName)
										   of DestNoteFile]
	    bind NewFileName
	    do (if (NC.ValidCardP (SETQ Card (NC.CardFromUID DestCardUID DestNoteFile)))
		     then (if [NOT (EQUAL (SETQ NewFileName (fetch (NoteFile FullFileName)
									 of DestNoteFile))
						  (FULLNAME (fetch (CrossFileLinkSubstance 
									CrossFileLinkDestFileHint)
								 of Substance]
				then (replace (CrossFileLinkSubstance CrossFileLinkDestFileHint)
					  of Substance with (PACKFILENAME (QUOTE VERSION)
										NIL
										(QUOTE BODY)
										NewFileName))
				       (NC.MarkCardDirty CrossFileLinkCard))
			    (RETURN Card)
		   else (if Don'tOpenDestNoteFileFlg
			      then (RETURN NIL)
			    else (NC.PrintMsg InterestedWindow T 
						  "Couldn't find destination card in "
						  DestFileName "." (CHARACTER 13))
				   (if (NOT (NC.AskYesOrNo 
						     "Want to try opening a different notefile? "
								 " -- " "Yes" NIL InterestedWindow 
								 WasOpenPromptWindowFlg))
				       then (RETURN NIL)
				     else (SETQ DestNoteFile (SETQ DestFileName NIL])

(NC.CreateCrossFileLinkCard
  [LAMBDA (SourceCard DestCard TwoWayFlg)                    (* rht: " 9-Dec-86 14:50")

          (* * Create a cross file link card in SourceCard's notefile.)



          (* * rht 11/19/86: Now rips off version number from destination notefile hint.)



          (* * rht 12/9/86: No longer records fact that card was "just created.")


    (LET ((DestNoteFile (fetch (Card NoteFile) of DestCard))
	  CrossFileLinkCard)
         (SETQ CrossFileLinkCard (NC.MakeNoteCard (QUOTE CrossFileLink)
						      (fetch (Card NoteFile) of SourceCard)
						      (NC.FetchTitle DestCard)
						      T
						      (create CrossFileLinkSubstance
								CrossFileLinkDestCardUID ←
								(fetch (Card UID) of DestCard)
								CrossFileLinkDestNoteFileUID ←
								(fetch (NoteFile UID) of 
										     DestNoteFile)
								CrossFileLinkDestFileHint ←
								(PACKFILENAME (QUOTE VERSION)
										NIL
										(QUOTE BODY)
										(fetch
										  (NoteFile 
										     FullFileName)
										   of DestNoteFile))
								CrossFileLinkTwoWayFlg ← TwoWayFlg)))
                                                             (* Indicate that card was just created.)
     CrossFileLinkCard])

(NC.AskCrossFileLinkMode
  [LAMBDA (DestCard InterestedWindow)                        (* rht: " 4-Jun-87 14:58")

          (* * Ask the user whether to make the link be twoway or oneway. Return T if user says two-way.
	  If dest notefile is open read-only, then only choice is one-way so don't ask.)


    (LET* ((NoteFile (fetch (Card NoteFile) of DestCard))
	   (FullFileName (fetch (NoteFile FullFileName) of NoteFile)))
          (if (NC.ReadOnlyNoteFileP NoteFile)
	      then NIL
	    else (NC.AskYesOrNo (CONCAT "Okay to make cross-file link to '" (NC.RetrieveTitle
						DestCard)
					      "' in '"
					      (FILENAMEFIELD FullFileName (QUOTE NAME))
					      ";"
					      (FILENAMEFIELD FullFileName (QUOTE VERSION))
					      "' be TWOWAY?"
					      (CHARACTER 13)
					      
				  "(otherwise leaves no record of link in destination notefile) ")
				    " -- " "Yes" T InterestedWindow])

(NC.CheckCrossFileLinkType
  [LAMBDA (RemoteCrossFileLinkCard LocalCrossFileLinkCard Link)
                                                             (* rht: "27-May-87 22:33")

          (* * If link types don't agree, change remote crossfilelink type to match.)


    (LET ((RemoteDestCard (NC.GetCrossFileLinkDestCard LocalCrossFileLinkCard NIL T))
	  (LinkLabel (fetch (Link Label) of Link))
	  RemoteLink NoteFile)
         (if RemoteDestCard
	     then [SETQ RemoteLink (OR (for FromLink in (NC.RetrieveFromLinks 
									  RemoteCrossFileLinkCard)
						when (NC.SameCardP (fetch (Link SourceCard)
									  of FromLink)
								       RemoteDestCard)
						do (RETURN FromLink))
					     (for ToLink in (NC.RetrieveToLinks 
									  RemoteCrossFileLinkCard)
						when (NC.SameCardP (fetch (Link DestinationCard)
									  of ToLink)
								       RemoteDestCard)
						do (RETURN ToLink]
		    (if (NOT (EQ (fetch (Link Label) of RemoteLink)
				       LinkLabel))
			then (if [NOT (NCP.ValidLinkTypeP LinkLabel (SETQ NoteFile
								    (fetch (Card NoteFile)
								       of RemoteCrossFileLinkCard]
				   then (NCP.CreateLinkType LinkLabel NoteFile))
			       (NC.RelabelLink RemoteLink NIL LinkLabel])

(NC.ComputeCrossFileLinkMode
  [LAMBDA (RemoteCard CrossFileLinkModePropList InterestedWindow)
                                                             (* rht: " 6-Jun-87 16:19")

          (* * If we've already made cross file links to RemoteCard's notefile, then it'll be registered on 
	  CrossFileLinkModePropList. Otherwise, consult global var, possibly ask user, and register her answer on 
	  CrossFileLinkModePropList.)



          (* * rht 6/6/87: Changed so that check of globalvar happens before check of CrossFileLinkModePropList.)


    (DECLARE (GLOBALVARS NC.NewCrossFileLinksMode))
    (LET ((NoteFile (fetch (Card NoteFile) of RemoteCard))
	  Mode)
         (COND
	   ((FMEMB NC.NewCrossFileLinksMode (QUOTE (TWOWAY ONEWAY)))
	     NC.NewCrossFileLinksMode)
	   ((FMEMB NoteFile CrossFileLinkModePropList)
	     (LISTGET CrossFileLinkModePropList NoteFile))
	   (T (SETQ Mode (if (NC.AskCrossFileLinkMode RemoteCard InterestedWindow)
			       then (QUOTE TWOWAY)
			     else (QUOTE ONEWAY)))
	      (LISTPUT CrossFileLinkModePropList NoteFile Mode)
	      Mode])
)
(* * changes to NCGRAPHCARD)

(DEFINEQ

(NC.GraphCardLeftButtonFn
  [LAMBDA (GraphNode GraphWindow)                            (* Randy.Gobbel " 4-Nov-87 14:16")

          (* * If this is a node containing a link icon, then do: IF Selection in progress, then pressing a node gets its 
	  destination ID if its actually a note card node. Otherwise, bring up the note card pointed to by the node.)



          (* * fgh 11/14/85 Updated to handle Card object.)



          (* * fgh 11/14/85 Isn't this obsolete??????)



          (* * rht&pmi 11/14/86: No longer does stupid pushcopy stuff.)



          (* * rg 11/4/87 added ReadOnly to NC.EditNoteCard call)


    (LET ((LinkIcon (fetch (GRAPHNODE NODELABEL) of GraphNode)))
         (if [AND (NC.LinkIconImageObjP LinkIcon)
		      (NOT (OR (KEYDOWNP (QUOTE LSHIFT))
				   (KEYDOWNP (QUOTE RSHIFT))
				   (KEYDOWNP (QUOTE CTRL))
				   (KEYDOWNP (QUOTE COPY))
				   (KEYDOWNP (QUOTE DELETE))
				   (KEYDOWNP (QUOTE MOVE]
	     then [LET [(Card (fetch (Link DestinationCard) of (NC.FetchLinkFromLinkIcon
								       LinkIcon]
		         (NC.EditNoteCard Card (fetch (NoteFile ReadOnlyFlg)
						    of (fetch (Card NoteFile) of Card]
	   else NIL])

(NC.RelayoutGraphCard
  [LAMBDA (Win)                                              (* pmi: "21-Jul-87 18:42")

          (* * Relayout the graph by making roots out of all nodes without FROMNODES.)



          (* * rht 8/15/86: Now uses proper COPYBUTTONEVENTFN in the SHOWGRAPH call.)



          (* * rht 11/1/86: Added NC.ProtectedCardOperation wrapper and check for ops in progress.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation)



          (* * pmi 7/21/87: Made sure LAYOUTGRAPH is getting a list for ROOTIDS.)


    (LET ((Card (NC.CoerceToCard Win)))
         (NC.ProtectedCardOperation
	   Card "Relayout Graph Card" NIL
	   (LET ((Graph (WINDOWPROP Win (QUOTE GRAPH)))
		 GraphNodes)
	        (if (SETQ GraphNodes (fetch (GRAPH GRAPHNODES) of Graph))
		    then (SETQ Graph (LAYOUTGRAPH
			       GraphNodes
			       [MKLIST (OR (for Node in GraphNodes
						  when (NULL (fetch (GRAPHNODE FROMNODES)
								    of Node))
						  collect (fetch (GRAPHNODE NODEID) of Node))
					       (fetch (GRAPHNODE NODEID) of (CAR GraphNodes]
			       (QUOTE Lattice)))
			   (replace (GRAPH GRAPH.ADDNODEFN) of Graph
			      with (FUNCTION NC.GraphAddNodeFn))
			   (replace (GRAPH GRAPH.DELETENODEFN) of Graph
			      with (FUNCTION NC.GraphDeleteNodeFn))
			   (replace (GRAPH GRAPH.ADDLINKFN) of Graph
			      with (FUNCTION NC.GraphAddLinkFn))
			   (replace (GRAPH GRAPH.DELETELINKFN) of Graph
			      with (FUNCTION NC.GraphDeleteLinkFn))
			   (replace (GRAPH GRAPH.MOVENODEFN) of Graph
			      with (FUNCTION NC.GraphMoveNodeFn))
			   (replace (GRAPH GRAPH.FONTCHANGEFN) of Graph
			      with (FUNCTION NC.GraphFontChangeFn))
			   (SHOWGRAPH Graph Win (FUNCTION NC.GraphCardLeftButtonFn)
					(FUNCTION NC.GraphCardMiddleButtonFn)
					NIL T (FUNCTION NC.GRAPHERCOPYBUTTONEVENTFN))
			   (NC.InstallTitleBarButtonEventFn Win (FUNCTION 
								NC.TitleBarButtonEventFn])
)
(* * changes to NCTEXTCARD)

(DEFINEQ

(NC.InstallTextTitleBarMiddleMenu
  [LAMBDA (Window CardType)                                  (* pmi: " 2-Apr-87 10:23")

          (* * Make a text card middle button title bar menu and install.)



          (* * pmi 4/1/87: Changed to replace MENUFONT with NC.MenuFont)


    (DECLARE (GLOBALVARS NC.MenuFont))
    (LET (Menu)
         [WINDOWPROP Window (QUOTE TitleBarMiddleButtonMenu)
		       (SETQ Menu (\TEDIT.CREATEMENU (NC.GetCardTypeField MiddleButtonMenuItems 
									      CardType]
         (replace (MENU MENUFONT) of Menu with NC.MenuFont)
         (replace (MENU ITEMHEIGHT) of Menu with (IPLUS (FONTPROP NC.MenuFont
									      (QUOTE HEIGHT))
								  1))
         (replace (MENU IMAGE) of Menu with NIL])

(NC.MakeTEditCard
  [LAMBDA (Card Title NoDisplayFlg ParamList)                (* rht: "17-Apr-87 16:18")
                                                             (* Make up a blank text card and display it.)

          (* * rht 9/10/85: Fixed call to NC.MakeTEditPropsList so prompt window gets fixed up before card is brought up.)



          (* * fgh 11/13/85 Updated to handle Card object.)



          (* * rht 4/11/86: Now passes type to NC.MakeTEditMiddleMenu.)



          (* * rht 5/6/86: Now calls NC.InstallTitleBarLeftMenu and NC.InstallTextTitleBarMiddleMenu.)



          (* * rht 9/8/86: No longer hangs Card off NoteCardObject windowprop. THis is done in NC.MakeNoteCard.)



          (* * rht 9/19/86: Mod to above fix. Now calls NC.MakeNewCardWindow a new fn that creates window and hangs Card off 
	  windowprop. Also takes ParamList arg.)



          (* * rht&pmi 11/19/86: Now passes NoteFile arg to NC.MakeTEditPropsList.)



          (* * rht 4/17/87: Now makes a prompt window before opening the window.)


    (LET (TextStream Window Type)
         (COND
	   (NoDisplayFlg [SETQ TextStream (OPENTEXTSTREAM "" NIL NIL NIL
							      (NC.MakeTEditPropsList
								NIL
								(LISTGET ParamList (QUOTE 
								 Don'tAttachUserSpecifiedPropsFlg]
			 (NC.SetSubstance Card TextStream)
			 (STREAMPROP TextStream (QUOTE NoteCardObject)
				       Card)
			 Card)
	   (T (SETQ Window (NC.MakeNewCardWindow Card (OR Title "Untitled")
						     NIL T))
                                                             (* Make a prompt window "invisibly" so it gets hooked 
							     in.)
	      (NC.AttachPromptWindowOffScreen Window)
	      (SETQ Type (NC.RetrieveType Card))
	      (NC.InstallTitleBarLeftMenu Window Type)
	      (NC.InstallTextTitleBarMiddleMenu Window Type)
	      (WINDOWADDPROP Window (QUOTE SHRINKFN)
			       (FUNCTION NC.TextCardShrinkFn))
	      (TEDIT NIL Window NIL (NC.MakeTEditPropsList Window (NC.FileBoxP Card T)
							       (fetch (Card NoteFile) of Card)))
	      (until (WINDOWPROP Window (QUOTE TEXTSTREAM)) do (BLOCK))
	      (SETQ TextStream (WINDOWPROP Window (QUOTE TEXTSTREAM)))
	      (NC.SetSubstance Card TextStream)
	      (STREAMPROP TextStream (QUOTE NoteCardObject)
			    Card)
	      Window])

(NC.BringUpTEditCard
  [LAMBDA (Card TextStream RegionOrPosition)                 (* rht: "17-Apr-87 16:11")
                                                             (* Bring up a TEdit window for Card ID whose text 
							     stream is TextStream in Region specified by 
							     RegionOrPosition or by the user.)

          (* * rht 9/10/85: Fixed call to NC.MakeTEditPropsList so prompt window gets fixed up before card is brought up.)



          (* * fgh 11/13/85 Updated to handle Card objects.)



          (* * kirk 2Dec85 Removed illegal RETURN)



          (* * rht 4/11/86: Added Type arg to call to NC.MakeTEditMiddleMenu and changed names of menu windowprops.)



          (* * rht 5/5/86: Now calls NC.InstallTitleBarLeftMenu and NC.InstallTextTitleBarMiddleMenu.)



          (* * rht 8/2/86: Now doesn't throw in any extra tedit props if card is a filebox.)



          (* * rht 11/16/86: Now moves window to RegionOrPosition if already up.)



          (* * rht&pmi 11/19/86: Now passes NoteFile arg to NC.MakeTEditPropsList.)



          (* * rht & pmi 12/16/86: Changed the way we get TEditWindow.)



          (* * rht 1/30/87: Now calls RESTART-PROCESS-OF-TEDIT-WINDOW from Bagley's TEDIT-PROCESS-KILLER package.)



          (* * rht 4/17/87: Now makes a prompt window before opening the window.)


    (LET (Region TEditWindow TEditProcess Title TextStreamDirtyFlg Type)
         (if (SETQ TEditWindow (NC.FetchWindow Card))
	     then (TOTOPW TEditWindow)
		    (if RegionOrPosition
			then (SHAPEW TEditWindow (NC.DetermineDisplayRegion Card 
										 RegionOrPosition)))
		    (RPTQ 2 (FLASHW TEditWindow))
		    (if (SETQ TEditProcess (WINDOWPROP TEditWindow (QUOTE PROCESS)))
			then (TTY.PROCESS TEditProcess)
		      else                                 (* Process may have been turned off.
							     Try to restart.)
			     (SETQ TEditProcess (RESTART-PROCESS-OF-TEDIT-WINDOW TEditWindow)))
		    TEditWindow
	   else (SETQ Region (NC.DetermineDisplayRegion Card RegionOrPosition))
		  (SETQ Title (NC.RetrieveTitle Card))
		  (SETQ Type (NC.RetrieveType Card))
		  (SETQ TEditWindow (CREATEW Region Title NIL T)) 
                                                             (* Make a prompt window "invisibly" so it gets hooked 
							     in.)
		  (NC.AttachPromptWindowOffScreen TEditWindow)
		  (WINDOWADDPROP TEditWindow (QUOTE SHRINKFN)
				   (FUNCTION NC.TextCardShrinkFn))
		  (NC.InstallTitleBarLeftMenu TEditWindow Type)
		  (NC.InstallTextTitleBarMiddleMenu TEditWindow Type)
		  (SETQ TextStreamDirtyFlg (NC.CardDirtyP Card))
		  (TEDIT TextStream TEditWindow NIL (NC.MakeTEditPropsList TEditWindow
									       (NC.FileBoxP Card T)
									       (fetch (Card 
											 NoteFile)
										  of Card)))
		  (AND TextStreamDirtyFlg (NC.MarkCardDirty Card)))
     TEditWindow])

(NC.TEditMenuFn
  [LAMBDA (Window)                                           (* Randy.Gobbel "23-Apr-87 15:32")

          (* * Gets called from LEFT or MIDDLE button press in title bar of TEdit window. If LEFT press bring up the 
	  Notecards Manipulation Window. IF MIDDLE press bring up the TEdit specific NoteCard operations menu.
	  Bring up menus using TEDIT.DEFAULT.MENUFN)



          (* * rht 4/11/86: No only calls TEDIT.DEFAULT.MENUFN for middle button press. On left button press, works like 
	  graph and sketch cards.)



          (* * rg 4/23/87 added contention lock)


    (if (LASTMOUSESTATE LEFT)
	then (APPLY* (OR (MENU (WINDOWPROP Window (QUOTE TitleBarLeftButtonMenu)))
			       (FUNCTION NILL))
			 Window)
      else (WINDOWPROP Window (QUOTE TEDIT.MENU)
			   (WINDOWPROP Window (QUOTE TitleBarMiddleButtonMenu)))
	     (NC.ProtectedCardOperation (NC.CoerceToCard Window)
					"Perform TEdit Operation" Window (TEDIT.DEFAULT.MENUFN
					  Window])

(NC.GetTextSubstance
  [LAMBDA (Card Length Stream)                               (* rht: " 2-Feb-87 17:51")
                                                             (* Get a text stream from the database file)

          (* * fgh 11/13/85 Updated to handle Card objects.)



          (* * fgh 11/20/85 NoteCards now passes down start and end pointer as args.)



          (* * fgh 11/21/85 Now passed Length instead of start and end ptrs.)



          (* * rht 1/23/86: Now takes Stream as arg instead of computing from Card.)



          (* * rht 2/2/87: Fixed bug in the way NC.MakeTEditPropsList was being called.)


    (LET ((TempStream (OPENSTREAM (QUOTE {NODIRCORE})
				    (QUOTE BOTH)
				    (QUOTE NEW)))
	  TextStream StartPtr)

          (* * Copy text stream to a NODIRCORE file from the current location. Number of bytes copied should be Length minus 
	  the 4 bytes already read for OriginalLocation)


         (COPYBYTES Stream TempStream (SETQ StartPtr (GETFILEPTR Stream))
		      (PLUS StartPtr Length))

          (* * return an open textstream on the temp file)


         [SETQ TextStream (OPENTEXTSTREAM TempStream NIL NIL NIL (NC.MakeTEditPropsList
						NIL
						(NC.FileBoxP Card T)
						(fetch (Card NoteFile) of Card]
         (STREAMPROP TextStream (QUOTE NoteCardObject)
		       Card)
     TextStream])
)
(* * changes to NCSKETCHCARD)

(DEFINEQ

(NC.MakeSketchCard
  [LAMBDA (Card Title NoDisplayFlg)                          (* fgh: "30-Jun-86 23:13")

          (* * rht 2/1/85: Added windowprop to prevent sketch asking about saving changes.)



          (* * fgh 11/14/85 Updated to handle Card object.)



          (* * rht 5/6/86 Replaced call to NC.SetupTitleBarMenu with calls to NC.InstallTitleBarButtonEventFn and 
	  NC.InstallTitleBarLeftMenu and NC.InstallSketchTitleBarMiddleMenu.)



          (* * fgh 6/30/86 Added NC.SK.COPY.BUTTONEVENTFN on Sketch Window. Added SKETCH.ADD.ELEMENT call when NoDisplayFlg)


    (if NoDisplayFlg
	then (NC.SetSubstance Card (SKETCH.ADD.ELEMENT NIL NIL))
	       Card
      else (LET (Window CardType)
	          (SETQ CardType (NC.RetrieveType Card))
	          [SETQ Window (SKETCHW.CREATE NIL NIL (NC.DetermineDisplayRegion Card NIL)
						   (OR Title "Untitled")
						   NIL
						   (SKETCH.COMMANDMENU (NC.GetCardTypeField 
									    MiddleButtonMenuItems 
											 CardType]
	          (WINDOWPROP Window (QUOTE DONTQUERYCHANGES)
				T)
	          (WINDOWPROP Window (QUOTE COPYBUTTONEVENTFN)
				(FUNCTION NC.SK.COPY.BUTTONEVENTFN))
	          (WINDOWPROP Window (QUOTE SHRINKFN)
				(FUNCTION NC.SketchCardShrinkFn))
	          (NC.InstallTitleBarButtonEventFn Window (FUNCTION 
						       NC.SketchTitleBarButtonEventFn))
	          (NC.InstallTitleBarLeftMenu Window CardType)
	          (NC.SetSubstance Card (INSURE.SKETCH Window))
	      Window])

(NC.BringUpSketchCard
  [LAMBDA (Card Substance RegionOrPosition)                  (* rht: " 2-Mar-87 20:44")
                                                             (* Bring up a sketch card containing substance in 
							     specified region)

          (* * rht 2/1/85: Added windowprop to prevent sketch asking about saving changes.)



          (* * rht 10/10/85: Now sets substance if was nil.)



          (* * fgh 11/14/85 Updated to handle Card object.)



          (* * rht 5/5/86: Replaced call to NC.SetupTitleBarMenu with calls to NC.InstallTitleBarButtonEventFn and 
	  NC.InstallTitleBarLeftMenu and NC.InstallSketchTitleBarMiddleMenu.)



          (* * fgh 6/30/86 Added NC.SK.COPY.BUTTONEVENTFN to sketch window. Made Substance to be INSURE.SKETCH of the sketch 
	  window.)



          (* * rht 11/16/86: Now moves window to RegionOrPosition if already up.)



          (* * rht 3/2/87: No longer passes RegionViewed and Scale to SKETCHW.CREATE. SKETCHW.CREATE will extract them from 
	  the imageobj.)


    (LET ([SketchName (AND (NULL Substance)
			     (MKATOM (fetch (Card UID) of Card]
	  Region Title SketchViewer CardType)
         [COND
	   [(SETQ SketchViewer (NC.FetchWindow Card))
	     (TOTOPW SketchViewer)
	     (if RegionOrPosition
		 then (SHAPEW SketchViewer (NC.DetermineDisplayRegion Card RegionOrPosition)))
	     (RPTQ 2 (FLASHW SketchViewer))
	     (TTY.PROCESS (WINDOWPROP SketchViewer (QUOTE PROCESS]
	   (T (SETQ CardType (NC.RetrieveType Card))
	      [SETQ SketchViewer (SKETCHW.CREATE (OR Substance SketchName)
						     NIL
						     (NC.DetermineDisplayRegion Card 
										 RegionOrPosition)
						     (NC.RetrieveTitle Card)
						     NIL
						     (SKETCH.COMMANDMENU (NC.GetCardTypeField
									     MiddleButtonMenuItems 
									     CardType]
	      (WINDOWPROP SketchViewer (QUOTE DONTQUERYCHANGES)
			    T)
	      (WINDOWPROP SketchViewer (QUOTE COPYBUTTONEVENTFN)
			    (FUNCTION NC.SK.COPY.BUTTONEVENTFN))
	      (WINDOWPROP SketchViewer (QUOTE SHRINKFN)
			    (FUNCTION NC.SketchCardShrinkFn))
	      (NC.InstallTitleBarButtonEventFn SketchViewer (FUNCTION 
						   NC.SketchTitleBarButtonEventFn))
	      (NC.InstallTitleBarLeftMenu SketchViewer CardType)
	      (OR Substance (NC.SetSubstance Card (INSURE.SKETCH SketchViewer]
     SketchViewer])
)
(* * changes to NCIDEASKETCHCARD)

(DEFINEQ

(NCIDEASKETCH.MakeIdeaSketchCard
  [LAMBDA (Card Title NoDisplayFlg)                          (* kirk: "10-Aug-86 17:17")

          (* * Create an idea sketch card. This is almost a copy of NC.MakeSketchCard.)



          (* * kirk 10Aug86 Converted to 1.3k)


    (if NoDisplayFlg
	then (NC.SetSubstance Card (SKETCH.ADD.ELEMENT NIL NIL))
	       Card
      else (LET (Window CardType)
	          (SETQ CardType (NC.RetrieveType Card))
	          [SETQ Window (WRITEW.CREATE NIL NIL (NC.DetermineDisplayRegion Card NIL)
						  (OR Title "Untitled")
						  NIL
						  (SKETCH.COMMANDMENU (NC.GetCardTypeField 
									    MiddleButtonMenuItems 
											 CardType]
	          (WINDOWPROP Window (QUOTE DONTQUERYCHANGES)
				T)
	          (WINDOWPROP Window (QUOTE COPYBUTTONEVENTFN)
				(FUNCTION NC.SK.COPY.BUTTONEVENTFN))
	          (WINDOWPROP Window (QUOTE SHRINKFN)
				(FUNCTION NC.SketchCardShrinkFn))
	          (NC.InstallTitleBarButtonEventFn Window (FUNCTION 
						       NC.SketchTitleBarButtonEventFn))
	          (NC.InstallTitleBarLeftMenu Window CardType)
	          (NC.SetSubstance Card (INSURE.SKETCH Window))
	      Window])

(NCIDEASKETCH.BringUpIdeaSketchCard
  [LAMBDA (Card Substance Region/Position)                   (* kirk: "11-Aug-86 16:17")
                                                             (* Bring up a sketch card containing substance in 
							     specified region)

          (* * rht 2/1/85: Added windowprop to prevent sketch asking about saving changes.)



          (* * rht 10/10/85: Now sets substance if was nil.)



          (* * fgh 11/14/85 Updated to handle Card object.)



          (* * rht 5/5/86: Replaced call to NC.SetupTitleBarMenu with calls to NC.InstallTitleBarButtonEventFn and 
	  NC.InstallTitleBarLeftMenu and NC.InstallSketchTitleBarMiddleMenu.)



          (* * fgh 6/30/86 Added NC.SK.COPY.BUTTONEVENTFN to sketch window. Made Substance to be INSURE.SKETCH of the sketch 
	  window.)


    (LET ([SketchName (AND (NULL Substance)
			     (MKATOM (fetch (Card UID) of Card]
	  Region Title SketchViewer CardType)
         [COND
	   [(SETQ SketchViewer (NC.FetchWindow Card))
	     (RPTQ 2 (FLASHW SketchViewer))
	     (TOTOPW SketchViewer)
	     (TTY.PROCESS (WINDOWPROP SketchViewer (QUOTE PROCESS]
	   (T (SETQ CardType (NC.RetrieveType Card))
	      [SETQ SketchViewer (WRITEW.CREATE (OR Substance SketchName)
						    (NC.FetchRegionViewed Card)
						    (NC.DetermineDisplayRegion Card Region/Position)
						    (NC.RetrieveTitle Card)
						    (NC.FetchScale Card)
						    (SKETCH.COMMANDMENU (NC.GetCardTypeField 
									    MiddleButtonMenuItems 
											 CardType]
	      (WINDOWPROP SketchViewer (QUOTE DONTQUERYCHANGES)
			    T)
	      (WINDOWPROP SketchViewer (QUOTE COPYBUTTONEVENTFN)
			    (FUNCTION NC.SK.COPY.BUTTONEVENTFN))
	      (WINDOWPROP SketchViewer (QUOTE SHRINKFN)
			    (FUNCTION NC.SketchCardShrinkFn))
	      (NC.InstallTitleBarButtonEventFn SketchViewer (FUNCTION 
						   NC.SketchTitleBarButtonEventFn))
	      (NC.InstallTitleBarLeftMenu SketchViewer CardType)
	      (OR Substance (NC.SetSubstance Card (INSURE.SKETCH SketchViewer]
     SketchViewer])
)
(* * changes to NCINTERFACE)

(DEFINEQ

(NC.InstallTitleBarLeftMenu
  [LAMBDA (Window CardType)                                  (* pmi: "25-Mar-87 12:04")

          (* * Make a menu from the CardType's LeftButtonMenuItems and install on windowprop.)



          (* * pmi 3/25/87: Added NC.MenuFont to all menus)


    (DECLARE (GLOBALVARS NC.MenuFont))
    (WINDOWPROP Window (QUOTE TitleBarLeftButtonMenu)
		  (create MENU
			    ITEMS ← (NC.GetCardTypeField LeftButtonMenuItems CardType)
			    CENTERFLG ← T
			    MENUFONT ← NC.MenuFont
			    ITEMHEIGHT ← (IPLUS (FONTPROP NC.MenuFont (QUOTE HEIGHT))
						  1])

(NC.AskLinkLabel
  [LAMBDA (MainWindow MultipleFlg SystemLinksFlg NewLinkFlg CancelOkayFlg ReverseLinksFlg 
		      OldLinkLabels ReturnListOfListFlg)     (* pmi: " 1-Apr-87 12:12")
                                                             (* Asks for label on notecard links)

          (* * rht 8/2/84: Added double columns for when called by the browser, i.e. ReverseLinksFlg=T.
	  Reverse links have prefix "←".)



          (* * rht 11/19/84: Changed strings from "pointer" to "link" and from "label" to "type".)



          (* * rht 2/14/85: Added extra arg OldLinkLabels in the Multiple selection case to display previous choices.)



          (* * rht 10/11/85: Took out printing to prompt window. It's a waste of screen space.)



          (* * rht 10/22/85: Added ReturnListOfListFlg so caller can tell difference between aborting from Stylesheet and 
	  choosing NULL set of links.)



          (* * fgh 11/14/85 Updated to handle NoteFile and card objects.)



          (* * pmi 12/5/86: Modified so that clicking outside of Link type menu is equivalent to choosing **CANCEL** from 
	  menu.)



          (* * pmi 3/25/87: Added NC.MenuFont to all menus)


    (DECLARE (GLOBALVARS NC.MenuFont NC.UCASESystemLinkLabels NC.UnspecifiedLinkLabel))
    (PROG (Menu Choice Choices LabelsList LinkLabels Position Card NoteFile)
	    (SETQ Card (NC.CoerceToCard MainWindow))
	    (SETQ NoteFile (fetch (Card NoteFile) of Card))
	    (SETQ LinkLabels (NC.RetrieveLinkLabels NoteFile SystemLinksFlg))
	    [SETQ Position (AND (WINDOWP MainWindow)
				    (create POSITION
					      XCOORD ← (fetch (REGION LEFT)
							  of (WINDOWPROP MainWindow (QUOTE
									       REGION)))
					      YCOORD ← (fetch (REGION TOP) of (WINDOWREGION
										    MainWindow]
	    [COND
	      (MultipleFlg [SETQ Choices
			     (STYLESHEET (CREATE.STYLE
					     (QUOTE ITEMS)
					     [COND
					       [ReverseLinksFlg
						 (LIST (create MENU
								   ITEMS ← LinkLabels)
							 (create MENU
								   ITEMS ←
								   (for Link in LinkLabels
								      collect (PACK*
										  (QUOTE ←)
										  Link]
					       (T (LIST (create MENU
								    ITEMS ← LinkLabels]
					     (QUOTE NEED.NOT.FILL.IN)
					     (QUOTE MULTI)
					     (QUOTE POSITION)
					     Position
					     (QUOTE TITLE)
					     "Link Types?"
					     (QUOTE SELECTIONS)
					     (LIST (for Label in OldLinkLabels
							when (NEQ (NTHCHAR Label 1)
								      (QUOTE ←))
							collect Label)
						     (for Label in OldLinkLabels
							when (EQ (NTHCHAR Label 1)
								     (QUOTE ←))
							collect Label]
			   (RETURN (COND
				       ((NULL Choices)     (* User aborted from stylesheet.)
					 NIL)
				       [(AND ReverseLinksFlg ReturnListOfListFlg)
					 (LIST (NCONC (CAR Choices)
							  (CADR Choices]
				       (ReverseLinksFlg (NCONC (CAR Choices)
								 (CADR Choices)))
				       (ReturnListOfListFlg Choices)
				       (T (CAR Choices]
	    (SETQ Menu (create MENU
				   TITLE ← " Link Type "
				   ITEMS ← [NCONC (COND
						      [ReverseLinksFlg (for Link in LinkLabels
									  join (LIST
										   Link
										   (CONCAT "←" Link]
						      (T (COPY LinkLabels)))
						    (AND NewLinkFlg (LIST (QUOTE 
									      --New% Link% Type--)))
						    (AND CancelOkayFlg (LIST (QUOTE **CANCEL**]
				   CENTERFLG ← T
				   MENUPOSITION ← Position
				   MENUCOLUMNS ← (AND ReverseLinksFlg 2)
				   MENUFONT ← NC.MenuFont
				   ITEMHEIGHT ← (IPLUS (FONTPROP NC.MenuFont (QUOTE HEIGHT))
							 1)))

          (* * Allow user to cancel by selecting outside of Links menu)


	    (SETQ Choice (OR (MKATOM (MENU Menu))
				 (QUOTE **CANCEL**)))
	    [COND
	      ((EQ Choice (QUOTE **CANCEL**))
		(SETQ Choice))
	      ((EQ Choice (QUOTE --New% Link% Type--))
		(NC.ClearMsg MainWindow NIL)
		(until (COND
			   ((NOT (FMEMB [U-CASE (SETQ Choice
							(MKATOM (NC.AskUser 
									  "Enter new link type: "
										NIL NIL NIL 
										MainWindow NIL]
					    NC.UCASESystemLinkLabels))
			     T)
			   (T (NC.PrintMsg MainWindow T Choice " is a system reserved link type."
					     (CHARACTER 13)
					     "Please choose another link type."
					     (CHARACTER 13))
			      NIL)))
		(OR Choice (SETQ Choice NC.UnspecifiedLinkLabel))
		(AND (NOT (FMEMB Choice LinkLabels))
		       (NC.StoreLinkLabels NoteFile (CONS Choice LinkLabels]
	    (RETURN Choice])

(NC.SelectNoteCards
  [LAMBDA (SingleCardFlg SelectionPredicate Menu InstigatingCardOrWindow Msg CheckForCancelFlg 
			 FileLevelLockFlg)                   (* Randy.Gobbel "12-Aug-87 16:18")

          (* Select a set of note cards or a single note card, depending on SingleCardFlg. Works by interpreting all mouse 
	  presses until a card has been chosen (if SingleCardFlg is T) or until the Done button has been pressed 
	  (if SingleCardFlg is NIL). If the mouse press occus within a Title bar of a notecard, add that note card to the 
	  selected list. Otherwise, if you are pointing into a note card, call the BUTTONEVENTFN for that note card.
	  The Selection in Progress flag has been set, so all note card BUTTONEVENTFNs should know to ignore all presses 
	  except those that occur on link icons. Link icon presses should simply add the desination of that link to the 
	  selected note cards list. This function should always be called from inside of an NC.CardSelectionOperation 
	  wrapper.)



          (* * rht 8/1/84: Changed second RESETSAVE call to give NC.ClearMsg a NIL argument.)



          (* * rht 1/9/85: Fixed so now prints name of selected item even it's a link.)



          (* * rht 2/15/85: Now can backspace over last selection chosen. Added new arg Msg so that when we reprint the list,
	  we can reprint the message as well.)



          (* * rht 3/23/85: Added the CheckForCancelFlg arg, which if non-nil causes Cancel to be handled differently then 
	  Done after no selections. Namely, Cancel will return the atom CANCELLED whereas Done with no selections returns 
	  NIL. If CheckForCancelFlg is NIL then NIL is returned in both cases.)



          (* * fgh 11/14/85 Updated to handle Card and NoteFile objects.)



          (* * rht 11/18/85: Fixed so able to select when InstigatingNoteFile is NIL.)



          (* * fgh 12/20/85 Totally rewritten for 1.3 selection mechanism. Based on COPYINSERT now rather than on takingf 
	  over the mouse process.)



          (* * fgh 1/15/86 Added call to SPAWN.MOUSE in case this is called under the mouse process)



          (* * kirk 25Apr86 Changed to use SessionIcon (NC.NoteCardsIconWindow) rather than PROMPTWINDOW if no Instigating 
	  window is supplied.)



          (* * fgh 7/5/86 Added code to put CRs into printout of selected cards in order to keep prompt window from getting 
	  infinitely wide to accomdate the printout.)



          (* * rht 10/5/86: Now allows choice of cards from remote notefile.)



          (* * rht 10/18/86: Give TTY process to process that originally had it if possible.)



          (* * rht & pmi 11/14/86: Now checks for valid card before testing SelectionPredicate.)



          (* * pmi 12/5/86 Modified prompt messages to mention SHIFT-selection.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument.)



          (* * rg 3/18/87 reworked for NC.CardSelectionOperation: added NAMED-RESETSAVE forms for Card locking.)



          (* * 3/23/87: Changed to call REMOVEWINDOW instead of DETACHWINDOW before deleting the attached menu.
	  Also changed so that menu is attached to InstigatingWindow rather than to PromptWindow. This makes it possible for 
	  windows to "slide down" when selection ends.)



          (* * rht 3/24/87: Now calls NC.CoerceToInterestedWindow)



          (* * RG 4/1/87 changed CANCELLED to DON'T)



          (* * rg 4/22/87 changed some names,)



          (* * rht&rg&pmi 4/22/87: Moved location of ALLOW.BUTTON.EVENTS.)



          (* * rg 6/2/87 added FileLevelLockFlg)



          (* * rht 6/6/87: If user selects a cross-file link card, then try to follow it.)


    (DECLARE (USEDFREE CardListResetVar))

          (* * if we are running under the mouse process, start up a new mouse process)


    (ALLOW.BUTTON.EVENTS)
    (LET (Window Card ButtonEventFn InstigatingWindow InstigatingCard InstigatingNoteFile MenuWindow 
		 PromptWindow CopyInsertEvent CardProcessedEvent SelectedCards BinLoopProcess 
		 OldTTYProcess OpInProgress ResetItems TTYResetVar InternalResetVar)
         (NAMED-RESETLST
	   InternalResetVar
	   (OR SelectionPredicate (SETQ SelectionPredicate (FUNCTION TRUE)))
	   (SETQ PromptWindow (OR (NC.AttachPromptWindow (SETQ InstigatingWindow
								 (NC.CoerceToInterestedWindow
								   InstigatingCardOrWindow)))
				      PROMPTWINDOW))
	   (SETQ InstigatingCard (NC.CoerceToCard InstigatingCardOrWindow))
	   (SETQ InstigatingNoteFile (AND InstigatingCard (fetch (Card NoteFile) of 
										  InstigatingCard)))
	   (NC.PrintMsg InstigatingWindow T (COND
			    (Msg (CONCAT Msg (CHARACTER 13)))
			    (T ""))
			  "Items shift-selected:  ")
	   (SETQ OldTTYProcess (TTY.PROCESS))

          (* * Set up the prompt window for proper use by the CopyInsertFn)


	   (NAMED-RESETSAVE InternalResetVar (WINDOWPROP PromptWindow (QUOTE SelectCardsMonitor)
							     (CREATE.MONITORLOCK (QUOTE 
										      SelectCards)))
			      (BQUOTE (WINDOWPROP , PromptWindow SelectCardsMonitor NIL)))
	   [WINDOWPROP PromptWindow (QUOTE CopyInsertEvent)
			 (SETQ CopyInsertEvent (CREATE.EVENT (QUOTE CopyInsertEvent]
	   (WINDOWPROP PromptWindow (QUOTE NewCardsProcessed)
			 T)
	   [WINDOWPROP PromptWindow (QUOTE CardProcessedEvent)
			 (SETQ CardProcessedEvent (CREATE.EVENT (QUOTE CardProcessedEvent]
	   (WINDOWPROP PromptWindow (QUOTE SelectNoteCardsProcess)
			 (THIS.PROCESS))
	   (WINDOWPROP PromptWindow (QUOTE COPYINSERTFN)
			 (FUNCTION NC.SelectNoteCardsCopyInsertFn))
	   (NAMED-RESETSAVE InternalResetVar (WINDOWPROP PromptWindow (QUOTE SelectedCards)
							     NIL)
			      (BQUOTE (WINDOWPROP , PromptWindow (QUOTE SelectedCards)
						      NIL)))
	   (NAMED-RESETSAVE InternalResetVar (WINDOWPROP PromptWindow (QUOTE SelectingCards)
							     T)
			      (BQUOTE (WINDOWPROP , PromptWindow SelectingCards NIL)))

          (* * make sure ↑E aborts properly)


	   (NAMED-RESETSAVE InternalResetVar (RESET.INTERRUPTS (LISPINTERRUPTS)
								   T))

          (* * Make the process behind the prompt window including control for a blinking cursor)


	   [WINDOWPROP PromptWindow (QUOTE PROCESS)
			 (SETQ BinLoopProcess (ADD.PROCESS
			     (QUOTE (PROG NIL (BLOCK)
					      (TTYDISPLAYSTREAM (PROCESSPROP (THIS.PROCESS)
										 (QUOTE WINDOW)))
					      XXXX
					      (BIN)
					      (BLOCK)
					      (GO XXXX)))
			     (QUOTE WINDOW)
			     PromptWindow
			     (QUOTE NAME)
			     (QUOTE BinLoopProcess)
			     (QUOTE TTYENTRYFN)
			     (FUNCTION [LAMBDA (Process)
				 (PROCESSPROP Process (QUOTE OldCaret)
						(CARET CROSSHAIRS))
				 (ECHOMODE])
			     (QUOTE TTYEXITFN)
			     (FUNCTION (LAMBDA (Process)
				 (CARET (PROCESSPROP Process (QUOTE OldCaret)))
				 (ECHOMODE T]
	   (NAMED-RESETSAVE InternalResetVar NIL (BQUOTE (DEL.PROCESS , BinLoopProcess)))

          (* * Insure the prompt window is cleared on the way out)


	   [NAMED-RESETSAVE InternalResetVar NIL
			      (BQUOTE (PROGN (AND (HASTTYWINDOWP , BinLoopProcess)
							(TTY.PROCESS (if (AND (PROCESSP
										      , OldTTYProcess)
										    (HASTTYWINDOWP
										      , OldTTYProcess)
										    )
									   then , OldTTYProcess
									 else T)))
						 (NC.ClearMsg , InstigatingWindow T]
	   (WINDOWADDPROP PromptWindow (QUOTE CLOSEFN)
			    (FUNCTION NC.ZapBinLoopProcess))

          (* * Set up the menu above the prompt window)

                                                             (* fix in case MENUPOSITION is set incorrectly in menu
							     passed down)
	   (replace (MENU MENUPOSITION) of Menu
	      with (CONSTANT (create POSITION
					   XCOORD ← 0
					   YCOORD ← 0)))
	   [NAMED-RESETSAVE InternalResetVar (PROGN (ATTACHMENU
							  Menu
							  (OR InstigatingWindow PROMPTWINDOW)
							  (if InstigatingWindow
							      then (QUOTE TOP)
							    else (QUOTE BOTTOM))
							  (if (AND (WINDOWP InstigatingWindow)
								       (WINDOWP PromptWindow))
							      then (CDR (WINDOWPROP
									      PromptWindow
									      (QUOTE WHEREATTACHED))
									    )
							    else (QUOTE LEFT)))
							(WINDOWPROP (WFROMMENU Menu)
								      (QUOTE SelectionPromptWindow)
								      PromptWindow))
			      (BQUOTE (PROGN (REMOVEWINDOW (WFROMMENU , Menu]

          (* * If there is an instigating window, make sure it and all its attachments are visible on the screen.)


	   (if InstigatingWindow
	       then (NC.MoveWindowOntoScreen InstigatingWindow))

          (* * Give the prompt window the tty process)


	   (TTY.PROCESS (WINDOWPROP PromptWindow (QUOTE PROCESS)))

          (* * Loop as long as necessary)


	   [WITH.MONITOR
	     (WINDOWPROP PromptWindow (QUOTE SelectCardsMonitor))
	     (until (OR (EQ SelectedCards (QUOTE DON'T))
			    (AND SingleCardFlg SelectedCards)
			    (EQ (CAR SelectedCards)
				  (QUOTE DONE)))
		do
		 (                                           (* Wait for the user to respond by copy inserting 
							     something into the prompt window)
		  (until [OR (NOT (PROCESSP BinLoopProcess))
				 (NOT (EQ SelectedCards (WINDOWPROP PromptWindow (QUOTE
									    SelectedCards]
		     do (MONITOR.AWAIT.EVENT (WINDOWPROP PromptWindow (QUOTE 
									       SelectCardsMonitor))
						 CopyInsertEvent 1000))
                                                             (* Get the latest selection list)
		  (SETQ SelectedCards (WINDOWPROP PromptWindow (QUOTE SelectedCards)))
		  (WINDOWPROP PromptWindow (QUOTE NewCardsProcessed)
				T)
		  (NOTIFY.EVENT CardProcessedEvent T)
		  (OR (PROCESSP BinLoopProcess)
			(SETQ SelectedCards (QUOTE DON'T)))
		  (NAMED-RESETLST
		    TTYResetVar                              (* Turn off the caret)
		    (NAMED-RESETSAVE TTYResetVar (TTY.PROCESS (THIS.PROCESS)))
                                                             (* If the last thing wasn't a done or cancel, process 
							     the new selection)
		    (SETQ Card (CAR SelectedCards))
		    (WITH.MONITOR
		      NC.LockLock
		      (COND
			((AND (NEQ Card (QUOTE DONE))
				(NEQ SelectedCards (QUOTE DON'T))
				(NEQ Card (QUOTE *New% Card*)))
                                                             (* Try to follow cross-file links.)
			  [if (AND (NC.ValidCardP Card)
				       (NC.CrossFileLinkCardP Card))
			      then (SETQ Card (NC.GetCrossFileLinkDestCard Card 
										InstigatingWindow))
				     (WINDOWPROP PromptWindow (QUOTE SelectedCards)
						   (SETQ SelectedCards (CONS Card (CDR 
										    SelectedCards]
                                                             (* Check to make sure that the selection is valid)
			  [COND
			    ((EQ Card (QUOTE *Undo% Selection*))
                                                             (* Chop off two elements from the list -
							     the indicator and the previous item.)
			      (SETQ Card (CADR SelectedCards))
			      (WINDOWPROP PromptWindow (QUOTE SelectedCards)
					    (SETQ SelectedCards (CDDR SelectedCards)))
                                                             (* now get our hands off of all the locks we've 
							     acquired for this card)
			      (if Card
				  then (NAMED-RESETUNSAVE CardListResetVar (NC.FetchUserDataProp
								Card
								(QUOTE ResetItems)))
					 (NC.SetUserDataProp Card (QUOTE ResetItems)
							       NIL))
			      (NC.ClearMsg InstigatingWindow NIL))
			    [(OR (NOT (NC.ValidCardP Card))
				   (NULL (APPLY* SelectionPredicate Card)))
                                                             (* Does this card match the slection predicate)
			      (NC.PrintMsg InstigatingWindow T "*** Invalid selection. ***"
					     (CHARACTER 13))
			      (WINDOWPROP PromptWindow (QUOTE SelectedCards)
					    (SETQ SelectedCards (CDR SelectedCards]
			    ((AND (SETQ OpInProgress (if FileLevelLockFlg
							     then (NC.NoteFileCheckOpInProgress
								      (fetch (Card NoteFile)
									 of Card))
							   else (NC.CardCheckOpInProgress Card)))
				    (NEQ OpInProgress (QUOTE US)))
			      (NC.PrintOperationInProgressMsg InstigatingWindow "Select Card" 
								OpInProgress)
			      (DISMISS 1000)
			      (WINDOWPROP PromptWindow (QUOTE SelectedCards)
					    (SETQ SelectedCards (CDR SelectedCards)))
			      (NC.ClearMsg InstigatingWindow NIL))
			    (T                               (* A valid selection.)
			       (NC.ClearMsg InstigatingWindow NIL)
			       [if FileLevelLockFlg
				   then [SETQ ResetItems
					    (LIST (NAMED-RESETSAVE
						      CardListResetVar
						      (NC.NoteFileProp (fetch (Card NoteFile)
									    of Card)
									 (QUOTE OperationInProgress)
									 "Select Card")
						      (BQUOTE (NC.NoteFileProp
								  ,
								  (fetch (Card NoteFile)
								     of Card)
								  OperationInProgress NIL)))
						    (NAMED-RESETSAVE
						      CardListResetVar
						      (NC.NoteFileProp (fetch (Card NoteFile)
									    of Card)
									 (QUOTE ProcessInProgress)
									 (THIS.PROCESS))
						      (BQUOTE (NC.NoteFileProp
								  ,
								  (fetch (Card NoteFile)
								     of Card)
								  ProcessInProgress NIL)))
						    (NAMED-RESETSAVE CardListResetVar
								       (SETQ NC.NoteFileBusyList
									 (CONS (THIS.PROCESS)
										 NC.NoteFileBusyList))
								       (QUOTE (SETQ
										  NC.NoteFileBusyList
										  (DREMOVE
										    (THIS.PROCESS)
										    
									      NC.NoteFileBusyList]
				 else (SETQ ResetItems
					  (LIST [NAMED-RESETSAVE CardListResetVar
								     (SETQ NC.CardBusyList
								       (CONS (THIS.PROCESS)
									       NC.CardBusyList))
								     (QUOTE (SETQ
										NC.CardBusyList
										(DREMOVE (
										     THIS.PROCESS)
											   
										  NC.CardBusyList]
						  [NAMED-RESETSAVE
						    CardListResetVar
						    [NC.NoteFileProp
						      (fetch (Card NoteFile) of Card)
						      (QUOTE CardProcessInProgressList)
						      (CONS (THIS.PROCESS)
							      (NC.NoteFileProp (fetch
										   (Card NoteFile)
										    of Card)
										 (QUOTE 
									CardProcessInProgressList]
						    (BQUOTE (NC.ResetCardProcessInProgress
								,
								(fetch (Card NoteFile)
								   of Card]
						  (NAMED-RESETSAVE CardListResetVar
								     (NC.SetUserDataProp
								       Card
								       (QUOTE OperationInProgress)
								       "Select Card")
								     (BQUOTE (NC.SetUserDataProp
										 , Card 
									      OperationInProgress NIL)
									       ))
						  (NAMED-RESETSAVE CardListResetVar
								     (NC.SetUserDataProp
								       Card
								       (QUOTE ProcessInProgress)
								       (THIS.PROCESS))
								     (BQUOTE (NC.SetUserDataProp
										 , Card 
										ProcessInProgress NIL]
			       (NAMED-RESETSAVE InternalResetVar (NC.SetUserDataProp
						    Card
						    (QUOTE ResetItems)
						    ResetItems)
						  (BQUOTE (NC.SetUserDataProp , Card ResetItems 
										  NIL]

          (* * Print the results in the prompt window)


			  (NC.PrintMsg InstigatingWindow NIL (COND
					   (Msg (CONCAT Msg (CHARACTER 13)))
					   (T ""))
					 "Items selected:  ")
			  (for ThisCard in (REVERSE SelectedCards)
			     do (NC.PrintMsg InstigatingWindow NIL (NC.RetrieveTitle ThisCard)
						 ",  ")
				  (if [AND InstigatingWindow (GREATERP
						 (DSPXPOSITION NIL PromptWindow)
						 (TIMES 1.25 (WINDOWPROP InstigatingWindow
									     (QUOTE WIDTH]
				      then (NC.PrintMsg InstigatingWindow NIL (CHARACTER 13]

          (* * Return the result)


	   (PROG1 [COND
		      ((EQ SelectedCards (QUOTE DON'T))
			(COND
			  (CheckForCancelFlg (QUOTE DON'T))
			  (T NIL)))
		      (SingleCardFlg (if (EQ (CAR SelectedCards)
						 (QUOTE DONE))
					 then NIL
				       else (CAR SelectedCards)))
		      (T (if (EQ (CAR SelectedCards)
				     (QUOTE DONE))
			     then (DREVERSE (CDR SelectedCards))
			   else (DREVERSE SelectedCards]
		    (WINDOWPROP PromptWindow (QUOTE SelectedCards)
				  NIL])

(NC.AttachNoteFileName
  [LAMBDA (CardWindow OffFlg)                                (* rht: "25-Mar-87 14:46")

          (* * Attach an indicator of the NoteFile for this Card to the Card)



          (* * fgh 5/29/86 Changed collection of old attached windows to prevent NILs in collection result.)



          (* * fgh 6/13/86 Put detachment and reattachment of previous attached windows into a RESETLST.
	  Added FREEATTACHEDWINDOW as the CLOSEFN of the indicator window. Added code to reset PASSTOMAINWINDOW COMS of the 
	  previously attachwed windows. Changed MINSIZE of indicator window to allow small fonts. Added a REPAINTFN to the 
	  indicator window.)



          (* * fgh 7/2/86 Replaced the CLEARW call in the indicator window REPAINTFN with a DSPRESET for two reasons: reset 
	  the X coor befre printining and CLEARW is not allowed in REPAINTFNS.)



          (* * fgh&rht 7/5/86: Changed the name "FileName" to "NameToPrint".)



          (* * rht 3/20/87: Moved Frank's hack that temporarily detaches windows into a macro called 
	  NC.WithWindowsUnattached.)



          (* * rht 3/25/87: Now calls NC.NoteFileIndicatorWinHeight.)


    (LET ((Card (NC.CardFromWindow CardWindow))
	  AttachedWindows FileName Window)
         (if (NC.CardP Card)
	     then (SETQ AttachedWindows (ATTACHEDWINDOWS CardWindow))
		    (if OffFlg
			then [CLOSEW (for window in AttachedWindows
					    thereis (WINDOWPROP window (QUOTE NoteFileIndicator]
			       (REPOSITIONATTACHEDWINDOWS CardWindow)
		      else (TOTOPW CardWindow)
			     (if [SETQ Window (for window in AttachedWindows
						     thereis (WINDOWPROP window (QUOTE 
										NoteFileIndicator]
				 then 

          (* * There already is an indicator window, open and redisplay it.)


					(OR (OPENWP Window)
					      (OPENW Window))
					(REDISPLAYW Window)
			       else 

          (* * No existing indicator window, make one.)


				      (NC.WithTopWindowsUnattached
					CardWindow

          (* * Make the indicator window.)


					(LET (NoteFile NameToPrint YSize IndicatorWindow)
					     (SETQ NoteFile (fetch (Card NoteFile) of Card))
					     (SETQ NameToPrint (NC.MakeNoteFileNameIndicator
						 NoteFile))
					     (SETQ YSize (NC.NoteFileIndicatorWinHeight))
					     (SETQ IndicatorWindow
					       (CREATEW (CREATEREGION 0 0 100 YSize)
							  NIL T))
					     (WINDOWPROP IndicatorWindow (QUOTE MAXSIZE)
							   (CONS 1000 YSize))
					     (WINDOWPROP IndicatorWindow (QUOTE MINSIZE)
							   (CONS 20 YSize))
					     (ATTACHWINDOW IndicatorWindow CardWindow (QUOTE
							       TOP)
							     (QUOTE JUSTIFY)
							     (QUOTE LOCALCLOSE))
					     [WINDOWPROP IndicatorWindow (QUOTE BUTTONEVENTFN)
							   (FUNCTION (LAMBDA (window)
							       (INVERTW window)
							       [NC.SetUpNoteFileInterface
								 (fetch (Card NoteFile)
								    of (NC.CardFromWindow
									   (MAINWINDOW window]
							       (INVERTW window]
					     (WINDOWPROP IndicatorWindow (QUOTE NameToPrint)
							   NameToPrint)
					     (WINDOWADDPROP IndicatorWindow (QUOTE CLOSEFN)
							      (FUNCTION FREEATTACHEDWINDOW)
							      T)
					     [WINDOWPROP IndicatorWindow (QUOTE REPAINTFN)
							   (FUNCTION (LAMBDA (Window Region)
							       (DSPRESET Window)
							       (PRIN1 (WINDOWPROP Window
										      (QUOTE 
										      NameToPrint))
									Window]
					     (DSPFONT NC.NoteFileIndicatorFont IndicatorWindow)
					     (PRIN1 NameToPrint IndicatorWindow)
					     (OPENW IndicatorWindow)
					     (WINDOWPROP IndicatorWindow (QUOTE NoteFileIndicator)
							   (QUOTE Showing])

(NC.CardImageObjP
  [LAMBDA (ImageObj)                                         (* fgh: "19-Dec-85 23:34")
    (type? Card (IMAGEOBJPROP ImageObj (QUOTE OBJECTDATUM])

(NC.CopyStructure
  [LAMBDA (RootCards DestinationFileBox TraversalSpecs InterestedWindow QuietFlg)
                                                             (* Randy.Gobbel " 3-Jun-87 10:15")

          (* * Copy a NoteCard structure into a filebox)



          (* * kirk 13/7/86: Placed TraversalSpecs after RootCards selection and changed prompt message)



          (* * rht 9/2/86: Threw away CheckFlg arg. Wasn't being used. Changed to call NCP.CollectCards instead of outdated 
	  NC.CollectCards. Changed arg named ToPosition to DestinationFileBox. Also changed FromCard to RootCard.
	  Passes two link types to NC.AskTraversalSpecs.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 3/9/87: Now accepts multiple root cards.)



          (* * rg 3/9/87 added NC.ProtectedSessionOperation wrapper)



          (* * RG 3/18/87 changed NC.ProtectedSessionOperation to NCP.WithLockedCards ; added NC.IfAllCardsFree wrapper)



          (* * rht&rg&pmi 4/22/87: Removed calls to ERROR!)



          (* * rg 6/2/87 added check for DON'T to selection of dest filebox)


    (DECLARE (GLOBALVARS NC.SelectingCardsMenu NC.SelectingCardMenu))
    (NCP.WithLockedCards (SETQ RootCards (MKLIST RootCards))
			 (NC.IfAllCardsFree
			   (NC.LockListOfCards RootCards "Copy Structure")
			   (if [AND (OR RootCards (SETQ RootCards
						(NC.SelectNoteCards NIL NIL NC.SelectingCardsMenu 
								      NIL 
						   "Shift-select the root cards of the structure")))
					[OR TraversalSpecs (SETQ TraversalSpecs
						(NC.AskTraversalSpecs (fetch (Card NoteFile)
									   of (CAR RootCards))
									(QUOTE (SubBox FiledCard]
					(OR DestinationFileBox
					      (NEQ (SETQ DestinationFileBox
						       (NC.SelectNoteCards T
									     (FUNCTION [LAMBDA (
										   Card)
										 (NC.FileBoxP
										   Card T])
									     NC.SelectingCardMenu NIL 
					     "Shift-select the FileBox to contain the structure."
									     T))
						     (QUOTE DON'T]
			       then (NC.CopyCards (NCP.CollectCards RootCards
									  (fetch (TRAVERSALSPECS
										     LinkTypes)
									     of TraversalSpecs)
									  (fetch (TRAVERSALSPECS
										     Depth)
									     of TraversalSpecs))
						      DestinationFileBox RootCards QuietFlg 
						      InterestedWindow])

(NC.CloseStructure
  [LAMBDA (RootCards TraversalSpecs InterestedWindow QuietFlg)
                                                             (* Randy.Gobbel " 2-Apr-87 15:38")

          (* * rht 9/2/86: Replaced call to outdated NC.CollectCards with NCP.CollectCards. Threw away useless NoCheckFlg and
	  Don'tClearFlg args.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 3/9/87: Now accepts multiple root cards.)



          (* * rg 3/9/87 added NC.ProtectedSessionOperation wrapper)



          (* * rg 4/1/87 changes NC.ProtectedSessionOperation to NCP.WithLockedCards ; added NC.IfAllCardsFree wrapper)


    (NCP.WithLockedCards (SETQ RootCards (MKLIST RootCards))
			 (NC.IfAllCardsFree (NC.LockListOfCards RootCards "Close Structure")
					    (OR RootCards (SETQ RootCards
						    (NC.SelectNoteCards NIL NIL 
									  NC.SelectingCardsMenu NIL 
						   "Shift-select the root cards of the structure"))
						  (ERROR!))
					    [OR TraversalSpecs (SETQ TraversalSpecs
						    (NC.AskTraversalSpecs (fetch (Card NoteFile)
									       of (CAR RootCards))
									    (QUOTE (SubBox 
											FiledCard]
					    (if (AND RootCards TraversalSpecs)
						then (OR QuietFlg (NC.PrintMsg InterestedWindow 
										     T 
								  "Collecting cards to close ..."))
						       (NC.CloseNoteCards
							 (NCP.CollectCards RootCards
									     (fetch (TRAVERSALSPECS
											LinkTypes)
										of TraversalSpecs)
									     (fetch (TRAVERSALSPECS
											Depth)
										of TraversalSpecs))
							 NIL NIL InterestedWindow)
						       (OR QuietFlg (NC.ClearMsg InterestedWindow 
										     T))
						       RootCards])

(NC.DeleteStructure
  [LAMBDA (RootCards TraversalSpecs InterestedWindow QuietFlg Don'tPutToBeDeletedCardsFlg)
                                                             (* Randy.Gobbel " 2-Apr-87 15:38")

          (* * rht 8/29/86: Reorganized and changed to call NCP.CollectCards which is more efficient than the old 
	  NCP.ComputeTransitiveClosure. Also now takes QuietFlg and Don'tPutToBeDeletedCardsFlg args.
	  Threw away Don'tClearFlg.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 3/9/87: Now accepts multiple root cards.)



          (* * rg 3/9/87 added NC.ProtectedSessionOperation wrapper)



          (* * rg 4/2/87 turned NC.ProtectedSessionOperation into NC.CardSelectionOperation)


    (NCP.WithLockedCards (SETQ RootCards (MKLIST RootCards))
			 (NC.IfAllCardsFree (NC.LockListOfCards RootCards "Delete Structure")
					    (OR RootCards (SETQ RootCards
						    (NC.SelectNoteCards NIL NIL 
									  NC.SelectingCardsMenu NIL 
						   "Shift-select the root cards of the structure"))
						  (ERROR!))
					    [OR TraversalSpecs (SETQ TraversalSpecs
						    (NC.AskTraversalSpecs (fetch (Card NoteFile)
									       of (CAR RootCards))
									    (QUOTE (SubBox 
											FiledCard]
					    (if (AND RootCards TraversalSpecs)
						then (OR QuietFlg (NC.PrintMsg InterestedWindow 
										     T 
								 "Collecting cards to delete ..."))
						       (NC.DeleteNoteCards
							 (NCP.CollectCards RootCards
									     (fetch (TRAVERSALSPECS
											LinkTypes)
										of TraversalSpecs)
									     (fetch (TRAVERSALSPECS
											Depth)
										of TraversalSpecs))
							 T NIL InterestedWindow QuietFlg NIL 
							 Don'tPutToBeDeletedCardsFlg)
						       (OR QuietFlg (NC.ClearMsg InterestedWindow 
										     T))
						       RootCards])
)
(* * changes to NCFILEBOXCARD)

(DEFINEQ

(NC.AddFileBoxCard
  [LAMBDA NIL                                                (* rht: " 7-Apr-86 18:21")

          (* * fgh 2/17/86 Added attached bitmap field.)


    (NC.AddCardType (QUOTE FileBox)
		      (QUOTE Text)
		      [BQUOTE ((MakeFn , (FUNCTION NC.MakeFileBox]
		      (BQUOTE ((LinkDisplayMode Title)
				 (DefaultHeight 200)
				 (DefaultWidth 335)
				 (DisplayedInMenuFlg , T)
				 (LinkIconAttachedBitMap , NC.FileBoxIcon)
				 (LeftButtonMenuItems
				   ,
				   (for Item in (NC.GetCardTypeField LeftButtonMenuItems
									 (QUOTE Text))
				      join (if (EQ (CAR Item)
							 (QUOTE Insert% Link))
						 then (LIST NC.GlobalInsertLinkMenuItem
								(QUOTE
								  (Put% Cards% Here
								    (FUNCTION 
								      NC.FileBoxCollectChildren)
								    
					    "Collect new cards and file boxes into this FileBox.")))
					       else (LIST Item])

(NC.MakeFileBox
  [LAMBDA (Card Title NoDisplayFlg ParamList)                (* rht: "10-Nov-86 22:49")
                                                             (* Make up a blank contents card, hook it to the user 
							     specified parent contents cards, and display it.)

          (* * rht 12/2/84: In NoDisplayFlg case, changed to return ID rather than TextStream.)



          (* * rht 12/8/84: Massive shaving. Took out code to force filing now (at creation time))



          (* * rht 9/11/85: Took out insertion of spacer when no markers.)



          (* * fgh 11/13/85 Updated to handle Card object.)



          (* * fgh 2/6/86 Chaged calls to NC.FetchDefaultHeight & NC.FetchDefaultWidth)



          (* * fgh 2/6/86 Removed bug where NC.ClearMsg was deleteing card immediately.)



          (* * rht 4/11/86: Now passes Type and Window to NC.MakeTEditLeftMenu.)



          (* * rht 8/2/86: Now lets NC.MakeTEditPropsList build the props to be passed to TEDIT.)



          (* * rht 9/8/86: Now doesn't create window before calling TEDIT to avoid stupid prompt win popping up.)



          (* * rht 9/19/86: Now applies supertype's MakeFn to cut out redundant code.)



          (* * rht 11/10/86: Now passes NIL as title to Super's makefn.)


    (DECLARE (GLOBALVARS NC.MarkersInFileBoxesFlg NC.SubBoxMarkerLabel NC.FiledCardMarkerLabel 
			     NC.AlphabetizedFileBoxChildrenFlg))
    (LET ((Spacer (CONCAT (CHARACTER 13)
			    (CHARACTER 13)))
	  Window TextStream Type)
         [SETQ Window (WINDOWP (NC.ApplySupersFn MakeFn Card NIL NoDisplayFlg
						     (if ParamList
							 then (LISTPUT ParamList (QUOTE 
								 Don'tAttachUserSpecifiedPropsFlg)
									   T)
						       else (QUOTE (
Don'tAttachUserSpecifiedPropsFlg T]
         (SETQ TextStream (NC.FetchSubstance Card))
         (COND
	   (NC.MarkersInFileBoxesFlg (TEDIT.INSERT.OBJECT (NC.MakePlaceMarker 
									     NC.SubBoxMarkerLabel)
							    TextStream 1)
				     (TEDIT.INSERT TextStream Spacer 2)
				     (TEDIT.INSERT.OBJECT (NC.MakePlaceMarker 
									  NC.FiledCardMarkerLabel)
							    TextStream 4)
				     (TEDIT.INSERT TextStream Spacer 5)))
         (if NC.AlphabetizedFileBoxChildrenFlg
	     then (NCP.CardProp Card (QUOTE OrderingFn)
				    (FUNCTION NC.IDAlphOrder)))
         (if NoDisplayFlg
	     then Card
	   else Window])

(NC.FileBoxCollectChildren
  [LAMBDA (WindowOrTextStream Card NewChildren NoDisplayFlg)
                                                             (* Randy.Gobbel " 2-Apr-87 15:38")

          (* * Ask user for new children (either cards or fileboxes) for this filebox. Check to make sure that no 
	  circularities are introduced. This code is sort of the inverse of the NC.AddParents code and thus looks quite 
	  similar.)



          (* * rht 10/29/84: Added NoDisplayFlg to prevent error message when no appropriate elements exist.
	  Also now returns ID if at least one child was added, NIL otherwise.)



          (* * fgh 11/13/85 Updated to handle Card object.)



          (* * rht 7/5/86: Now checks for readonly cards.)



          (* * rht 8/11/86: Added code to check to make sure that another operation is not in progress on this card when this
	  fn is called.)



          (* * rht 10/17/86: Made successful filing operations NOT do dismiss.)



          (* * pmi 12/5/86: Modified message to NC.SelectNoteCards to mention SHIFT-selection.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 1/28/87: Now activates parent box if necessary and saves before deactivating.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation)



          (* * rg 3/18/87 added NC.CardSelectionOperation wrapper)


    (OR Card (SETQ Card (NC.CoerceToCard WindowOrTextStream)))
    (NC.ProtectedCardOperation Card "Put Cards Here" NIL
			       (NCP.WithLockedCards
				 (LET ((Window (NC.FetchWindow Card)))
				      (if (NC.CheckForNotReadOnly Card Window 
								      "Can't do filing in ")
					  then (OR NewChildren (SETQ NewChildren
							 (NC.SelectNoteCards NIL NIL 
								  NC.SelectingFileBoxChildrenMenu 
									       Card 
							     " Please shift-select new children.")))
						 (COND
						   ([AND NewChildren Card
							   (LET ((WasActiveFlg (NC.ActiveCardP
										 Card)))
							        (OR WasActiveFlg (NC.GetNoteCard
									Card))
							        (PROG1 (for NewChild
									    in NewChildren
									    bind OneHook
									    when (NC.MakeChildLink
										     NewChild Card 
										     Window)
									    do (SETQ OneHook T)
									    finally (RETURN
											OneHook))
									 (OR WasActiveFlg
									       (NC.QuitCard Card 
											      NIL NIL 
											      NIL NIL 
											      NIL T]
						     Card)
						   ((NULL NoDisplayFlg)
						     (NC.PrintMsg Window NIL 
						  "No appropriate NoteCards or FileBoxes chosen."
								    (CHARACTER 13)
								    "Hence no children added."
								    (CHARACTER 13))
						     (DISMISS 1000)
						     (NC.ClearMsg Window T)
						     NIL)
						   (T NIL])
)
(* * changes to NCBROWSERCARD)

(DEFINEQ

(NC.AddBrowserCard
  [LAMBDA NIL                                                (* rht: "25-Apr-87 17:58")

          (* * fgh 11/14/85 Updated to handle merge of card and substance types.)



          (* * rht 4/7/86: Added middle button menu items.)



          (* * rht 4/25/87: Added QuitFn)


    (NC.AddCardType (QUOTE Browser)
		      (QUOTE Graph)
		      [BQUOTE ((MakeFn , (FUNCTION NC.MakeBrowserCard))
				 (EditFn , (FUNCTION NC.BringUpBrowserCard))
				 (PutFn , (FUNCTION NC.PutBrowserSubstance))
				 (GetFn , (FUNCTION NC.GetBrowserSubstance))
				 (DeleteLinksFn , (FUNCTION NC.DelReferencesToCardFromBrowser))
				 (QuitFn , (FUNCTION NC.BrowserCardQuitFn]
		      (BQUOTE ((LinkDisplayMode Title)
				 (DefaultHeight 350)
				 (DefaultWidth 500)
				 (DisplayedInMenuFlg , T)
				 (LeftButtonMenuItems , (for Item in (NC.GetCardTypeField
									   LeftButtonMenuItems
									   (QUOTE Graph))
							   collect (if (EQ (CAR Item)
										 (QUOTE 
										     Insert% Link))
									 then 
								      NC.GlobalInsertLinkMenuItem
								       else Item)))
				 (MiddleButtonMenuItems , (QUOTE ((Recompute% Browser
								       (FUNCTION 
									 NC.UpdateBrowserCard)
								       
			     "Recomputes this browser to show the current state of the NoteFile.")
								     (Relayout% Graph
								       (FUNCTION 
									 NC.RelayoutBrowserCard)
								       
						    "Re-layout the browser, but keep same nodes.")
								     (Reconnect% Nodes
								       (FUNCTION 
									 NC.ConnectNodesInBrowser)
								       
	   "Draw all possible links, from currently selected link types, between pairs of nodes.")
								     (Unconnect% Nodes
								       (FUNCTION 
								       NC.UnconnectNodesInBrowser)
								       
							       "Undraw all links in the browser.")
								     (Expand% Browser% Node
								       (FUNCTION 
									 NC.ExpandBrowserNode)
								       
					      "Expand the graph under one node to a given depth.")
								     (Graph% Edit% Menu
								       (FUNCTION 
									 NC.GetGraphEditMenu)
								       
								"Bring up the graph editor menu.")
								     (Change% Browser% Specs
								       (FUNCTION 
									 NC.ChangeBrowserSpecs)
								       
		 "Make changes to some or all of the browser specs, e.g. link types, depth, etc.")
								     (Browser% Overview% Win
								       (FUNCTION 
									NC.MakeBrowserOverviewWin)
								       
							    "Attach the browser overview window.")
								     (Change% Overview% Specs
								       (FUNCTION 
								       NC.AskBrowserOverviewSpecs)
								       
			      "Change the browser overview specs: where to attach and what mode."])

(NC.MakeBrowserCard
  [LAMBDA (Card Title NoDisplayFlg ParamList)                (* rht: " 4-Jun-87 11:49")

          (* Make a browser card with id Card using root at RootID and the link following predictae specified by Predicate.
	  IF Root and/or ListOfLinkLabels not specified, ask the user.)



          (* * rht 8/3/84: Changed to call NC.AskLinkLabel with its ReverseLinkLabel parameter set to T.)



          (* * fgh 10/2/84 Changed Link Icons to be image objects in NodeLabel of Graph Npodes rather than annotations on 
	  graph nodes.)



          (* * rht 10/19/84: Fixed setting up of browser card's prop list in case NoDisplayFlg is T so we have no Window.
	  Now NC.MakeLinksLegend returns the label pairs.)



          (* * rht 11/27/84: Removed the WINDOWADDPROP call to put NC.GraphCardCloseFn on the CLOSEFN of the window.
	  This causes trouble. NC.QuitCard will get put on by NC.MakeNoteCard and that's enough.)



          (* * rht 1/3/85: Now puts a dummy region of the right size if the NoDisplayFlg is on.)



          (* * rht 1/15/85: Put hooks for AddNode, AddLink, etc. so editing graph edits underlying structure.)



          (* * rht 2/14/85: Added VerticalFlg and made BrowserSpecs get put on browser's proplist in all cases.)



          (* * rht 4/1/85: Now calls NC.AskBrowserSpecs with additional Don'tAskFlg in case of call from Programmer's 
	  interface.)



          (* * rht 11/17/85: Updated to handle new card and notefile objects.)



          (* * rht 2/7/86: Now gets browser format, etc. via fetch/set fns.)



          (* * rht 5/6/86: Took out call to NC.SetupTitleBarMenu.)



          (* * rht 5/8/86: Added calls to rig title bar properly.)



          (* * rht 7/10/86: Now passes ListOfLinkLabels to NC.AskBrowserSpecs.)



          (* * rht 9/19/86: Mod to above fix. Now calls NC.MakeNewCardWindow a new fn that creates window and hangs Card off 
	  windowprop.)



          (* * pmi 12/5/86: Modified message to NC.SelectNoteCards to mention SHIFT-selection. Also added GLOBALVARS 
	  statement.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 12/16/86: Now checks that NC.MakeLink succeeded before creating a real link icon. If not, then make a 
	  standin for a cross file link icon.)



          (* * rg 3/18/87 added NC.CardSelectionOperation wrapper)



          (* * rht 3/20/87: Removed needless call to NC.ActivateCard.)



          (* * rg 4/2/87 changed wrapper to NCP.WithLockedCards and added NC.IfAllCardsFree wrapper)



          (* * rht 5/26/87: Now handles cross-file links properly, i.e. uses cross-file link standin in cases when 
	  GrowLinkLattice wasn't able to follow into the remote notefile.)


    (DECLARE (GLOBALVARS NC.SubBoxLinkLabel NC.BrowserContentsLinkLabel NC.SpecialBrowserSpecsFlg 
			     NC.*Graph*BrowserFormat NC.SelectingBrowserSourceMenu))
    (NCP.WithLockedCards
      (PROG ([RootCards (MKLIST (LISTGET ParamList (QUOTE ROOTCARDS]
	       (ListOfLinkLabels (LISTGET ParamList (QUOTE LINKTYPES)))
	       (BrowserFormat (LISTGET ParamList (QUOTE FORMAT)))
	       (Depth (LISTGET ParamList (QUOTE DEPTH)))
	       (CardType (NC.RetrieveType Card))
	       Lattice RootNodes Window Graph SpecialBrowserSpecs BrowserSpecs DropVirtualNodesFlg)
	      (NC.IfAllCardsFree
		(NC.LockListOfCards RootCards "Make Browser Card")
		[COND
		  ((NULL NoDisplayFlg)
		    (SETQ Window (NC.MakeNewCardWindow Card (OR Title "Untitled")))
		    (WINDOWADDPROP Window (QUOTE SHRINKFN)
				     (FUNCTION NC.GraphCardShrinkFn]
		[if (NULL RootCards)
		    then (SETQ RootCards (if NoDisplayFlg
						 then (LIST NIL)
					       else (NC.SelectNoteCards NIL NIL 
								    NC.SelectingBrowserSourceMenu 
									    Window 
		      "Please shift-select the Cards and/or Boxes the browser should start from."
									    T]
		(COND
		  ((EQ RootCards (QUOTE DON'T))
		    (NC.DeactivateCard Card)
		    (CLOSEW Window)
		    (RETURN)))
		(NC.HoldTTYProcess)
		[SETQ BrowserSpecs (NC.AskBrowserSpecs Window Card ListOfLinkLabels Depth 
							   BrowserFormat T (if (OR ParamList 
										     NoDisplayFlg)
									       then (QUOTE 
											  DONTASK]
		(COND
		  ((NULL BrowserSpecs)
		    (NC.DeactivateCard Card)
		    (CLOSEW Window)
		    (RETURN)))
		(SETQ ListOfLinkLabels (CAR BrowserSpecs))
		(SETQ Depth (CADR BrowserSpecs))
		(SETQ BrowserFormat (CADDR BrowserSpecs))
                                                             (* If user wants *GRAPH* format, i.e. virtual nodes 
							     eliminated, then set the flag)
		(if (FMEMB NC.*Graph*BrowserFormat BrowserFormat)
		    then (SETQ DropVirtualNodesFlg T))
		[SETQ SpecialBrowserSpecs (COND
		    (NC.SpecialBrowserSpecsFlg (NC.AskSpecialBrowserSpecs Window))
		    (T (create SPECIALBROWSERSPECS]
		(OR NoDisplayFlg (NC.PrintMsg Window T (CHARACTER 13)
						  "Computing browser graph. Please wait. ..."))
                                                             (* Create new browser hash array)
		(NC.GetBrowserHashArray Card)              (* Compute lattice breakdth-first starting from 
							     roots.)
		(SETQ Lattice (NC.GrowLinkLattice RootCards NIL ListOfLinkLabels Card Depth))
		(SETQ RootNodes (for RootCard in RootCards collect (NC.GetBrowserNodeID
									     Card RootCard)))
		(OR NoDisplayFlg (WINDOWPROP Window (QUOTE NoteCardObject)
						 Card))

          (* * Link destination id information stored in NodeLabel field into a LinkIcon for display)


		(for Node in Lattice bind NodeID (CrossFileLinkModePropList
						  ←
						  (LIST (fetch (Card NoteFile) of Card)
							  NIL))
		   eachtime (BLOCK)
		   do [replace (GRAPHNODE NODELABEL) of Node
			   with (LET (NewLink)
				       (if [AND (NOT (NC.CrossFileLinkCardP
							     (fetch (GRAPHNODE NODELABEL)
								of Node)))
						    (SETQ NewLink
						      (NC.MakeLink Window 
								     NC.BrowserContentsLinkLabel
								     (fetch (GRAPHNODE NODELABEL)
									of Node)
								     Card NIL NIL NIL NIL NIL
								     (NC.ComputeCrossFileLinkMode
								       (fetch (GRAPHNODE NODELABEL)
									  of Node)
								       CrossFileLinkModePropList 
								       Window]
					   then (NC.MakeLinkIcon NewLink)
					 else (NC.MakeCrossFileLinkIconStandIn
						  (fetch (GRAPHNODE NODELABEL) of Node]
                                                             (* Untouch each graph node so that next Recompute will
							     put fresh values on proplist.)
			(SETQ NodeID (fetch (GRAPHNODE NODEID) of Node))
			(NC.GraphNodeIDRemProp (NC.CoerceToGraphNodeID NodeID)
						 (QUOTE TouchedFlg))
			(NC.GraphNodeIDRemProp (NC.CoerceToGraphNodeID NodeID)
						 (QUOTE VisitedFlg)))
		(SETQ Graph (if (AND Lattice RootNodes)
				  then (LAYOUTGRAPH Lattice RootNodes (SUBST (QUOTE LATTICE)
										   
									  NC.*Graph*BrowserFormat 
										   BrowserFormat)
							(fetch (SPECIALBROWSERSPECS Font)
							   of SpecialBrowserSpecs)
							(fetch (SPECIALBROWSERSPECS MotherD)
							   of SpecialBrowserSpecs)
							(fetch (SPECIALBROWSERSPECS PersonalD)
							   of SpecialBrowserSpecs)
							(fetch (SPECIALBROWSERSPECS FamilyD)
							   of SpecialBrowserSpecs))
				else (create GRAPH)))
		(NC.SetBrowserLinksLegend Card (NC.MakeLinksLegend Graph Window 
								       DropVirtualNodesFlg))
		(OR NoDisplayFlg (NC.PrintMsg Window NIL "Done!"))
		(NC.SetSubstance Card Graph)
		(NC.SetBrowserLinkLabels Card (OR ListOfLinkLabels (LIST NC.SubBoxLinkLabel)))
		(NC.SetBrowserRoots Card RootCards)
		(NC.SetBrowserFormat Card BrowserFormat)
		(NC.SetBrowserDepth Card Depth)
		(NC.SetSpecialBrowserSpecs Card SpecialBrowserSpecs)
		(COND
		  (NoDisplayFlg (RETURN Card)))
		(WINDOWPROP Window (QUOTE GRAPH)
			      Graph)
		(NC.InstallTitleBarLeftMenu Window CardType)
		(NC.InstallTitleBarMiddleMenu Window CardType)
		(NC.RelayoutBrowserCard Window)
		(RETURN Window])

(NC.BringUpBrowserCard
  [LAMBDA (Card Substance Region/Position)                   (* rht: " 6-Feb-87 15:57")

          (* * Given a browser Substance, open a browser window and set it up to be a NoteCard with ID.)



          (* * rht 11/17/84: Now returns window.)



          (* * rht 9/11/85: Now checks for changed link icon display global params.)



          (* * rht 11/17/85: Now handles new card and Notefile objects.)



          (* * rht 2/1/86: Now restores any saved UID user data info stashed on card's prop list.)



          (* * fgh 2/5/86 Added call to NC.ApplySupersFn)



          (* * rht 2/14/86: Now rebuilds browser hash array.)



          (* * rht 2/28/86: Added WINDOWPROP for SCROLLFN and RESHAPEFN.)



          (* * rht 3/2/86: Took out call to NC.FetchBrowserHashArray.)



          (* * rht 4/5/86: Now only replaces graphnodes' TONODES' NODEID and DESTNODEID if they're non-nil.)



          (* * rht 5/5/86: Took out call to NC.SetupTitleBarMenu.)



          (* * rht&pmi 2/6/87: Moved call to NC.GraphLinkIconUpdateCheck in front of call to GraphCard's EditFn so as to 
	  remove "double display" problem.)


    (LET ((GraphNodes (fetch (GRAPH GRAPHNODES) of Substance))
	  Window OldUIDToNewUIDHashArray BrowserSavedLinkingInfo)

          (* * Restore any saved UID user data info stashed on card UID's prop list.)


         [if (SETQ BrowserSavedLinkingInfo (NC.FetchBrowserSavedLinkingInfo Card))
	     then (SETQ OldUIDToNewUIDHashArray (HASHARRAY 100 NIL (FUNCTION NC.MakeHashKey)
								 (FUNCTION NC.SameUIDP)))
		    (for BrowserSavedLinkingInfoForNode in BrowserSavedLinkingInfo
		       eachtime (BLOCK) bind SourceUID when (SETQ SourceUID
								      (
								   NC.NewBrowserNodeUIDFromOldUID
									(CAR 
								   BrowserSavedLinkingInfoForNode)
									GraphNodes 
									OldUIDToNewUIDHashArray))
		       do (for SavedLinkingInfo on (CDR BrowserSavedLinkingInfoForNode)
			       by (CDDR SavedLinkingInfo) eachtime (BLOCK)
			       do (NC.GraphNodeIDPutProp SourceUID (
							       NC.NewBrowserNodeUIDFromOldUID
							       (CAR SavedLinkingInfo)
							       GraphNodes OldUIDToNewUIDHashArray)
							     (CADR SavedLinkingInfo]
         (NC.SetBrowserSavedLinkingInfo Card NIL)

          (* * For each graph node corresponding to a notecard, hang the card object off the node id's prop list.)


         [for GraphNode in GraphNodes bind LinkIcon DestCard eachtime (BLOCK)
	    when (NC.LinkIconImageObjP (SETQ LinkIcon (fetch (GRAPHNODE NODELABEL)
							       of GraphNode)))
	    do (NC.GraphNodeIDPutProp (NC.CoerceToGraphNodeID GraphNode)
					  (QUOTE CardObject)
					  (SETQ DestCard (fetch (Link DestinationCard)
							      of (NC.FetchLinkFromLinkIcon 
											 LinkIcon]

          (* * Make a new browser hash array with the new graph node UIDs.)


         (NC.SetUserDataProp Card (QUOTE BrowserHashArray)
			       NIL)
         (NC.GetBrowserHashArray Card Substance)

          (* * For each graph node, fix the NODEID and DESTNODEID fields of each of its TONODES LinkParameters.)


         [for GraphNode in GraphNodes eachtime (BLOCK)
	    do (for ToNode in (fetch (GRAPHNODE TONODES) of GraphNode)
		    bind (ThisNodeID ← (NC.CoerceToGraphNodeID GraphNode)) eachtime (BLOCK)
		    when (EQ (CAR ToNode)
				 LINKPARAMS)
		    do (AND (LISTGET ToNode (QUOTE NODEID))
				(LISTPUT ToNode (QUOTE NODEID)
					   ThisNodeID))
			 (AND (LISTGET ToNode (QUOTE DESTNODEID))
				(LISTPUT ToNode (QUOTE DESTNODEID)
					   (NC.CoerceToGraphNodeID (CADR ToNode]

          (* * Bring up card and mess with its window.)


         (NC.GraphLinkIconUpdateCheck Card NIL Substance T)
         (SETQ Window (NC.ApplySupersFn EditFn Card Substance Region/Position))
         (NC.MakeLinksLegendMenu Window (NC.FetchBrowserLinksLegend Card))
                                                             (* Disable the old-style right button grapher editor 
							     menu.)
         (WINDOWPROP Window (QUOTE RIGHTBUTTONFN)
		       (FUNCTION NC.BrowserRightButtonFn))
         (WINDOWADDPROP Window (QUOTE SHRINKFN)
			  (FUNCTION NC.GraphCardShrinkFn))
         (WINDOWADDPROP Window (QUOTE REPAINTFN)
			  (FUNCTION NC.BrowserRepaintFn)
			  T)
         (WINDOWPROP Window (QUOTE SCROLLFN)
		       (FUNCTION NC.BrowserScrollFn))
         (WINDOWPROP Window (QUOTE RESHAPEFN)
		       (FUNCTION NC.BrowserReshapeFn))

          (* * I have to hang notecard's Card on window now in case REDISPLAYW runs and tries to get Card from window.)


         (WINDOWPROP Window (QUOTE NoteCardObject)
		       Card)                                 (* Check if link icon display global params have 
							     changed since last time card was up.
							     If so, fix graph nodes and redisplay.)
                                                             (* if (NC.GraphLinkIconUpdateCheck Card Window 
							     Substance T) then (REDISPLAYW Window))
     Window])

(NC.UpdateBrowserCard
  [LAMBDA (Window)                                           (* rht: " 4-Jun-87 11:50")

          (* * rht 10/14/84: Added call to DETACHALLWINDOWS to close any existing links legend window and prompt window.
	  Also added call to NC.MakeLinksLegend to make a new attached legend menu.)



          (* * rht 1/15/85: Put hooks for AddNode, AddLink, etc. so editing graph edits underlying structure.)



          (* * rht 2/14/85: Added ability to respecify roots and link labels before recomputing graph.)



          (* * rht 3/8/85: Modified to use new browser props stored on card's proplist as of release 1.2.)



          (* * rht 3/17/85: Now takes OnlyLayoutFlg argument. If set, then don't recompute lattice or ask about root nodes.)



          (* * rht 11/17/85: updated to handle new card and notefile objects.)



          (* * kirk 23Jan86 Changed to use NC.AskYesOrNo)



          (* * rht 2/7/86: Now gets and sets browser format, etc. via fetch/set fns.)



          (* * rht 3/7/86: Now only closes the Links legend menu attached window.)



          (* * rht 6/10/86: Moved code to delete links legend menu and code to make new browser hash array to after 
	  questioning user about respecifying roots.)



          (* * rht 11/1/86: Added NC.ProtectedCardOperation wrapper and check for ops in progress.)



          (* * pmi 12/5/86: Modified message to NC.SelectNoteCards to mention SHIFT-selection.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 12/16/86: Now checks that NC.MakeLink succeeded before creating a real link icon. If not, then make a 
	  standin for a cross file link icon.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation, removed DontCheckOpInProgressFlg)



          (* * rg 3/18/87 added NC.CardSelectionOperation wrapper)



          (* * rht 3/19/87: Fixed the part that calls NC.MakeLink so it really only rebuilds links if they've changed.)



          (* * rg 4/1/87 changed CANCELLED to DON'T)



          (* * rht 5/26/87: Now handles cross-file links properly, i.e. uses cross-file link standin in cases when 
	  GrowLinkLattice wasn't able to follow into the remote notefile.)


    (LET ((Card (NC.CoerceToCard Window)))
         (NC.ProtectedCardOperation
	   Card "Recompute Browser Card" NIL
	   (NCP.WithLockedCards
	     (PROG (LinkLabels RootCards RootNodes Lattice LinkIcon Graph GraphNodes NodeLabel 
				 BrowserSpecs BrowserFormat DropVirtualNodesFlg Depth 
				 SpecialBrowserSpecs OldLabelNodes OldRootCards)
		     (SETQ RootCards (NC.FetchBrowserRoots Card))
		     (NC.IfAllCardsFree
		       (NC.LockListOfCards RootCards "Update Browser Card")
		       (SETQ LinkLabels (NC.FetchBrowserLinkLabels Card))
		       [SETQ BrowserFormat (OR (NC.FetchBrowserFormat Card)
						   (QUOTE (LATTICE]
                                                             (* If user wants *GRAPH* format, i.e. virtual nodes 
							     eliminated, then set the flag)
		       (if (FMEMB NC.*Graph*BrowserFormat BrowserFormat)
			   then (SETQ DropVirtualNodesFlg T))
		       (SETQ Depth (OR (NC.FetchBrowserDepth Card)
					   999999))
		       (SETQ SpecialBrowserSpecs (OR (NC.FetchSpecialBrowserSpecs Card)
							 (create SPECIALBROWSERSPECS)))
		       [SETQ GraphNodes (fetch (GRAPH GRAPHNODES) of (SETQ Graph
									     (WINDOWPROP
									       Window
									       (QUOTE GRAPH]
                                                             (* Get new roots.)
		       [if (OR (NULL RootCards)
				   (NC.AskYesOrNo "Want to respecify roots? " "--" "No" T Window T 
						    NIL))
			   then (NC.BrowserFlipRoots Window Card GraphNodes (SETQ OldRootCards 
							   RootCards))
				  (SETQ RootCards (NC.SelectNoteCards NIL NIL 
								    NC.SelectingBrowserSourceMenu 
									  Window (CONCAT
									    
		      "Please shift-select the Cards and/or Boxes the browser should start from."
									    (CHARACTER 13)
									    
							       "(Current roots are highlighted.)")
									  T))
				  (NC.BrowserFlipRoots Window Card GraphNodes OldRootCards)
				  (COND
				    ((EQ RootCards (QUOTE DON'T))
				      (RETURN]             (* Get rid of the links legend menu attached window.)
		       (for Win in (ATTACHEDWINDOWS Window) when (WINDOWPROP Win
										       (QUOTE
											 
										  LINKSLEGENDWINP))
			  do (DETACHWINDOW Win)
			       (CLOSEW Win))               (* Smash the current hash array, putting a fresh one 
							     in its place.)
		       (NC.GetBrowserHashArray Card)
		       (NC.PrintMsg Window T (CHARACTER 13)
				      "Computing browser graph. Please wait. ...")
                                                             (* Compute lattice breadth-first from the roots.)
		       (SETQ Lattice (NC.GrowLinkLattice RootCards NIL LinkLabels Card Depth))
		       (SETQ RootNodes (for RootCard in RootCards collect (
									      NC.GetBrowserNodeID
										    Card RootCard)))
		       (NC.SetPropListDirtyFlg Card T)     (* Remove all links that are in the old browser graph 
							     but not in the new one)
		       [for Node in GraphNodes eachtime (BLOCK)
			  unless [for LatticeNode in Lattice bind (CardForNode
									    ←
									    (
									 NC.CardFromBrowserNodeID
									      (
									   NC.CoerceToGraphNodeID
										Node)))
				      thereis (NC.SameCardP CardForNode (
								  NC.CardFromBrowserNodeID
								  (NC.CoerceToGraphNodeID 
										      LatticeNode]
			  do (LET ((NodeLabel (fetch (GRAPHNODE NODELABEL) of Node)))
				    (COND
				      ((NC.LinkIconImageObjP NodeLabel)
					(NC.DeleteLink (NC.FetchLinkFromLinkIcon NodeLabel)
							 T T))
				      ((STRINGP NodeLabel)
                                                             (* Collect the label nodes from the old browser.)
					(SETQ OldLabelNodes (CONS Node OldLabelNodes]
                                                             (* Create Links for all nodes in the new browser graph
							     but not in the old one.)
		       [for Node in Lattice eachtime (BLOCK)
			  bind (CrossFileLinkModePropList ← (LIST (fetch (Card NoteFile)
									 of Card)
								      NIL))
			  do
			   (LET [(NodeID (fetch (GRAPHNODE NODEID) of Node))
				 (OldNode (for GraphNode in GraphNodes
					     bind (CardForNode ← (NC.CardFromBrowserNodeID
								   (NC.CoerceToGraphNodeID Node)))
					     when (NC.SameCardP CardForNode (
								      NC.CardFromBrowserNodeID
								      (NC.CoerceToGraphNodeID
									GraphNode)))
					     do (RETURN GraphNode]
			        [if OldNode
				    then (replace (GRAPHNODE NODELABEL) of Node
					      with (fetch (GRAPHNODE NODELABEL) of OldNode))
				  else
				   (replace (GRAPHNODE NODELABEL) of Node
				      with
				       (LET (NewLink)
					    (if [AND (NOT (NC.CrossFileLinkCardP
								  (fetch (GRAPHNODE NODELABEL)
								     of Node)))
							 (SETQ NewLink
							   (NC.MakeLink Window 
								      NC.BrowserContentsLinkLabel
									  (fetch (GRAPHNODE 
											NODELABEL)
									     of Node)
									  Card NIL NIL NIL NIL NIL
									  (
								      NC.ComputeCrossFileLinkMode
									    (fetch (GRAPHNODE
										       NODELABEL)
									       of Node)
									    CrossFileLinkModePropList 
									    Window]
						then (NC.MakeLinkIcon NewLink)
					      else (NC.MakeCrossFileLinkIconStandIn
						       (fetch (GRAPHNODE NODELABEL) of Node]
                                                             (* Untouch each graph node so that next Recompute will
							     put fresh values on proplist.)
			        (NC.GraphNodeIDRemProp NodeID (QUOTE TouchedFlg))
			        (NC.GraphNodeIDRemProp NodeID (QUOTE VisitedFlg]
                                                             (* Throw in the label nodes from the old browser.)
		       (SETQ Lattice (NCONC Lattice OldLabelNodes))
                                                             (* For each old label node, take away nonexistent 
							     fromnodes and save the label nodes that no longer have
							     any from nodes.)
		       (for OldLabelNode in OldLabelNodes eachtime (BLOCK)
			  do (replace (GRAPHNODE FROMNODES) of OldLabelNode
				  with (for FromNodeID in (fetch (GRAPHNODE FROMNODES)
								   of OldLabelNode)
					    bind FromNode eachtime (BLOCK)
					    when (SETQ FromNode (FASSOC FromNodeID Lattice))
					    collect        (* If the From node isn't a label node, then add to 
							     its Tonode list.)
						      [if (NC.LinkIconImageObjP
							      (fetch (GRAPHNODE NODELABEL)
								 of FromNode))
							  then (replace (GRAPHNODE TONODES)
								    of FromNode
								    with
								     (CONS (fetch (GRAPHNODE
											NODEID)
										of OldLabelNode)
									     (fetch (GRAPHNODE
											TONODES)
										of FromNode]
						      FromNodeID))
                                                             (* For the old label node's ToNodes, just need to 
							     remove any for ToNodes that no longer exist.)
			       (replace (GRAPHNODE TONODES) of OldLabelNode
				  with (for ToNodeID in (fetch (GRAPHNODE TONODES)
								 of OldLabelNode)
					    bind ToNode eachtime (BLOCK)
					    when (SETQ ToNode (FASSOC ToNodeID Lattice))
					    collect        (* If the To node isn't a label node, then add to its 
							     FromNode list.)
						      [if (NC.LinkIconImageObjP
							      (fetch (GRAPHNODE NODELABEL)
								 of ToNode))
							  then (replace (GRAPHNODE FROMNODES)
								    of ToNode
								    with
								     (CONS (fetch (GRAPHNODE
											NODEID)
										of OldLabelNode)
									     (fetch (GRAPHNODE
											FROMNODES)
										of ToNode]
						      ToNodeID)))
                                                             (* Layout graph, including as roots any non-virtual 
							     nodes with no from nodes to avoid disconnected 
							     graphs.)
		       (SETQ Graph (if (AND Lattice RootNodes)
					 then (LAYOUTGRAPH
						  Lattice
						  (for Node in Lattice bind NodeID
						     eachtime (BLOCK)
								(SETQ NodeID
								  (OR (NC.CoerceToGraphNodeID
									  Node)
									(fetch (GRAPHNODE NODEID)
									   of Node)))
						     when (OR (FMEMB NodeID RootNodes)
								  (NULL (fetch (GRAPHNODE 
											FROMNODES)
									     of Node)))
						     collect NodeID)
						  (SUBST (QUOTE LATTICE)
							   NC.*Graph*BrowserFormat BrowserFormat)
						  (fetch (SPECIALBROWSERSPECS Font) of 
									      SpecialBrowserSpecs)
						  (fetch (SPECIALBROWSERSPECS MotherD)
						     of SpecialBrowserSpecs)
						  (fetch (SPECIALBROWSERSPECS PersonalD)
						     of SpecialBrowserSpecs)
						  (fetch (SPECIALBROWSERSPECS FamilyD)
						     of SpecialBrowserSpecs))
				       else (create GRAPH)))
                                                             (* Build links legend and fix up TONODES in the 
							     graph.)
		       (NC.SetBrowserLinksLegend Card (NC.MakeLinksLegend Graph Window 
									      DropVirtualNodesFlg))
		       (NC.SetBrowserRoots Card RootCards)
		       (NC.SetBrowserDepth Card Depth)
		       (WINDOWPROP Window (QUOTE GRAPH)
				     Graph)
		       (NC.RelayoutBrowserCard Window])

(NC.RelayoutBrowserCard
  [LAMBDA (Window)                                           (* rht: "13-May-87 10:54")

          (* * Called from the middle button of a browser or structeditbrowser card. This lays out and displays the browser, 
	  but does not recompute the nodes.)



          (* * rht 11/17/85: updated to handle new notefile and card objects.)



          (* * rht 2/7/86: Now gets browser format, etc. via fetch/set fns.)



          (* * rht 2/28/86: Added WINDOWPROP for SCROLLFN and RESHAPEFN.)



          (* * rht 5/8/86: Added calls to rig title bar properly.)



          (* * fgh 6/30/86 Added NC.GRAPHERCOPYBUTTONEVENTFN to SHOWGRAPH call)



          (* * rht 11/1/86: Added NC.ProtectedCardOperation wrapper and check for ops in progress.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation, removed DontCheckOpInProgressFlg)


    (LET ((Card (NC.CoerceToCard Window)))
         (NC.ProtectedCardOperation
	   Card "Relayout Browser Card" NIL
	   (PROG (RootCards RootNodeIDs OldToNodePairs Graph GraphNodes BrowserFormat 
			      DropVirtualNodesFlg SpecialBrowserSpecs)
	           (NC.PrintMsg Window T "Laying out graph ...")
	           (SETQ RootCards (NC.FetchBrowserRoots Card))
	           [SETQ BrowserFormat (OR (NC.FetchBrowserFormat Card)
					       (QUOTE (LATTICE]
                                                             (* If user wants *GRAPH* format, i.e. virtual nodes 
							     eliminated, then set the flag)
	           (if (FMEMB NC.*Graph*BrowserFormat BrowserFormat)
		       then (SETQ DropVirtualNodesFlg T))
	           (SETQ SpecialBrowserSpecs (OR (CAR (NC.FetchSpecialBrowserSpecs Card))
						     (create SPECIALBROWSERSPECS)))
	           [SETQ GraphNodes (fetch (GRAPH GRAPHNODES) of (SETQ Graph
									 (WINDOWPROP Window
										       (QUOTE
											 GRAPH]
                                                             (* Create hash array if haven't already.)
	           (NC.GetBrowserHashArray Card Graph)     (* check graph node size against image box size.)
	           (NC.GraphLinkIconUpdateCheck Card Window Graph NIL)

          (* Save the TONODES values of the nodes so can replace later after LAYOUTGRAPH call. At the same time, throw away 
	  all the link params info in TONODES field.)


	           [SETQ OldToNodePairs (for Node in GraphNodes bind ToNodes eachtime
										      (BLOCK)
					     collect
					      (PROG1 [CONS (fetch (GRAPHNODE NODEID)
								  of Node)
							       (APPEND (SETQ ToNodes
									   (fetch (GRAPHNODE 
											  TONODES)
									      of Node]
						       (replace (GRAPHNODE TONODES) of Node
							  with (for ToNode in ToNodes
								    collect
								     (if (EQ (CAR ToNode)
										 LINKPARAMS)
									 then (CADR ToNode)
								       else ToNode]
	           (SETQ RootNodeIDs (for RootCard in RootCards collect (NC.GetBrowserNodeID
										  Card RootCard)))
	           (NC.SetPropListDirtyFlg Card T)         (* Layout graph, including as roots any non-virtual 
							     nodes with no from nodes to avoid disconnected 
							     graphs.)
	           (SETQ Graph (if GraphNodes
				     then (LAYOUTGRAPH
					      GraphNodes
					      (for Node in GraphNodes bind NodeID
						 eachtime (BLOCK)
							    (SETQ NodeID (fetch (GRAPHNODE NODEID)
									      of Node))
						 when (OR (AND (NULL (fetch (GRAPHNODE
											FROMNODES)
										of Node))
								     (NOT (LISTP NodeID)))
							      (FMEMB NodeID RootNodeIDs))
						 collect NodeID)
					      (SUBST (QUOTE LATTICE)
						       NC.*Graph*BrowserFormat BrowserFormat)
					      (fetch (SPECIALBROWSERSPECS Font) of 
									      SpecialBrowserSpecs)
					      (fetch (SPECIALBROWSERSPECS MotherD) of 
									      SpecialBrowserSpecs)
					      (fetch (SPECIALBROWSERSPECS PersonalD) of 
									      SpecialBrowserSpecs)
					      (fetch (SPECIALBROWSERSPECS FamilyD) of 
									      SpecialBrowserSpecs))
				   else (create GRAPH)))

          (* Replace the TONODES fields of the Graph nodes by their pre-LAYOUTGRAPH values. Also throw away any nodes that 
	  didn't appear in the old graph.)


	           (if Graph
		       then (replace (GRAPH GRAPHNODES) of Graph
				 with (for Node in (fetch (GRAPH GRAPHNODES) of Graph)
					   bind AssocPair eachtime (BLOCK)
					   when (SETQ AssocPair (FASSOC (fetch (GRAPHNODE
											 NODEID)
										 of Node)
									      OldToNodePairs))
					   collect (replace (GRAPHNODE TONODES) of Node
							with (CDR AssocPair))
						     (if DropVirtualNodesFlg
							 then (replace (GRAPHNODE NODEBORDER)
								   of Node with NIL))
                                                             (* Throw away LINKPARAMS junk from the FromNodes that 
							     LAYOUTGRAPH stuck in.)
						     (replace (GRAPHNODE FROMNODES) of Node
							with (for FromNode
								  in (fetch (GRAPHNODE FROMNODES)
									  of Node)
								  eachtime (BLOCK)
								  collect
								   (if (EQ (CAR FromNode)
									       LINKPARAMS)
								       then (CADR FromNode)
								     else FromNode)))
						     Node)))
	           (SHOWGRAPH Graph Window (FUNCTION NC.GraphCardLeftButtonFn)
				(FUNCTION NC.GraphCardMiddleButtonFn)
				NIL T (FUNCTION NC.GRAPHERCOPYBUTTONEVENTFN))

          (* * Have to reset windowprops since SHOWGRAPH messes with them.)

                                                             (* Disable the old-style right button grapher editor 
							     menu.)
	           (WINDOWPROP Window (QUOTE RIGHTBUTTONFN)
				 (FUNCTION NC.BrowserRightButtonFn))
	           (WINDOWADDPROP Window (QUOTE REPAINTFN)
				    (FUNCTION NC.BrowserRepaintFn)
				    T)
	           (WINDOWPROP Window (QUOTE SCROLLFN)
				 (FUNCTION NC.BrowserScrollFn))
	           (WINDOWPROP Window (QUOTE RESHAPEFN)
				 (FUNCTION NC.BrowserReshapeFn))
	           (NC.SetSubstance Card (WINDOWPROP Window (QUOTE GRAPH)))
	           (NC.MarkCardDirty Card)
	           (NC.InstallTitleBarButtonEventFn Window (FUNCTION NC.TitleBarButtonEventFn))
	           (NC.InstallCopyButtonEventFn Window)
	           (NC.ClearMsg Window T])

(NC.ConnectNodesInBrowser
  [LAMBDA (Window)                                           (* rht: "29-May-87 00:13")

          (* * Draw any links, from the current link set, between any pairs of nodes currently being shown in the browser.)



          (* * rht 2/7/86: Now gets and sets browser format, etc. via fetch/set fns. Also fixed one last old call to 
	  GETPROPLIST on a NodeID.)



          (* * rht 3/2/86: Added WINDOWPROP for SCROLLFN and RESHAPEFN.)



          (* * fgh 5/21/86 Updated reinstallation of title bar menus after SHOWGRAPH to use new title bar menu mechanism.)



          (* * rht 6/10/86: Now calls NC.ShowBrowserGraph.)



          (* * rht 11/1/86: Added NC.ProtectedCardOperation wrapper and check for ops in progress.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation, removed DontCheckOpInProgressFlg)



          (* * rht 5/28/87: Modified to handle cross-file links.)


    (LET ((Card (NC.CoerceToCard Window)))
         (NC.ProtectedCardOperation
	   Card "Reconnect Browser Card" NIL
	   (PROG (LinkLabels Graph GraphNodes BrowserFormat DropVirtualNodesFlg NodeIDs)
	           (SETQ LinkLabels (NC.FetchBrowserLinkLabels Card))
	           (SETQ BrowserFormat (NC.FetchBrowserFormat Card))
                                                             (* If user wants *GRAPH* format, i.e. virtual nodes 
							     eliminated, then set the flag)
	           (if (FMEMB NC.*Graph*BrowserFormat BrowserFormat)
		       then (SETQ DropVirtualNodesFlg T))
	           [SETQ GraphNodes (fetch (GRAPH GRAPHNODES) of (SETQ Graph
									 (WINDOWPROP Window
										       (QUOTE
											 GRAPH]
                                                             (* Create hash array if haven't already.)
	           (NC.GetBrowserHashArray Card Graph)     (* check graph node size against image box size.)
	           (NC.GraphLinkIconUpdateCheck Card Window Graph NIL)
                                                             (* These are the workhorse loops that rebuild the 
							     TONODES of each nonvirtual node.)
                                                             (* First smash all the nodeID's proplists and 
							     accumulate nodeIDs.)
	           (SETQ NodeIDs (for Node in GraphNodes bind NodeID eachtime (BLOCK)
				      when (NC.LinkIconImageObjP (fetch (GRAPHNODE NODELABEL)
									of Node))
				      collect (NC.SmashGraphNodeIDProps (SETQ NodeID
									      (
									   NC.CoerceToGraphNodeID
										Node)))
						NodeID))     (* Throw away duplicates obtained from virtual nodes.)
	           (SETQ NodeIDs (INTERSECTION NodeIDs NodeIDs))

          (* Next accumulate all linktypes on the from node's proplist using the To node's graphnodeID as prop name.
	  We do the analogous thing for backward links, but notice that we ignore backward linktypes that also appear in the 
	  list in their forward version.)


	           (for NodeID in NodeIDs bind RealCard
		      do (for Link in (NC.RetrieveToLinks (SETQ RealCard (
								      NC.CardFromBrowserNodeID
								      NodeID)))
			      bind DestNodeID eachtime (BLOCK) when (NC.LinkLabelP Link 
										       LinkLabels)
			      when [LET ((DestCard (fetch (Link DestinationCard) of Link)))
				          (SETQ DestNodeID (NC.GetBrowserNodeID
					      Card
					      (if (NC.CrossFileLinkCardP DestCard)
						  then (OR (NC.GetCrossFileLinkDestCard 
											 DestCard 
											   Window)
							       DestCard)
						else DestCard)))
				          (SETQ DestNodeID (for ID in NodeIDs
								when (NC.SameUIDP DestNodeID ID)
								do (RETURN ID]
			      do (NC.UIDAddProp NodeID DestNodeID (fetch (Link Label)
									 of Link)
						    T))
			   (for Link in (NC.RetrieveFromLinks RealCard) bind SourceNodeID
			      eachtime (BLOCK) when (AND (NC.ReverseLinkLabelP Link 
										       LinkLabels)
								 (NOT (NC.LinkLabelP Link 
										       LinkLabels)))
			      when [LET ((SourceCard (fetch (Link SourceCard) of Link)))
				          (SETQ SourceNodeID (NC.GetBrowserNodeID
					      Card
					      (if (NC.CrossFileLinkCardP SourceCard)
						  then (OR (NC.GetCrossFileLinkDestCard 
										       SourceCard 
											   Window)
							       SourceCard)
						else SourceCard)))
				          (SETQ SourceNodeID (for ID in NodeIDs
								  when (NC.SameUIDP SourceNodeID 
											ID)
								  do (RETURN ID]
			      do (NC.UIDAddProp SourceNodeID NodeID (fetch (Link Label)
									   of Link)
						    T)))
	           [for Node in GraphNodes bind NodeID OldToNodeIDs eachtime (BLOCK)
		      unless (LISTP (SETQ NodeID (fetch (GRAPHNODE NODEID) of Node)))
		      when (NC.LinkIconImageObjP (fetch (GRAPHNODE NODELABEL) of Node))
		      do                                   (* Accumulate the old NodeIDs, possibly virtual, from 
							     the TONODES list.)
			   (SETQ OldToNodeIDs (for ToNode in (fetch (GRAPHNODE TONODES)
								      of Node)
						   collect (if (EQ (CAR ToNode)
									 LINKPARAMS)
								 then (CADR ToNode)
							       else ToNode)))

          (* The trick here is to use a virtual node for this ToNode if one was used before, otherwise just the ToNodeID.
	  Also throw in the label nodes that were in the TONODES list before.)


			   (replace (GRAPHNODE TONODES) of Node
			      with (NCONC (for ToNodeID on (
							 NC.ComputeBrowserSavedLinkingInfoForNode
								     NodeID)
						 by (CDDR ToNodeID) eachtime (BLOCK)
						 collect (OR (for OldToNodeID in OldToNodeIDs
								    thereis
								     (AND (LISTP OldToNodeID)
									    (EQ (CAR ToNodeID)
										  (CAR OldToNodeID))
									    OldToNodeID))
								 (CAR ToNodeID)))
					      (for ToNodeID in OldToNodeIDs eachtime (BLOCK)
						 unless (NC.SameCardP Card (
									 NC.CardFromBrowserNodeID
									    (NC.CoerceToGraphNodeID
									      ToNodeID)))
						 collect ToNodeID]
	           (NC.RebuildFromNodesInGraph GraphNodes)
	           (NC.SetBrowserLinksLegend Card (NC.MakeLinksLegend Graph Window 
									  DropVirtualNodesFlg))
                                                             (* Display the graph.)
	           (NC.ShowBrowserGraph Graph Window)
	           (NC.SetSubstance Card (WINDOWPROP Window (QUOTE GRAPH)))
	           (NC.MarkCardDirty Card)
	           (NC.ClearMsg Window T])

(NC.UnconnectNodesInBrowser
  [LAMBDA (Window)                                           (* Randy.Gobbel " 4-Mar-87 13:51")

          (* * Remove all the links in the browser.)



          (* * rht 11/17/85: Now handles new card and notefile objects.)



          (* * rht 2/7/86: Now gets and sets browser format, etc. via fetch/set fns.)



          (* * fgh 5/21/86 Updated reinstallation of title bar menus after SHOWGRAPH to use new title bar menu mechanism.)



          (* * rht 6/10/86: Now calls NC.ShowBrowserGraph.)



          (* * rht 11/1/86: Added NC.ProtectedCardOperation wrapper and check for ops in progress.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation, removed DontCheckOpInProgressFlg)


    (LET ((Card (NC.CoerceToCard Window)))
         (NC.ProtectedCardOperation Card "Unconnect Browser Card" NIL
				    (PROG (Graph GraphNodes BrowserFormat DropVirtualNodesFlg)
					    (SETQ BrowserFormat (NC.FetchBrowserFormat Card))
                                                             (* If user wants *GRAPH* format, i.e. virtual nodes 
							     eliminated, then set the flag)
					    (if (FMEMB NC.*Graph*BrowserFormat BrowserFormat)
						then (SETQ DropVirtualNodesFlg T))
					    [SETQ GraphNodes (fetch (GRAPH GRAPHNODES)
								  of (SETQ Graph
									 (WINDOWPROP Window
										       (QUOTE
											 GRAPH]
                                                             (* smash all the nodeID's proplists and TONODES 
							     fields.)
					    (for Node in GraphNodes bind NodeID
					       unless [PROGN (BLOCK)
								 (LISTP (SETQ NodeID
									    (fetch (GRAPHNODE
										       NODEID)
									       of Node]
					       do (NC.SmashGraphNodeIDProps NodeID)
						    (replace (GRAPHNODE TONODES) of Node
						       with NIL)
						    (replace (GRAPHNODE FROMNODES) of Node
						       with NIL))
					    (NC.MakeLinksLegend Graph Window DropVirtualNodesFlg)
                                                             (* Display the graph.)
					    (NC.ShowBrowserGraph Graph Window)
					    (NC.SetSubstance Card (WINDOWPROP Window
										  (QUOTE GRAPH)))
					    (NC.MarkCardDirty Card)
					    (NC.SetBrowserLinksLegend Card NIL)
					    (NC.ClearMsg Window T])

(NC.ExpandBrowserNode
  [LAMBDA (Window)                                           (* rht: " 4-Jun-87 11:50")

          (* * Ask user to choose a node in the browser and recompute the part of the lattice under that node to the given 
	  depth. And relayout the graph. The code is just a modification of the NC.UpdateBrowserCard code.)



          (* * rht 2/7/86: Now gets and sets browser format, etc. via fetch/set fns.)



          (* * rht 6/10/86: No longer does relayout after expand. Uses NC.LayoutNewBrowserNodes to compute proper locations 
	  of new nodes. Also calls NC.ShowBrowserGraph.)



          (* * rht 11/1/86: Added NC.ProtectedCardOperation wrapper and check for ops in progress.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation, removed DontCheckOpInProgressFlg)



          (* * rht 5/26/87: Now handles cross-file links properly, i.e. uses cross-file link standin in cases when 
	  GrowLinkLattice wasn't able to follow into the remote notefile.)


    (LET ((Card (NC.CoerceToCard Window)))
         (NC.ProtectedCardOperation
	   Card "Expand Node of Browser Card" NIL
	   (PROG (NodeToExpand LinkLabels RootCards RootNodes Lattice LinkIcon OldToNodePairs Graph 
				 GraphNodes NodeLabel OldNode Link BrowserSpecs BrowserFormat 
				 DropVirtualNodesFlg Depth SpecialBrowserSpecs SavedLabelNodes 
				 NewNodes)
	           (SETQ RootCards (NC.FetchBrowserRoots Card))
	           (SETQ LinkLabels (NC.FetchBrowserLinkLabels Card))
	           (SETQ BrowserFormat (NC.FetchBrowserFormat Card))
                                                             (* If user wants *GRAPH* format, i.e. virtual nodes 
							     eliminated, then set the flag)
	           (if (FMEMB NC.*Graph*BrowserFormat BrowserFormat)
		       then (SETQ DropVirtualNodesFlg T))
	           (SETQ SpecialBrowserSpecs (OR (NC.FetchSpecialBrowserSpecs Card)
						     (create SPECIALBROWSERSPECS)))
	           [SETQ GraphNodes (fetch (GRAPH GRAPHNODES) of (SETQ Graph
									 (WINDOWPROP Window
										       (QUOTE
											 GRAPH]
                                                             (* If there aren't any nodes in graph, then get out 
							     pronto.)
	           (if (NULL GraphNodes)
		       then (NC.PrintMsg Window T "No nodes to expand.")
			      (DISMISS 1000)
			      (NC.ClearMsg Window T)
			      (RETURN NIL))                (* Create hash array if haven't already.)
	           (NC.GetBrowserHashArray Card Graph)
	           (NC.PrintMsg Window T "Pick node to expand." (CHARACTER 13))
                                                             (* Note call to the grapher function READ/NODE to 
							     select a graph node.)
	           (SETQ NodeToExpand (READ/NODE GraphNodes Window))
                                                             (* Can't expand a label node.)
	           (if (NOT (NC.LinkIconImageObjP (fetch (GRAPHNODE NODELABEL) of 
										     NodeToExpand)))
		       then (NC.PrintMsg NIL T "Sorry, can't expand a label node.")
			      (FLASHW PROMPTWINDOW)
			      (NC.ClearMsg Window T)
			      (RETURN))
	           (SETQ Depth (MKATOM (NC.AskUser "Depth to expand (type integer or INF): " 
							 "--"
							 1 T Window NIL NIL T)))
	           (COND
		     ((EQ Depth (QUOTE INF))
		       (SETQ Depth MAX.FIXP))
		     ((NOT (AND (FIXP Depth)
				    (GREATERP Depth 0)))
		       (NC.PrintMsg Window T "Depth must be an integer greater than 0 or INF.")
		       (RETURN)))
	           (NC.PrintMsg Window T (CHARACTER 13)
				  "Augmenting browser graph. Please wait. ...")
                                                             (* Save the nodes pointed to by the chosen node that 
							     are label nodes. GrowLinkLattice will trash those, so 
							     we restore afterwards.)
	           (SETQ SavedLabelNodes (for ToNode in (fetch (GRAPHNODE TONODES)
								 of NodeToExpand)
					      eachtime (BLOCK)
					      when (AND (NOT (EQ (CAR ToNode)
									 LINKPARAMS))
							    (NOT (NC.LinkIconImageObjP ToNode)))
					      collect ToNode))
                                                             (* Increase link lattice from chosen node to given 
							     depth.)
	           (SETQ Lattice (NC.GrowLinkLattice (LIST (NC.CardFromBrowserNodeID
								   (fetch (GRAPHNODE NODEID)
								      of NodeToExpand)))
							 (APPEND GraphNodes)
							 LinkLabels Card Depth))
	           [AND SavedLabelNodes (replace (GRAPHNODE TONODES) of NodeToExpand
					     with (APPEND SavedLabelNodes (fetch (GRAPHNODE
											 TONODES)
										 of NodeToExpand]
	           (SETQ RootNodes (for RootCard in RootCards collect (NC.GetBrowserNodeID
										Card RootCard)))
	           (NC.SetPropListDirtyFlg Card T)         (* Create Links for all nodes in the new browser graph
							     but not in the old one.)
	           [for Node in Lattice bind NodeID (CrossFileLinkModePropList
						     ←
						     (LIST (fetch (Card NoteFile) of Card)
							     NIL))
		      do (COND
			     ((SETQ OldNode (FASSOC (SETQ NodeID (OR (NC.CoerceToGraphNodeID
									       Node)
									     (fetch (GRAPHNODE
											NODEID)
										of Node)))
							GraphNodes))
			       (replace (GRAPHNODE NODELABEL) of Node with (fetch
										   (GRAPHNODE 
											NODELABEL)
										    of OldNode)))
			     (T [replace (GRAPHNODE NODELABEL) of Node
				   with (LET (NewLink)
					       (if [AND (NOT (NC.CrossFileLinkCardP
								     (fetch (GRAPHNODE NODELABEL)
									of Node)))
							    (SETQ NewLink
							      (NC.MakeLink
								Window NC.BrowserContentsLinkLabel
								(fetch (GRAPHNODE NODELABEL)
								   of Node)
								Card NIL NIL NIL NIL NIL
								(NC.ComputeCrossFileLinkMode
								  (fetch (GRAPHNODE NODELABEL)
								     of Node)
								  CrossFileLinkModePropList Window]
						   then (NC.MakeLinkIcon NewLink)
						 else (NC.MakeCrossFileLinkIconStandIn
							  (fetch (GRAPHNODE NODELABEL)
							     of Node]
                                                             (* Make a list of all new nodes.)
				(push NewNodes Node)))     (* Throw away virtual node info.)
			   (AND NodeID (replace (GRAPHNODE NODEID) of Node with NodeID)) 
                                                             (* Untouch each graph node so that next Recompute will
							     put fresh values on proplist.)
			   (NC.GraphNodeIDRemProp NodeID (QUOTE TouchedFlg))
			   (NC.GraphNodeIDRemProp NodeID (QUOTE VisitedFlg)) 
                                                             (* Smash all the unnecessary junk off existing nodes, 
							     letting LAYOUTGRAPH and NC.MakeLinksLegend recompute.)
			   (replace (GRAPHNODE TONODES) of Node
			      with (for ToNode in (fetch (GRAPHNODE TONODES) of Node)
					bind ToNodeID eachtime (BLOCK)
					collect (if (SETQ ToNodeID (NC.CoerceToGraphNodeID
							    ToNode))
						      then 
                                                             (* Throw away link parameterlist info.)
                                                             (* Throw away link dashing info.)
							     (NC.GraphNodeIDPutProp
							       NodeID ToNodeID
							       (for LabelPair
								  in (NC.GraphNodeIDGetProp
									 NodeID ToNodeID)
								  collect (OR (CAR LabelPair)
										  LabelPair)))
							     (NC.GraphNodeIDPutProp
							       ToNodeID NodeID
							       (for LabelPair
								  in (NC.GraphNodeIDGetProp
									 ToNodeID NodeID)
								  collect (OR (CAR LabelPair)
										  LabelPair)))
							     ToNodeID
						    else ToNode]
                                                             (* LAYOUTGRAPH doesn't like duplicate nodes.
							     These get created when virtual nodes are turned into 
							     regular nodes.)
	           (SETQ Lattice (NC.RemoveDuplicateNodesFromGraph Lattice))
	           (NC.RebuildFromNodesInGraph Lattice)
	           (AND NewNodes (NC.LayoutNewBrowserNodes NodeToExpand NewNodes BrowserFormat 
							       SpecialBrowserSpecs))
	           (replace (GRAPH GRAPHNODES) of Graph with Lattice)
                                                             (* Build links legend and fix up TONODES in the 
							     graph.)
	           (NC.SetBrowserLinksLegend Card (NC.MakeLinksLegend Graph Window 
									  DropVirtualNodesFlg))
	           (WINDOWPROP Window (QUOTE GRAPH)
				 Graph)                      (* Display the graph.)
	           (NC.ShowBrowserGraph Graph Window)
	           (NC.SetSubstance Card Graph)
	           (NC.MarkCardDirty Card)
	           (NC.ClearMsg Window T])

(NC.AskBrowserSpecs
  [LAMBDA (MainWindow BrowserCard OldLinkLabels OldDepth OldFormat CreatingBrowserFlg Don'tAskFlg)
                                                             (* pmi: " 2-Apr-87 10:51")

          (* * Puts up the big stylesheet asking user about link types, depth, browser format, etc. The stylesheet returns a 
	  list of 5 things: forward links, backward links, depth, format, and orientation. The last two are smashed together 
	  to form a browserformat and the first two are nconc'ed together. Thus we return a list of 3 things: links, depth, 
	  and browserformat.)



          (* * rht 4/1/85: Now takes Don'tAskFlg arg for when we don't want to ask the user for browser specs.)



          (* * rht 11/17/85: Updated for new card and notefile objects.)



          (* * pmi 4/2/87: Added NC.MenuFont to all menus.)


    (DECLARE (GLOBALVARS NC.MenuFont))
    (PROG ((LinkLabels (NC.RetrieveLinkLabels (fetch (Card NoteFile) of BrowserCard)
						  T))
	     Position Choices ReverseFlg)
	    [if Don'tAskFlg
		then (RETURN (LIST (OR OldLinkLabels LinkLabels)
					 (OR OldDepth 99999)
					 (OR OldFormat (QUOTE (LATTICE]
	    [SETQ Position (AND (WINDOWP MainWindow)
				    (create POSITION
					      XCOORD ← (fetch (REGION LEFT)
							  of (WINDOWPROP MainWindow (QUOTE
									       REGION)))
					      YCOORD ← (fetch (REGION TOP) of (WINDOWREGION
										    MainWindow]
	    (if CreatingBrowserFlg
		then (SETQ OldLinkLabels LinkLabels))
	    (SETQ ReverseFlg (EQ (CADDR OldFormat)
				     (QUOTE REVERSE)))     (* The stylesheet is in a global var.
							     We only need to provide its position, items, and 
							     selections.)
	    (STYLE.PROP NC.BrowserSpecsStylesheet (QUOTE POSITION)
			  Position)
	    (STYLE.PROP NC.BrowserSpecsStylesheet (QUOTE ITEMS)
			  (LIST (create MENU
					    ITEMS ← LinkLabels
					    MENUFONT ← NC.MenuFont)
				  (create MENU
					    ITEMS ← (for Link in LinkLabels
						       collect (PACK* (QUOTE ←)
									  Link))
					    MENUFONT ← NC.MenuFont)
				  (create MENU
					    ITEMS ←
					    (QUOTE (0 1 2 3 4 5 6 7 8 9 INF))
					    MENUFONT ← NC.MenuFont)
				  (create MENU
					    ITEMS ← NC.BrowserFormatOptions
					    MENUFONT ← NC.MenuFont)
				  (create MENU
					    ITEMS ← (QUOTE (Horizontal Vertical Reverse/Horizontal 
									 Reverse/Vertical))
					    MENUFONT ← NC.MenuFont)))
	    [STYLE.PROP NC.BrowserSpecsStylesheet (QUOTE SELECTIONS)
			  (LIST (for Label in OldLinkLabels when (NEQ (NTHCHAR Label 1)
										(QUOTE ←))
				     collect Label)
				  (for Label in OldLinkLabels when (EQ (NTHCHAR Label 1)
									       (QUOTE ←))
				     collect Label)
				  (if (OR (NOT (FIXP OldDepth))
					      (IGREATERP OldDepth 9)
					      (ILESSP OldDepth 0))
				      then (QUOTE INF)
				    else OldDepth)
				  (OR (CAR (FASSOC (CAR OldFormat)
							 NC.BrowserFormatOptions))
					(QUOTE LATTICE))
				  (if (EQ (CADR OldFormat)
					      (QUOTE VERTICAL))
				      then (if ReverseFlg
						 then (QUOTE Reverse/Vertical)
					       else (QUOTE Vertical))
				    else (if ReverseFlg
					       then (QUOTE Reverse/Horizontal)
					     else (QUOTE Horizontal]
	    (SETQ Choices (STYLESHEET NC.BrowserSpecsStylesheet))
	    (RETURN (COND
			[Choices (LIST (APPEND (CAR Choices)
						   (CADR Choices))
					 (OR (FIXP (CADDR Choices))
					       MAX.FIXP)
					 (CONS (CADDDR Choices)
						 (SELECTQ (CADDDR (CDR Choices))
							    (Horizontal (LIST (QUOTE HORIZONTAL)
										(QUOTE 
										REVERSE/DAUGHTERS)))
							    (Vertical (LIST (QUOTE VERTICAL)
									      NIL))
							    (Reverse/Horizontal (LIST (QUOTE
											  HORIZONTAL)
											(QUOTE
											  REVERSE)
											(QUOTE
											  
										REVERSE/DAUGHTERS)))
							    (Reverse/Vertical (LIST (QUOTE 
											 VERTICAL)
										      (QUOTE 
											  REVERSE)))
							    NIL]
			(CreatingBrowserFlg NIL)
			(T (LIST OldLinkLabels OldDepth OldFormat])

(NC.ChangeBrowserSpecs
  [LAMBDA (Window)                                           (* Randy.Gobbel " 4-Mar-87 13:55")

          (* * Change the values of the various browser specs including link types, browser format, search depth, etc.)



          (* * rht 11/17/85: Updated for new card and notefile objects.)



          (* * rht 2/7/86: Now sets and gets browser link labels, etc. via fetch/set fns.)



          (* * rht 11/1/86: Added NC.ProtectedCardOperation wrapper and check for ops in progress.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation, removed DontCheckOpInProgressFlg)


    (LET ((Card (NC.CoerceToCard Window)))
         (NC.ProtectedCardOperation Card "Browser Specs" NIL
				    (PROG (LinkLabels RootNodes BrowserSpecs BrowserFormat Depth)
					    (SETQ LinkLabels (NC.FetchBrowserLinkLabels Card))
					    (SETQ BrowserFormat (NC.FetchBrowserFormat Card))
					    (SETQ Depth (NC.FetchBrowserDepth Card))
					    (SETQ BrowserSpecs (NC.AskBrowserSpecs Window Card 
										       LinkLabels 
										       Depth 
										    BrowserFormat))
					    (SETQ LinkLabels (CAR BrowserSpecs))
					    (SETQ Depth (CADR BrowserSpecs))
					    (SETQ BrowserFormat (CADDR BrowserSpecs))
					    (NC.SetPropListDirtyFlg Card T)
					    (NC.SetBrowserLinkLabels Card LinkLabels)
					    (NC.SetBrowserFormat Card BrowserFormat)
					    (NC.SetBrowserDepth Card Depth)
					    (NC.ClearMsg Window T])

(NC.BrowserCreateCard
  [LAMBDA (Graph Window)                                     (* rht: "20-Apr-87 15:03")

          (* * Called from grapher ADDNODE fn. Used to create a new card and corresponding browser node.)



          (* * Rht 11/17/85: updated for new card and notefile objects.)



          (* * rht 4/30/86: Now only computes title if got a link.)



          (* * rht 4/20/87: Added ProtectedCardOperation wrapper and call to ALLOW.BUTTON.EVENTS.)


    (LET ((GraphCard (NC.CoerceToCard Window))
	  Link GraphNodeID Card Title)
         (NC.ProtectedCardOperation GraphCard "Create card from browser" Window
				    (SETQ Link (NC.MakeLink Window NC.BrowserContentsLinkLabel
								(QUOTE *New% Card*)
								GraphCard NIL NIL NIL T))
				    (if Link
					then [SETQ Title (NC.RetrieveTitle
						   (SETQ Card (fetch (Link DestinationCard)
								   of Link]
					       (ALLOW.BUTTON.EVENTS)
					       (NC.SetTitle Card
							      (OR (NC.AskUser
								      "Title of new card: " NIL
								      (if (STREQUAL "Untitled" 
											Title)
									  then NIL
									else Title)
								      T Window)
								    "Untitled"))
                                                             (* Create hash array if haven't already.)
					       (NC.GetBrowserHashArray GraphCard Graph)
					       (SETQ GraphNodeID (NC.GetBrowserNodeID GraphCard 
											  Card))
					       (NC.MarkCardDirty GraphCard)
					       (NODECREATE GraphNodeID (NC.MakeLinkIcon Link)
							     (CURSORPOSITION NIL Window))
				      else NIL])

(NC.BrowserAddNode
  [LAMBDA (Graph Window)                                     (* Randy.Gobbel " 2-Apr-87 15:38")

          (* * Called by grapher when user creates a new node. Returns new node or nil.)



          (* * rht 11/17/85: updated to handle new card and notefile formats.)



          (* * pmi 12/5/86: Modified message to NC.SelectNoteCards to mention SHIFT-selection. Also added GLOBALVARS 
	  statement.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rg 3/18/87 added NC.ProtectedCardOperation and NC.CardSelectionOperation wrappers)



          (* * rg 4/2/87 changed NC.CardSelectionOperation to NCP.WithLockedCards)


    (DECLARE (GLOBALVARS NC.BrowserContentsLinkLabel))
    (NC.ProtectedCardOperation (NC.CoerceToCard Window)
			       "Add Node" Window
			       (NCP.WithLockedCards (PROG ((GraphCard (NC.CoerceToCard Window))
							     Link GraphNodeID Card)
                                                             (* Get user to select an existing card.
							     Not allowed to create a new one.)
							    (SETQ Card
							      (NC.SelectNoteCards
								T
								[FUNCTION (LAMBDA (SelectedCard)
								    (COND
								      ((NOT (NC.SameCardP 
										     SelectedCard 
											GraphCard))
									T)
								      (T (NC.PrintMsg Window T 
							      "The browser can't link to itself."
											(CHARACTER
											  13)
											
									     "Selection ignored."
											(CHARACTER
											  13))
									 NIL]
								NC.SelectingCardMenu GraphCard 
					      "Shift-select a card or box to include in browser."))
							    (if (NULL Card)
								then (RETURN NIL))
                                                             (* Make link from browser to new card.)
							    (SETQ Link
							      (NC.MakeLink Window 
								      NC.BrowserContentsLinkLabel 
									     Card GraphCard NIL NIL 
									     NIL T))
                                                             (* Check that it doesn't already exist.
							     If not, create a browser node.)
							    (COND
							      (Link 
                                                             (* Create hash array if haven't already.)
								    (NC.GetBrowserHashArray 
											GraphCard 
											    Graph)
								    [SETQ GraphNodeID
								      (NC.GetBrowserNodeID
									GraphCard
									(SETQ Card
									  (fetch (Link 
										  DestinationCard)
									     of Link]
								    (COND
								      ((for Node
									  in (fetch (GRAPH 
										       GRAPHNODES)
										  of Graph)
									  thereis
									   (EQ GraphNodeID
										 (
									   NC.CoerceToGraphNodeID
										   Node)))
									(NC.PrintMsg Window T 
										"Node for card '"
										       (
										 NC.RetrieveTitle
											 Card)
										       
									    "' already in graph.")
									(NCP.DeleteLinks Link)
									(RETURN NIL)))
								    (NC.MarkCardDirty GraphCard)
								    (RETURN (NODECREATE
										GraphNodeID
										(NC.MakeLinkIcon
										  Link)
										(CURSORPOSITION
										  NIL Window])

(NC.DelBrowserContentsLink
  [LAMBDA (GraphCard DestCard DeleteCardFlg)                 (* pmi: " 7-Aug-87 18:09")

          (* * Delete the browsercontents link connecting GraphCard and DestID.)



          (* * rht 11/17/85: updated to handle new card and notefile formats.)



          (* * rht 4/30/86: Now checks to make sure there's a link to delete.)



          (* * rht 5/26/87: Now handles cross-file browsercontents links.)



          (* * pmi 8/7/87: Added DeleteCardFlg arg so we won't create orphans if DestCard is about to be deleted.)


    (DECLARE (GLOBALVARS NC.BrowserContentsLinkLabel))
    (LET ((Links (NCP.GetLinks GraphCard DestCard NC.BrowserContentsLinkLabel)))
         (if (CDR Links)
	     then (NC.ReportError "NC.DelBrowserContentsLink" (CONCAT 
						       "Multiple browser contents links between "
									    (NC.FetchTitle 
											GraphCard)
									    " and "
									    (NC.FetchTitle DestCard)
									    ))
		    NIL)
         (if Links
	     then                                          (* Don't create an orphan if this card is about to be 
							     deleted.)
		    (NC.DeleteLink (CAR Links)
				     DeleteCardFlg T)
	   else                                            (* Could be that it's a cross file browsercontents 
							     link.)
		  (for Link in (NCP.GetLinks GraphCard NIL NC.BrowserContentsLinkLabel)
		     bind CrossFileLinkCard (DestCardUID ← (fetch (Card UID) of DestCard))
		     when [AND (NC.CrossFileLinkCardP (SETQ CrossFileLinkCard
							      (fetch (Link DestinationCard)
								 of Link)))
				   (NC.SameUIDP DestCardUID (fetch (CrossFileLinkSubstance 
									 CrossFileLinkDestCardUID)
								 of (NCP.CardSubstance 
										CrossFileLinkCard]
		     do (RETURN (NC.DeleteLink Link T T])

(NC.MakeBrowserOverviewWin
  [LAMBDA (BrowserWin Region)                                (* Randy.Gobbel " 4-Mar-87 13:57")

          (* * Make and attach a little window to contain a shrunken bitmap of the entire browser. If Region arg is passed 
	  then use that as size for overview win, else use defaults.)



          (* * rht 3/7/86: Now uses stylesheet to figure out where to attach.)



          (* * rht 11/1/86: Added NC.ProtectedCardOperation wrapper and check for ops in progress.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation, removed DontCheckOpInProgressFlg)


    (LET ((Card (NC.CoerceToCard BrowserWin)))
         (NC.ProtectedCardOperation Card "Build Browser Overview" NIL
				    (LET ((OverviewWinWidth (if Region
								then (fetch (REGION WIDTH)
									  of Region)
							      else (OR (WINDOWPROP
									     BrowserWin
									     (QUOTE 
										 OverviewWinWidth))
									   
								   NC.BrowserOverviewDefaultWidth)))
					  (OverviewWinHeight (if Region
								 then (fetch (REGION HEIGHT)
									   of Region)
							       else (OR (WINDOWPROP
									      BrowserWin
									      (QUOTE 
										OverviewWinHeight))
									    
								  NC.BrowserOverviewDefaultHeight)))
					  [OverviewWin (OPENWP (WINDOWPROP BrowserWin
									       (QUOTE 
									       BrowserOverviewWin]
					  (WhereToAttach (OR (WINDOWPROP BrowserWin (QUOTE
									       
									 WHERETOATTACHOVERVIEWWIN))
							       NC.DefaultWhereToAttachOverviewWin)))
				         (if OverviewWin
					   else            (* Make a new overview window.)
						  (SETQ OverviewWin
						    (CREATEW (CREATEREGION (fetch (POSITION
											  XCOORD)
										  of 
									     NC.OffScreenPosition)
									       (fetch (POSITION
											  YCOORD)
										  of 
									     NC.OffScreenPosition)
									       OverviewWinWidth 
									       OverviewWinHeight)))
						  (WINDOWPROP BrowserWin (QUOTE 
									       BrowserOverviewWin)
								OverviewWin))
				         (NC.ReattachBrowserOverviewWin OverviewWin BrowserWin 
									  WhereToAttach)
				         (NC.RedrawBrowserOverviewWin OverviewWin BrowserWin])

(NC.AskBrowserOverviewSpecs
  [LAMBDA (BrowserWin)                                       (* Randy.Gobbel " 4-Mar-87 14:00")

          (* * Put up stylesheet to get mode and where to attach overview win.)



          (* * rht 11/1/86: Added NC.ProtectedCardOperation wrapper and check for ops in progress.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation, removed DontCheckOpInProgressFlg)


    (LET ((Card (NC.CoerceToCard BrowserWin)))
         (NC.ProtectedCardOperation Card "Browser Overview Specs" NIL
				    (LET ((WhereLastAttached (OR (WINDOWPROP BrowserWin
										 (QUOTE 
									 WHERETOATTACHOVERVIEWWIN))
								   NC.DefaultWhereToAttachOverviewWin)
							     )
					  (LastMode (OR (WINDOWPROP BrowserWin (QUOTE 
										  OVERVIEWWINMODE))
							  NC.DefaultBrowserOverviewMode))
					  OverviewSpecsResults)
				         (STYLE.PROP NC.BrowserOverviewSpecsStylesheet
						       (QUOTE SELECTIONS)
						       (LIST (CAR WhereLastAttached)
							       (SELECTQ (CDR WhereLastAttached)
									  ((TOP RIGHT)
									    (QUOTE TOP/RIGHT))
									  ((LEFT BOTTOM)
									    (QUOTE BOTTOM/LEFT))
									  (QUOTE CENTER))
							       LastMode))
				         [STYLE.PROP NC.BrowserOverviewSpecsStylesheet
						       (QUOTE POSITION)
						       (create POSITION
								 XCOORD ← (fetch (REGION LEFT)
									     of
									      (WINDOWPROP
										BrowserWin
										(QUOTE REGION)))
								 YCOORD ← (fetch (REGION TOP)
									     of (WINDOWREGION
										    BrowserWin]
				         (if (SETQ OverviewSpecsResults (STYLESHEET 
								NC.BrowserOverviewSpecsStylesheet))
					     then (WINDOWPROP BrowserWin (QUOTE 
									 WHERETOATTACHOVERVIEWWIN)
								  (CONS (CAR OverviewSpecsResults)
									  (CADR 
									     OverviewSpecsResults)))
						    (WINDOWPROP BrowserWin (QUOTE OVERVIEWWINMODE)
								  (CADDR OverviewSpecsResults))
					   else NIL])

(NC.BrowserCardQuitFn
  [LAMBDA (Card)                                             (* rht: "25-Apr-87 17:57")

          (* * This clears all UserData fields of Graph node UIDs. I ONLY HAVE TO DO THIS BECAUSE INTERLISP WON'T GC CYCLES!)


    [for GraphNode in (fetch (GRAPH GRAPHNODES) of (NC.FetchSubstance Card))
       do (LET ((GraphNodeID (NC.CoerceToGraphNodeIDOrLabel GraphNode)))
	         (AND (type? UID GraphNodeID)
			(NC.UIDSetPropList GraphNodeID NIL]
    (NCP.ApplySuperTypeFn QuitFn Card])

(NC.GetBrowserNodeID
  [LAMBDA (BrowserCard NodeCard)                             (* rht: " 1-Jun-87 21:42")

          (* * Create a browser node atom from a new UID. Hang the card object off as a property for those who need it.)



          (* * rht 11/18/85: Now checks to see if NodeCard already appears in graph before creating a new GraphNodeID.
	  Use the browser hash array to do the lookup.)



          (* * rht 6/1/87: Changed hash array to map from card UIDs to graph node ids rather than from card objects to graph 
	  node ids.)


    (LET ((HashArray (NC.HashArrayFromBrowserCard BrowserCard))
	  (NodeCardUID (fetch (Card UID) of NodeCard))
	  NewUID)
         (if (GETHASH NodeCardUID HashArray)
	   else (NC.GraphNodeIDPutProp (SETQ NewUID (NC.MakeBrowserNodeUID))
					   (QUOTE CardObject)
					   NodeCard)
		  (PUTHASH NodeCardUID NewUID HashArray)
		  NewUID])

(NC.GetBrowserHashArray
  [LAMBDA (BrowserCard Graph)                                (* rht: "10-Jun-87 22:41")

          (* * Build and install a hash array mapping cards to browsernode UIDs, unless one's already there.
	  If Graph argument is nil, then make a new hash array smashing any existin one.)



          (* * rht 4/30/86: Now makes sure we're not working with a label node instead of a card node.)



          (* * rht 6/1/87: Changed hash array to map from card UIDs to graph node ids rather than from card objects to graph 
	  node ids.)



          (* * rht 6/10/87: Now checks that CardObject on GraphNodeID is valid card before stashing in hash array.)


    (DECLARE (GLOBALVARS NC.BrowserHashArraySize))
    (if (AND Graph (NC.HashArrayFromBrowserCard BrowserCard))
      else (LET ((HashArray (NC.CreateUIDHashArray NC.BrowserHashArraySize)))
	          (NC.SetUserDataProp BrowserCard (QUOTE BrowserHashArray)
					HashArray)
	          (AND Graph (for GraphNode in (fetch (GRAPH GRAPHNODES) of Graph)
				  bind GraphNodeID eachtime (BLOCK) when (SETQ GraphNodeID
										   (
									   NC.CoerceToGraphNodeID
										     GraphNode))
				  do (LET [(CardObject (NC.GraphNodeIDGetProp GraphNodeID
										  (QUOTE CardObject]
					    (if (NC.ValidCardP CardObject)
						then (PUTHASH (fetch (Card UID) of CardObject)
								  GraphNodeID HashArray])

(NC.RemoveBrowserNodeHashArrayEntry
  [LAMBDA (BrowserCard NodeCard)                             (* rht: " 1-Jun-87 21:40")

          (* * Remove the entry for given card from given browser's hash array.)



          (* * rht 6/1/87: Now expects hash array to map from card UIDs to graph node ids rather than from card objects to 
	  graph node ids.)


    (LET ((HashArray (NC.HashArrayFromBrowserCard BrowserCard)))
         (if HashArray
	     then (PUTHASH (fetch (Card UID) of NodeCard)
			       NIL HashArray])

(NC.SetBrowserRoots
  [LAMBDA (Card BrowserRoots)                                (* rht: " 6-Feb-87 18:38")

          (* * Put the roots on the Card's UID property list in the CardUID/NoteFileUID pair format.)



          (* * rht 2/6/87: Now checks that BrowserRoots are valid cards.)


    (NC.SetBrowserRootsInfo Card (for BrowserRoot in BrowserRoots eachtime (BLOCK)
				      when (NC.ValidCardP BrowserRoot)
				      collect (CONS (fetch (Card UID) of BrowserRoot)
							(fetch (NoteFile UID)
							   of (fetch (Card NoteFile)
								   of BrowserRoot])
)
(* * changes to NCLINKINDEXCARD)

(DEFINEQ

(NC.AddLinkIndexCard
  [LAMBDA NIL                                                (* rht: "11-Apr-86 21:58")

          (* * fgh 11/14/85 Updated toremove substance type param to add card type.)


    (NC.AddCardType (QUOTE LinkIndex)
		      (QUOTE Text)
		      [BQUOTE ((MakeFn , (FUNCTION NC.MakeLinkIndex))
				 (EditFn , (FUNCTION NC.BringUpLinkIndexCard]
		      (BQUOTE ((LinkDisplayMode Title)
				 (DefaultHeight 350)
				 (DefaultWidth 350)
				 (DisplayedInMenuFlg , T)
				 (LeftButtonMenuItems , (APPEND (NC.GetCardTypeField 
									      LeftButtonMenuItems
										       (QUOTE
											 Text))
								  NC.LinkIndexExtraMenuItems])

(NC.MakeLinkIndex
  [LAMBDA (Card Title NoDisplayFlg SpecialArgsList)          (* rht: "17-Apr-87 20:01")

          (* * Gather all instances of a given set of linktypes, printing the titles of cards at the from and to ends of the 
	  link.)



          (* * rht 10/24/84: Now callable from Programmer's interface. If NoDisplayFlg it non-nil, then will build LinkIndex 
	  invisibly. If SpecialArgsList is non-nil, then should be list of (<linklabels> <backpointersP>))



          (* * rht 9/21/85: Now uses stylesheet for LinkIndexSpecs. Broke out workhorse code into the function 
	  NC.ComputeLinkIndex)



          (* * fgh 11/17/85 Updated to handle Card objects.)



          (* * rht 4/11/86: Took out call to NCP.AddTitleBarMenuItems. Now done in NC.AddLinkIndexCard.
	  Also changed to call NC.ApplySuper.)



          (* * rht 9/5/86: Now bails out properly if user aborts in stylesheet.)



          (* * rht 9/19/86: Now passes IndexCard rather than Window to NC.AskLinkIndexSpecs. Added call to NC.HoldTTYProcess 
	  to keep linkindexspecs on top.)



          (* * rg 3/16/87 NC.DeleteNoteCards -> NC.DeleteNoteCard)


    (PROG ((LinkLabels (CAR SpecialArgsList))
	     (BackLinksFlg (CADR SpecialArgsList))
	     Window LinkIndexSpecs)
	    (SPAWN.MOUSE)
	    (SETQ Window (WINDOWP (NC.ApplySupersFn MakeFn Card (CONCAT "Link Index: "
									      (DATE))
							NoDisplayFlg)))
	    (if (NOT NoDisplayFlg)
		then (NC.HoldTTYProcess)
		       (SETQ LinkIndexSpecs (NC.AskLinkIndexSpecs Card LinkLabels BackLinksFlg T))
		       (if (NULL LinkIndexSpecs)
			   then (NC.DeleteNoteCard Card NIL T)
				  (RETURN NIL))
		       (SETQ LinkLabels (CAR LinkIndexSpecs))
		       (SETQ BackLinksFlg (CADR LinkIndexSpecs)))
	    (NC.ComputeLinkIndex Card LinkLabels BackLinksFlg)
	    (RETURN (if NoDisplayFlg
			  then Card
			else (NC.ClearMsg Window T)
			       Window])

(NC.ComputeLinkIndex
  [LAMBDA (IndexCard LinkLabels BackLinksFlg)                (* kirk: " 9-Sep-86 15:13")

          (* * This is the workhorse. Walks through all links, gathering those with label in LinkLabels and creating back 
	  links if BackLinksP is non-nil.)



          (* * kirk 9/9/86 Deleted obsolete param from NC.RetrieveToLinks)


    (LET ((Window (NC.FetchWindow IndexCard))
	  (NoteFile (fetch (Card NoteFile) of IndexCard))
	  TextStream SortedWinners LastCard)
         (RESETLST (RESETSAVE (CURSOR WAITINGCURSOR))
		     (SETQ TextStream (NC.FetchSubstance IndexCard))
		     (NC.AppendStringToStream TextStream (CONCAT 
								"Sorted link index compiled on: "
								     (DATE)
								     (CHARACTER 13)
								     " for linktypes: "
								     (CAR LinkLabels)))
		     [COND
		       (LinkLabels (for Label in (CDR LinkLabels)
				      do (NC.AppendStringToStream TextStream (CONCAT ", " Label)
								      ))
				   (NC.AppendStringToStream TextStream (CONCAT (CHARACTER
										     13)
										   (CHARACTER
										     13)))
				   (NC.PrintMsg Window T "Gathering links ... ")

          (* * Find all cards with instances of a desired link label, record whether they were active, sort them, print their
	  titles to the stream, and deactivate the ones that weren't active.)


				   (SETQ SortedWinners
				     (SORT [NC.MapCards
					       NoteFile
					       (FUNCTION [LAMBDA (Card PredicateResult)
						   (LIST (NC.RetrieveTitle Card)
							   Card PredicateResult])
					       (FUNCTION (LAMBDA (Card)
						   (LET (ToLinks FromLinks)
						        (if (OR (for Link
								       in (SETQ ToLinks
									      (NC.RetrieveToLinks
										Card))
								       thereis (NC.LinkLabelP
										   Link LinkLabels))
								    (for Link
								       in (SETQ FromLinks
									      (NC.RetrieveFromLinks
										Card))
								       thereis (
									     NC.ReverseLinkLabelP
										   Link LinkLabels)))
							    then (LIST ToLinks FromLinks]
					     T))
				   (for WinnerList in SortedWinners
				      do (NC.AppendLinkIndexEntry TextStream IndexCard WinnerList 
								      LinkLabels BackLinksFlg))
				   (NC.PrintMsg Window NIL "Done!" (CHARACTER 13]
		     (NC.PutProp IndexCard (QUOTE LinkIndexLinkLabels)
				   (LIST LinkLabels))
		     (NC.PutProp IndexCard (QUOTE LinkIndexBackLinksFlg)
				   BackLinksFlg)
		     (NC.SetPropListDirtyFlg IndexCard T])

(NC.RecomputeLinkIndex
  [LAMBDA (WindowOrTextStream)                               (* Randy.Gobbel " 4-Mar-87 14:31")

          (* * Recompute the contents of the link index card. Modeled after NC.UpdateBrowserCard.)



          (* * fgh 11/17/85 Updated to handle Card object.)



          (* * rht 11/1/86: Added NC.ProtectedCardOperation wrapper and check for ops in progress.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation, removed DontCheckOpInProgressFlg)


    (LET ((Card (NC.CoerceToCard WindowOrTextStream))
	  Window LinkLabels BackLinksFlg PropList BrowserSpecs TextStream)
         (NC.ProtectedCardOperation Card "Recompute LinkIndex" NIL (SETQ Window (NC.FetchWindow
					Card))
				    (SETQ TextStream (TEXTSTREAM WindowOrTextStream))
				    (SETQ PropList (NC.FetchPropList Card))
				    [SETQ LinkLabels (CAR (LISTGET PropList (QUOTE 
									      LinkIndexLinkLabels]
				    (SETQ BackLinksFlg (LISTGET PropList (QUOTE 
									    LinkIndexBackLinksFlg)))
				    (NC.PrintMsg Window T "Clearing old contents of link index ..."
						   (CHARACTER 13))
				    [TEDIT.DELETE TextStream (TEDIT.SETSEL TextStream 1
									       (fetch (TEXTOBJ
											  TEXTLEN)
										  of (TEXTOBJ
											 TextStream]
				    (NC.PrintMsg Window NIL "Done." (CHARACTER 13))
				    (NC.ComputeLinkIndex Card LinkLabels BackLinksFlg)
				    (NC.ClearMsg Window T])

(NC.AskLinkIndexSpecs
  [LAMBDA (Card OldLinkLabels OldBackLinksFlg CreatingLinkIndexFlg)
                                                             (* pmi: " 2-Apr-87 11:23")

          (* * Puts up the stylesheet asking user about link types, and whether to create back links.
	  This is modeled on NC.AskBrowserSpecs.)



          (* * fgh 11/17/85 Updated to use NoteFile rather than PSA.Database)



          (* * rht 9/19/86: Now takes Card arg rather than MainWindow.)



          (* * pmi 4/2/87: Added NC.MenuFont to all menus.)


    (DECLARE (GLOBALVARS NC.MenuFont))
    (LET ((MainWindow (NC.FetchWindow Card))
	  (NoteFile (fetch (Card NoteFile) of Card))
	  LinkLabels Position Choices ReverseFlg)
         (SETQ LinkLabels (NC.RetrieveLinkLabels NoteFile T))
         [SETQ Position (AND (WINDOWP MainWindow)
				 (create POSITION
					   XCOORD ← (fetch (REGION LEFT)
						       of (WINDOWPROP MainWindow (QUOTE REGION))
							     )
					   YCOORD ← (fetch (REGION TOP) of (WINDOWREGION 
										       MainWindow]
                                                             (* The stylesheet is in a global var.
							     We only need to provide its position, items, and 
							     selections.)
         (STYLE.PROP NC.LinkIndexSpecsStylesheet (QUOTE POSITION)
		       Position)
         (STYLE.PROP NC.LinkIndexSpecsStylesheet (QUOTE ITEMS)
		       (LIST (create MENU
					 ITEMS ← LinkLabels
					 MENUFONT ← NC.MenuFont)
			       (create MENU
					 ITEMS ← (for Link in LinkLabels
						    collect (PACK* (QUOTE ←)
								       Link))
					 MENUFONT ← NC.MenuFont)
			       (create MENU
					 ITEMS ← (QUOTE (Yes No))
					 MENUFONT ← NC.MenuFont)))
         [STYLE.PROP NC.LinkIndexSpecsStylesheet (QUOTE SELECTIONS)
		       (LIST (for Label in OldLinkLabels when (NEQ (NTHCHAR Label 1)
									     (QUOTE ←))
				  collect Label)
			       (for Label in OldLinkLabels when (EQ (NTHCHAR Label 1)
									    (QUOTE ←))
				  collect Label)
			       (COND
				 (OldBackLinksFlg (QUOTE Yes))
				 (T (QUOTE No]
         (SETQ Choices (STYLESHEET NC.LinkIndexSpecsStylesheet))
         (COND
	   [Choices (LIST (APPEND (CAR Choices)
				      (CADR Choices))
			    (COND
			      ((EQ (CADDR Choices)
				     (QUOTE Yes))
				T)
			      (T NIL]
	   (CreatingLinkIndexFlg NIL)
	   (T (LIST OldLinkLabels OldBackLinksFlg])

(NC.ChangeLinkIndexSpecs
  [LAMBDA (WindowOrTextStream)                               (* Randy.Gobbel " 4-Mar-87 14:32")

          (* * Change the values of the various link index specs including link types and back links flag.)



          (* * rht 9/19/86: Changed to pass Card rather than Window to NC.AskLinkIndexSpecs.)



          (* * rht 11/1/86: Added NC.ProtectedCardOperation wrapper and check for ops in progress.)



          (* * rg 3/4/87 rewritten for new version of NC.ProtectedCardOperation, removed DontCheckOpInProgressFlg)


    (LET ((Card (NC.CoerceToCard WindowOrTextStream))
	  LinkLabels BackLinksFlg PropList LinkIndexSpecs)
         (NC.ProtectedCardOperation Card "LinkIndex Specs" NIL (SETQ PropList (NC.FetchPropList
					Card))
				    [SETQ LinkLabels (CAR (LISTGET PropList (QUOTE 
									      LinkIndexLinkLabels]
				    (SETQ BackLinksFlg (LISTGET PropList (QUOTE 
									    LinkIndexBackLinksFlg)))
				    (SETQ LinkIndexSpecs (NC.AskLinkIndexSpecs Card LinkLabels 
										   BackLinksFlg))
				    (SETQ LinkLabels (CAR LinkIndexSpecs))
				    (SETQ BackLinksFlg (CADR LinkIndexSpecs))
				    (NC.SetPropListDirtyFlg Card T)
				    (NC.PutProp Card (QUOTE LinkIndexLinkLabels)
						  (LIST LinkLabels))
				    (NC.PutProp Card (QUOTE LinkIndexBackLinksFlg)
						  BackLinksFlg)
				    (NC.ClearMsg (NC.FetchWindow Card)
						   T])
)
(* * changes to NCTYPESMECH)

(DEFINEQ

(NC.MakeCardTypesList
  [LAMBDA NIL                                                (* Randy.Gobbel "14-Jul-87 16:07")

          (* * Make initial set of card types.)



          (* * fgh 1/31/86 Updated to handle hash table for card types.)



          (* * fgh 2/17/86 Added typless attached bit map to NoteCards card type.)



          (* * rht 4/7/86: Now sets up default left and middle button menu items.)



          (* * rg 3/27/87 added WITH.MONITOR)


    (DECLARE (GLOBALVARS NC.TypelessIcon NC.CardTypes NC.DefaultLeftButtonMenuItems 
			     NC.DefaultMiddleButtonMenuItems NC.TypesLock NC.NoteCardTypeMenu))
    (WITH.MONITOR NC.TypesLock (SETQ NC.CardTypes (OR (HARRAYP NC.CardTypes)
							  (HASHARRAY 50)))
		  (PUTHASH (QUOTE NoteCard)
			     (create NoteCardType
				       TypeName ← (QUOTE NoteCard)
				       SuperType ← NIL
				       CopyFn ← (FUNCTION [LAMBDA (Card ToStream FromStream Length)
                                                             (* Copy a card's substance using copybytes.)
					   (LET* ((FromStartPtr (GETFILEPTR FromStream))
						  (FromEndPtr (PLUS Length FromStartPtr)))
					         (COPYBYTES FromStream ToStream FromStartPtr 
							      FromEndPtr)
					     T])
				       CollectLinksFn ← (FUNCTION NILL)
				       LinkDisplayMode ← (create LINKDISPLAYMODE
								   ATTACHBITMAPFLG ← T)
				       DefaultWidth ← 100
				       DefaultHeight ← 100
				       LinkIconAttachedBitMap ← NC.TypelessIcon
				       LeftButtonMenuItems ← NC.DefaultLeftButtonMenuItems
				       MiddleButtonMenuItems ← NC.DefaultMiddleButtonMenuItems)
			     NC.CardTypes)
		  (SETQ NC.NoteCardTypeMenu])

(NC.AddCardType
  [LAMBDA (TypeName SuperType FnsAssocList VarsAssocList FullDefinitionFile ListOfFILLMEFields 
		    StubFlg)                                 (* Randy.Gobbel "27-Mar-87 16:05")

          (* * Create a new note card type and link it into the card type heirarchy.)



          (* * fgh 1/31/86 Updated to handle card type hash table.)



          (* * fgh 2/3/86 Updated to do inheritance at definition time rather than at access time.)



          (* * rht 7/15/86: Innards replaced by call to NC.ModifyCardType.)



          (* * rht 11/7/86: Now accepts ListOfFILLMEFields arg. Any such fields get the \\FILLME// atom as value.
	  No longer forces load of super. Takes three extra optional args StubFlg, FullDefinitionFile, and 
	  ListOfFILLMEFields.)



          (* * RG 3/27/87 added WITH.MONITOR)


    (WITH.MONITOR NC.TypesLock
		  (LET [NewType (MainFieldNames (CONSTANT (for FieldName
							       in (RECORDFIELDNAMES (QUOTE
											  
										     NoteCardType))
							       when (NEQ (QUOTE InheritedFlg)
									     (SUBATOM FieldName -12 
											-1))
							       collect FieldName]
		       (COND
			 ((NULL TypeName)
			   (NC.ReportError "NC.AddCardType" "Illegal type name: NIL"))
			 ((NULL SuperType)
			   (NC.ReportError "NC.AddCardType" "Illegal super type name: NIL")))

          (* * Create new NoteCardType)


		       (SETQ NewType
			 (create NoteCardType
				   TypeName ← TypeName
				   SuperType ← SuperType
				   StubFlg ← StubFlg
				   FullDefinitionFile ← FullDefinitionFile))

          (* * If it's a stub, then change the default values for fields from \\FILLME// to \\EMPTY// except for those in 
	  ListOfFILLMEFields.)


		       [if StubFlg
			   then (for FieldName in MainFieldNames unless (FMEMB FieldName 
									       ListOfFILLMEFields)
				     when (EQ (RECORDACCESS (BQUOTE (NoteCardType , FieldName)
									    )
								  NewType NIL (QUOTE fetch))
						  (QUOTE \\FILLME//))
				     do (RECORDACCESS (BQUOTE (NoteCardType , FieldName))
							  NewType NIL (QUOTE replace)
							  (QUOTE \\EMPTY//]

          (* * Compute fields, inheriting from above and propagating downward.)


		       (NC.ModifyCardType NewType FnsAssocList VarsAssocList)

          (* * Stash the new card type record, reset the menu and then return.)


		       (PUTHASH TypeName NewType NC.CardTypes)
		       (SETQ NC.NoteCardTypeMenu)
		   NewType])

(NC.IsSubTypeOfP
  [LAMBDA (SubTypeName SupposedSuperTypeName)                (* rht: "15-Jul-86 18:06")

          (* * Is SubTypeName the name of a Card type that is a sub type of carrd type SupposedSuperTypeName.)


    (LET (SuperType)
         (OR (EQ SubTypeName SupposedSuperTypeName)
	       (AND (SETQ SuperType (NC.GetCardTypeField SuperType SubTypeName))
		      (NC.IsSubTypeOfP SuperType SupposedSuperTypeName])

(NC.ModifyCardType
  [LAMBDA (TypeRecord FnsAssocList VarsAssocList)            (* rht: "15-Jul-86 13:13")

          (* * Changes the fields of the given type, inheriting other fields from the super and propagating changes downward.
	  This used to be the innards of NC.AddCardType.)


    (if (type? NoteCardType TypeRecord)
	then (LET [(MainFieldNames (CONSTANT (for FieldName in (RECORDFIELDNAMES
									 (QUOTE NoteCardType))
						    when (NEQ (QUOTE InheritedFlg)
								  (SUBATOM FieldName -12 -1))
						    collect FieldName]
		    (for AssocPair in (APPEND FnsAssocList VarsAssocList)
		       when (FMEMB (CAR AssocPair)
				       MainFieldNames)
		       do 

          (* * Set the proper field to the given value)


			    (RECORDACCESS (BQUOTE (NoteCardType , (CAR AssocPair)))
					    TypeRecord NIL (QUOTE replace)
					    (CADR AssocPair))

          (* * Set the corresponding InheritedFlg to indicate that this field is not inherited.)


			    (RECORDACCESS [BQUOTE (NoteCardType , (PACK* (CAR AssocPair)
									       (QUOTE InheritedFlg]
					    TypeRecord NIL (QUOTE replace)
					    NIL)))

          (* * Inherit any NIL fields from super type record.)


	       (AND (fetch (NoteCardType SuperType) of TypeRecord)
		      (NC.InheritFieldsFromSuperType TypeRecord))

          (* * Propagate any changes downward to the subtypes of this type.)


	       (NC.PropagateCardTypeFieldsDownward TypeRecord])

(NC.RecomputeCardType
  [LAMBDA (TypeName FnsAssocList VarsAssocList)              (* Randy.Gobbel "27-Mar-87 17:05")

          (* * Recomputes an existing card type, changing those fields present on FnsAssocList and VarsAssocList.)



          (* * rg 3/27/87 added WITH.MONITOR)


    (WITH.MONITOR NC.TypesLock (LET ((TypeRecord (NC.CardTypeRecord TypeName))
				     SuperType)
				    [COND
				      ((NULL TypeRecord)
					(NC.ReportError "NC.RecomputeCardType" (CONCAT 
										 "Unknown type: "
											   TypeName)))
				      ([AND (NEQ TypeName (QUOTE NoteCard))
					      (NULL (NC.CardTypeRecord (SETQ SuperType
									     (fetch (NoteCardType
											SuperType)
										of TypeRecord]
					(NC.ReportError "NC.RecomputeCardType"
							  (CONCAT TypeName 
								    " has unknown super type:  "
								    SuperType]

          (* * Compute fields, inheriting from above and propagating downward.)


				    (NC.ModifyCardType TypeRecord FnsAssocList VarsAssocList)

          (* * reset the menu)


				    (SETQ NC.NoteCardTypeMenu)
				TypeName])

(NC.SubTypesOfCardType
  [LAMBDA (TypeName)                                         (* fgh: "31-Jan-86 21:49")

          (* * Returns a list of the types names of all the sub-types of TypeName)



          (* * fgh 1/31/86 First created.)


    (LET (CollectLst)
         [MAPHASH NC.CardTypes (FUNCTION (LAMBDA (TypeRecord Key)
			(if (EQ TypeName (fetch (NoteCardType SuperType) of TypeRecord))
			    then (push CollectLst (fetch (NoteCardType TypeName) of 
										       TypeRecord]
     CollectLst])

(NC.InheritFieldsFromSuperType
  [LAMBDA (TypeNameOrRecord SuperTypeRecord)                 (* rht: " 8-Nov-86 18:10")

          (* * Inherit fields from super card type record if the supertype is not a stub.)



          (* * fgh 2/3/86 First created.)



          (* * fgh 8/26/86 Now uses SuperTypeRecord consistently if it is present.)



          (* * rht 11/7/86: Changed procedure for deciding when to inherit a field from upstairs.)


    (LET [(TypeRecord (if (type? NoteCardType TypeNameOrRecord)
			  then TypeNameOrRecord
			else (NC.CardTypeRecord TypeNameOrRecord)))
	  (InheritedFlgNames (CONSTANT (for FieldName in (RECORDFIELDNAMES (QUOTE 
										     NoteCardType))
					    when (EQ (QUOTE InheritedFlg)
							 (SUBATOM FieldName -12 -1))
					    collect FieldName]
         (if [OR SuperTypeRecord (SETQ SuperTypeRecord (NC.CardTypeRecord
			 (fetch (NoteCardType SuperType) of TypeRecord]
	     then (for FlgName in InheritedFlgNames
		       do (LET ((FieldName (SUBATOM FlgName 1 -13))
				  FieldValue SuperFieldValue)
			         (SETQ FieldValue (RECORDACCESS (BQUOTE (NoteCardType , 
											FieldName))
								    TypeRecord NIL (QUOTE fetch)))
			         (SETQ SuperFieldValue (RECORDACCESS (BQUOTE (NoteCardType
										     , FieldName))
									 SuperTypeRecord NIL
									 (QUOTE fetch)))

          (* * Only inherit from the super field if it's got a real value, and if either the subfield has value \\FILLME// or
	  the InheritedFlg field says to inherit. Don't inherit if the subfield is \\EMPTY//, cause that indicates a field 
	  for a stub that shouldn't inherit.)


			         (if [AND [NOT (FMEMB SuperFieldValue (QUOTE (\\FILLME//
											 \\EMPTY//]
					      (NOT (EQ FieldValue (QUOTE \\EMPTY//)))
					      (OR (EQ FieldValue (QUOTE \\FILLME//))
						    (RECORDACCESS (BQUOTE (NoteCardType , FlgName)
									      )
								    TypeRecord NIL (QUOTE fetch]
				     then (RECORDACCESS (BQUOTE (NoteCardType , FieldName))
							    TypeRecord NIL (QUOTE replace)
							    SuperFieldValue])

(NC.AutoLoadCardType
  [LAMBDA (TypeName FieldName FileSuggestion)                (* kirk: "22-Aug-86 15:48")

          (* * AutoLoad card type TypeName using FileSuggestion as the first place to look. Otherwise look in the directories
	  specified by NoteCardsDirectories. Works by starting at the give Type and moving up the inheritance heirarchy 
	  loading all types that are currently defined only by stubs until it reaches a card type for which FieldName is 
	  defined. This works because full inheritance is done whereever possible during type definition in NC.AddCardType.)



          (* * fgh 2/3/86 First created.)



          (* * fgh 7/16/86 Added ALLOW.BUTTON.EVENTS call)



          (* * kirk 8/22/86 Added check for NIL card type)


    (ALLOW.BUTTON.EVENTS)
    (LET ((CardTypeRecord (NC.CardTypeRecord TypeName))
	  (OriginalTypeName TypeName)
	  FieldValue)

          (* * If there's no stub for this card type, load the type definition file.)


         (if (NULL TypeName)
	     then (NC.ReportError NIL "NIL card type"))
         [if (NULL CardTypeRecord)
	     then (NC.CardTypeLoader TypeName FileSuggestion) 

          (* * Still no definition then we're sunk.)


		    (if (NULL (SETQ CardTypeRecord (NC.CardTypeRecord TypeName)))
			then (NC.ReportError NIL (CONCAT 
							  "Cannot find definition of card type: "
							       TypeName]

          (* * We have at least a stub for this card type. Move up the inheritance hierarchy loading the real files instead 
	  of the stubs until we have a value of the field we are looking for.)


         (until (EQ TypeName (QUOTE NoteCard))
	    do 

          (* * If this is a stub, load the real thing. Break if it can't be found.)


		 (if (fetch (NoteCardType StubFlg) of CardTypeRecord)
		     then (OR (NC.CardTypeLoader TypeName FileSuggestion)
				  (NC.ReportError NIL (CONCAT 
						     "Cannot find full definition of card type: "
								  TypeName)))
			    (SETQ CardTypeRecord (NC.CardTypeRecord TypeName)))

          (* * If the field was defined in the real thing, then return it. Else keep moving up load ing all the stubs.)


		 (if (SETQ FieldValue (RECORDACCESS (BQUOTE (NoteCardType , FieldName))
							  CardTypeRecord NIL (QUOTE fetch)))
		     then (RETURN FieldValue)
		   else (SETQ TypeName (fetch (NoteCardType SuperType) of CardTypeRecord))
			  (SETQ CardTypeRecord (NC.CardTypeRecord TypeName)))
	    finally (NC.ReportError NIL (CONCAT "Cannot find definition of card type: " 
						      OriginalTypeName "   Field name needed: " 
						      FieldName])
)
(* * changes to NCDATABASE)

(DEFINEQ

(NC.UIDSetPropList
  [LAMBDA (UID PropList)                                   (* rht: "25-Nov-85 23:38")
    (replace (UID UserData) of UID with PropList])

(NC.UIDPutProp
  [LAMBDA (UID Prop Value)                                 (* rht: "26-Nov-85 22:25")
    (LET ((PropList (fetch (UID UserData) of UID)))
         (COND
	   (PropList (LISTPUT PropList Prop Value))
	   (T (replace (UID UserData) of UID with (LIST Prop Value])

(NC.UIDGetProp
  [LAMBDA (UID Prop)                                       (* fgh: "20-Nov-85 19:10")
    (LISTGET (fetch (UID UserData) of UID)
	       Prop])

(NC.UIDGetPropList
  [LAMBDA (UID)                                            (* rht: " 1-Feb-86 14:27")

          (* * Return the user data field of UID.)


    (fetch (UID UserData) of UID])

(NC.ReadLink
  [LAMBDA (Stream)                                           (* rht: " 1-Nov-86 15:13")

          (* * Read a single Link DATAYPE instance from Stream)



          (* * Link identifier and CR)



          (* * rht 11/25/85: Now handles case of version 2 style link.)



          (* * fgh 8/27/86 Put in Kludge to handle problem with some versions of WRITE.IMAGEOBJ that put in an extra CR 
	  before the stuff.)



          (* * rht 11/1/86: Now uses our readtable when reading.)


    (DECLARE (GLOBALVARS NC.OrigReadTable))
    (LET ((FirstChar (NC.ReadPtr Stream 1)))
         (COND
	   ((ZEROP FirstChar)

          (* * Version Number 0 means end of list of links)


	     NIL)
	   ((EQ FirstChar 1)

          (* * The link info for a version 3 style link.)


	     (PROG1 (create Link
				UID ← (NC.ReadUID Stream)
				SourceCard ← (NC.CardOrCardHolderFromUID (NC.ReadUID Stream)
									   (NC.ReadUID Stream))
				DestinationCard ← (NC.CardOrCardHolderFromUID (NC.ReadUID Stream)
										(NC.ReadUID Stream))
				AnchorMode ← (READ Stream NC.OrigReadTable)
				Label ← (READ Stream NC.OrigReadTable)
				DisplayMode ← (READ Stream NC.OrigReadTable))

          (* * Get that damn CR)


		      (BIN Stream)))
	   ((EQ FirstChar 13)

          (* * KLUDGE to account for fact that some versions of WRITE.IMAGEOBJ put a CR before beginning the actual stuff.)


	     (NC.ReadLink Stream))
	   (T 

          (* * Version 2 style link. Move back over the left parantheses and read the link as a list.)


	      (SETFILEPTR Stream (SUB1 (GETFILEPTR Stream)))
	      (READ Stream NC.OrigReadTable])

(NC.OpenNoteFile
  [LAMBDA (NoteFileOrFileName Don'tCacheTypesAndTitlesFlg Don'tCreateFlg ConvertNoConfirmFlg 
			      Don'tCreateArrayFlg Can'tTruncateFlg Don'tCreateInterfaceFlg 
			      Don'tGetSpecialCardsFlg InterestedWindow PublicOrPrivate MenuPosition 
			      QuietFlg ReadOnlyFlg Don'tCheckForTruncationFlg Don'tCheckVersionFlg)
                                                             (* pmi: "24-Jun-87 17:23")

          (* * fgh 5/23/86 Renamed to NC.OpenNoteFile from NC.OpenDatabaseFile. Total revamp to implement device vector.)



          (* * kef 7/18/86: Inserted a call to stuff the UID into the NoteFile because BuildHashArray needed it.)



          (* * kef 7/21/86: Moved up the install of the NoteFile into the NoteFileHashArray to before the building of the 
	  NoteFile's hash array. The reason is that the remote multi client build hash array function needs to get a list of 
	  UIDs, and in order to do this, it needs to grab a Courier stream for the NoteFile given only the UID.
	  It can only do this if the UID is registered in the NoteFilesHashArray.)



          (* * fgh 8/31/86 Updated to account for changes made to system since 5/23/86 revamp. Changes reimplemented include:
	  (fgh 6/8/86 Added code to insure that two files with SameUIDP would never be open at once.) 
	  (fgh 6/25/86 Added contention locks -- NC.ProtectedNoteFileOperation, Don'tCheckOperationInProgressFlg etc.) 
	  (fgh 6/27/86 Added MenuPsotion arg to pass to SetUpNoteFileInterface) (kirk 15Jul86 Added call to 
	  NC.SetUpNoteFileInterface if already open))



          (* * fgh 9/1/86 Reimplemented ReadOnly NoteFile open.)



          (* * fgh 9/4/86 Put in default for NoteFilesHashArray which is NC.NoteFilesHashArray)



          (* * kirk/rht 8/29/86: Now resets Name after conversion from version 2 to version3.)



          (* * rht 10/29/86: Changed "aborted" to "canceled" in message.)



          (* * rht 10/31/86: Added Don'tCheckForTruncationFlg arg.)



          (* * rht&pmi 11/21/86: Took away the protection from around the AFTER call to open events fns.)



          (* * pmi 12/12/86: Added InterestedWindow argument to NC.SetUpNoteFileInterface so that it can print a prompt to 
	  the user about placing the NoteFile menu.)



          (* * rg 3/4/87 Added NC.ProtectedSessionOperation wrapper, removed Don'tCheckOperationsInProgressFlg)



          (* * rht 3/25/87: Now calls NC.CoerceToInterestedWindow.)



          (* * pmi 3/31/87: Moved line of code which sets the ReadOnlyFlg to just after the test for an open notefile.
	  Otherwise, a notefile opened read-only could be changed to one opened normally.)



          (* * rht 4/2/87: Now passes InterestedWindow to opennotefilefns.)



          (* * rg 4/2/87 enlarged scope of NC.ProtectedNoteFileOperation)



          (* * RG 4/3/87 replaced missing InterestedWindow arg to OpenNoteFileFn)



          (* * pmi 5/19/87: Removed NoteFilesHashArray argument. Replaced call to NC.StoreNoteFileInHashArray with 
	  NC.NoticeNoteFile in general cleanup.)



          (* * pmi 5/20/87: Moved the open test up to almost the beginning of the function.)



          (* * pmi 5/29/87: Deleted extra InterestedWindow argument to NC.ProtectedNoteFileOperation.
	  Added call to NC.RemoveAccessToNoteFile to "unnotice" this notefile if the file does not exist, and remove its 
	  icon, if it has one. If InterestedWindow is the window for this NoteFile's interface, then change it to 
	  NC.NoteCardsIconWindow.)



          (* * pmi 6/3/87: Added check and warning for filenames which do not have the .notefile extension and which have not
	  yet been noticed (operated on) by NoteCards.)



          (* * rht&pmi 6/4/87: Added TempInterestedWindow var to use until real InterestedWindow can be computed.)



          (* * rht 6/8/87: Fixed what happens for notefiles with bad headers.)



          (* * pmi 6/24/87: Added "(Highest version)" to question about opening highest version of a file.
	  Added Don'tCheckVersionFlg for Create and Compact, which have already figured out the correct version.)


    (DECLARE (GLOBALVARS NC.OpenNoteFileFns NC.LastNoteFileOpened))

          (* * NOTE: Session lock turns into NoteFile lock after NoteFile is created)


    (PROG ((TempInterestedWindow (OR InterestedWindow (NC.CoerceToInterestedWindow 
									       NoteFileOrFileName)))
	     NoteFile FileName NewerFileName OldVersion NewVersion NoteFileMenu ReturnValue 
	     CriticalUIDs)

          (* * Figure out the name of the file containing the NoteFile)


	    (if [NULL (SETQ FileName (if (type? NoteFile NoteFileOrFileName)
					       then (fetch (NoteFile FullFileName) of 
									       NoteFileOrFileName)
					     elseif NoteFileOrFileName
					     else (NC.DatabaseFileName 
								      "Name of NoteFile to open:"
									   " -- " T NIL NIL 
									   TempInterestedWindow]
		then (RETURN NIL))

          (* * Check for the .NoteFile extension if this notefile has not been noticed by NoteCards.)


	    (if (AND (NEQ (U-CASE (FILENAMEFIELD FileName (QUOTE EXTENSION)))
				(QUOTE NOTEFILE))
			 (NOT (NC.NoteFileNoticedP FileName)))
		then (NC.PrintMsg InterestedWindow T FileName 
				      " does not have a .NOTEFILE extension."
				      (CHARACTER 13))
		       (if (NULL (NC.AskYesOrNo (CONCAT "Are you sure you want to open " 
								FileName " as a NoteFile?")
						      " -- " "No" NIL InterestedWindow T NIL))
			   then (NC.ClearMsg InterestedWindow T)
				  (RETURN NIL)))

          (* * If this is an open NoteFIle, just bring up its menu.)


	    (if (NC.NoteFileOpenP FileName)
		then (OR Don'tCreateInterfaceFlg (NC.SetUpNoteFileInterface (
									  NC.NoteFileFromFileName
										    FileName)
										  MenuPosition 
									     TempInterestedWindow))
		       (NC.ClearMsg TempInterestedWindow T) 
                                                             (* bring up or create notefile icon if needed)
		       (RETURN NIL))

          (* * Check for higher version of same notefile)


	    [if (AND (NOT Don'tCheckVersionFlg)
			 (SETQ OldVersion (FILENAMEFIELD FileName (QUOTE VERSION)))
			 (SETQ NewVersion (FILENAMEFIELD (SETQ NewerFileName
							       (FULLNAME (PACKFILENAME
									     (QUOTE VERSION)
									     NIL
									     (QUOTE BODY)
									     FileName)))
							     (QUOTE VERSION)))
			 (LESSP OldVersion NewVersion))
		then 

          (* * Notify user)


		       (NC.PrintMsg TempInterestedWindow T "A higher version of " FileName 
				      " exists."
				      (CHARACTER 13))

          (* * Open the version the user requests.)


		       (if (NC.AskYesOrNo (CONCAT "Open " NewerFileName 
							" instead? (Highest version)")
					      " -- " "No" NIL TempInterestedWindow T NIL)
			   then (SETQ FileName NewerFileName)
				  (SETQ NoteFileOrFileName (NC.NoteFileFromFileName FileName))
				  (if (SETQ NoteFileMenu (NC.GetNoteFileMenu FileName))
				      then (NC.SetNoteFileMenu NoteFileOrFileName NoteFileMenu]

          (* * Create a NoteFile object or use existing notefile object if there is one for this file name.)


	    [SETQ NoteFile (if (type? NoteFile NoteFileOrFileName)
				 then NoteFileOrFileName
			       else (OR (NC.NoteFileFromFileName FileName)
					    (create NoteFile]
	    (replace (NoteFile FullFileName) of NoteFile with FileName)
	    (OR InterestedWindow (SETQ InterestedWindow (NC.CoerceToInterestedWindow NoteFile)))
	    (RETURN
	      (NC.ProtectedNoteFileOperation
		NoteFile "Open NoteFile" InterestedWindow
		(PROG NIL

          (* * Figure out the appropriate device vector from the file name.)


		        (NC.InstallDeviceVectorInNoteFile NoteFile PublicOrPrivate)

          (* * Moved this replace to after test for open notefile. Otherwise, if notefile is open read-only, it well be 
	  changed to regular open.)


		        (replace (NoteFile ReadOnlyFlg) of NoteFile with ReadOnlyFlg)

          (* * Notify user.)


		        (OR QuietFlg (NC.PrintMsg InterestedWindow T "Opening NoteFile: " 
						      FileName " ..." (CHARACTER 13)))
		        (SETQ ReturnValue
			  (PROG NIL

          (* * Run through OpenNoteFileFns with param of BEFORE. Exit if any returns DON'T)


			          (if [for Function in NC.OpenNoteFileFns
					   thereis (OR (EQ Function (QUOTE DON'T))
							   (EQ (QUOTE DON'T)
								 (APPLY* Function FileName NoteFile
									   (QUOTE BEFORE)
									   InterestedWindow]
				      then (if (WINDOWP InterestedWindow)
						 then (NC.PrintMsg InterestedWindow NIL 
								    "Open canceled for NoteFile "
								       FileName "." (CHARACTER
									 13))
							(DISMISS NC.MsgDelay)
							(NC.ClearMsg InterestedWindow T))
					     (RETURN))

          (* * Call the device specific OpenNoteFileFn, which returns a list of special UIDs)


			          (if [NULL (ERSETQ (SETQ ReturnValue
							    (APPLY* (fetch (NoteFile 
										   OpenNoteFileFn)
									 of NoteFile)
								      NoteFile InterestedWindow 
								      Don'tCheckForTruncationFlg]
				      then (SETQ ReturnValue (QUOTE NoteFileOpenFailed)))

          (* * Process error returns from the OpenNoteFileFn)


			          (if (NOT (LITATOM ReturnValue))
				      then 

          (* * OpenNoteFileFn returned correctly)


					     (SETQ CriticalUIDs ReturnValue)
				    else

          (* * Error, process it.)


				     (SETQ ReturnValue
				       (OR [SELECTQ
					       ReturnValue
					       (NoteFileNotFound (NC.RemoveAccessToNoteFile 
											 NoteFile)
								 (SETQ InterestedWindow
								   (NC.CoerceToInterestedWindow
								     InterestedWindow))
								 (NC.ProcessNoteFileNotFoundError
								   NoteFile 
								   Don'tCacheTypesAndTitlesFlg 
								   Don'tCreateFlg ConvertNoConfirmFlg 
								   Don'tCreateArrayFlg 
								   Can'tTruncateFlg 
								   Don'tCreateInterfaceFlg 
								   Don'tGetSpecialCardsFlg 
								   InterestedWindow PublicOrPrivate 
								   MenuPosition QuietFlg ReadOnlyFlg 
								   Don'tCheckForTruncationFlg))
					       (NoteFileNeedsConversion (
							   NC.ProcessNoteFileNeedsConversionError
									  NoteFile 
								      Don'tCacheTypesAndTitlesFlg 
									  Don'tCreateFlg 
									  ConvertNoConfirmFlg 
									  Don'tCreateArrayFlg 
									  Can'tTruncateFlg 
									  Don'tCreateInterfaceFlg 
									  Don'tGetSpecialCardsFlg 
									  InterestedWindow 
									  PublicOrPrivate 
									  MenuPosition QuietFlg 
									  ReadOnlyFlg 
								       Don'tCheckForTruncationFlg))
					       (NoteFileNeedsTruncation (
							   NC.ProcessNoteFileNeedsTruncationError
									  NoteFile 
								      Don'tCacheTypesAndTitlesFlg 
									  Don'tCreateFlg 
									  ConvertNoConfirmFlg 
									  Don'tCreateArrayFlg 
									  Can'tTruncateFlg 
									  Don'tCreateInterfaceFlg 
									  Don'tGetSpecialCardsFlg 
									  InterestedWindow 
									  PublicOrPrivate 
									  MenuPosition QuietFlg 
									  ReadOnlyFlg 
								       Don'tCheckForTruncationFlg))
					       [NoteFileAlreadyOpen
						 (ERSETQ (NC.ReportError
							     NIL
							     (CONCAT (fetch (NoteFile 
										     FullFileName)
									  of NoteFile)
								       
					    " is already open for exclusive access. Open failed."]
					       [NoteFileOpenFailed
						 (ERSETQ (NC.ReportError
							     NIL
							     (CONCAT "Open of "
								       (fetch (NoteFile 
										     FullFileName)
									  of NoteFile)
								       " failed for unknown reason."]
					       [(NoteFileHeaderBad BadNextIndexNum BadHashArraySize 
								   BadCheckptPtr BadNextLinkNum)
						 (ERSETQ (NC.ReportError
							     NIL
							     (CONCAT "Header of NoteFile "
								       (fetch (NoteFile 
										     FullFileName)
									  of NoteFile)
								       " is bad: " ReturnValue 
								 ".  Contact a NoteCards wizard."]
					       (PROGN (ERSETQ (NC.ReportError NIL
										    (CONCAT 
									   "Unknown error code ("
											      
										      ReturnValue 
						     ") returned by OpenNoteFileFn for NoteFile "
											      
											 FileName]
					     ReturnValue))

          (* * notify the user. if there's been a problem)


				     (if (AND (NOT (type? NoteFile ReturnValue))
						  (WINDOWP InterestedWindow))
					 then (NC.PrintMsg InterestedWindow NIL 
							       "Open canceled for NoteFile "
							       FileName "." (CHARACTER 13))
						(DISMISS NC.MsgDelay)
						(NC.ClearMsg InterestedWindow T))

          (* * return whatever the error processing returned.)


				     (RETURN ReturnValue))
			          (SETQ ReturnValue)

          (* * Make sure there is no other open NF with this UID.)


			          (LET (NF)
				       (if (AND (SETQ NF (GETHASH (fetch (
NoteFileCriticalUIDs NoteFile) of CriticalUIDs)
									  NC.NoteFilesHashArray))
						    (NEQ (fetch (NoteFile FullFileName)
							      of NoteFile)
							   (fetch (NoteFile FullFileName)
							      of NF))
						    (NC.NoteFileOpenP NF))
					   then (FLASHW PROMPTWINDOW)
						  (NC.PrintMsg PROMPTWINDOW T "Couldn't open " 
								 FileName (CHARACTER 13)
								 "because "
								 (fetch (NoteFile FullFileName)
								    of NF)
								 " is already open "
								 (CHARACTER 13)
								 "and has the same UID.")
						  (NC.CloseNoteFile NoteFile InterestedWindow T)
						  (RETURN NIL)))

          (* * If needed, build a hash array by calling the device specific BuilHashArrayFn.)


			          (replace (NoteFile UID) of NoteFile with (fetch
										   (
NoteFileCriticalUIDs NoteFile) of CriticalUIDs))

          (* * Store this NoteFile object in the appropriate NoteFile hash array)


			          (NC.NoticeNoteFile NoteFile)
			          (if (NOT Don'tCreateArrayFlg)
				      then
				       (OR QuietFlg (NC.PrintMsg InterestedWindow T 
								     "Opening NoteFile: "
								     FileName
								     (CHARACTER 13)
								     "Building index array ..."
								     (CHARACTER 13)))
				       (if
					 (OR [NULL (ERSETQ (SETQ ReturnValue
								   (APPLY*
								     (fetch (NoteFile 
										 BuildHashArrayFn)
									of NoteFile)
								     NoteFile QuietFlg 
								     InterestedWindow
								     (CONCAT "Opening NoteFile "
									       (fetch (NoteFile
											  
										     FullFileName)
										  of NoteFile)
									       (CHARACTER 13]
					       (NOT (type? NoteFile ReturnValue)))
					   then 

          (* * Error during building of hash array)


						  (ERSETQ (NC.ReportError
							      NIL
							      (CONCAT 
							  "Build Hash Array failed for NoteFile "
									(fetch (NoteFile 
										     FullFileName)
									   of NoteFile)
									" because " ReturnValue)))
						  (RETURN)))

          (* * Set up critical UIDs in NoteFile object using the values returned from OpenNoteFileFn.)


			          (NC.InstallCriticalUIDsInNoteFile NoteFile CriticalUIDs)

          (* * if needed, cache the special cards)


			          [if (NOT Don'tGetSpecialCardsFlg)
				      then (NC.GetSpecialCards NoteFile QuietFlg InterestedWindow
								   (CONCAT "Opening NoteFile: "
									     (fetch (NoteFile
											FullFileName)
										of NoteFile)
									     (CHARACTER 13]

          (* * If needed, start the titles and types caching process)


			          [if (NOT Don'tCacheTypesAndTitlesFlg)
				      then (replace (NoteFile CachingProcess) of NoteFile
						with (ADD.PROCESS (LIST (FUNCTION 
									   NC.CacheTypesAndTitles)
									      NoteFile]

          (* * If needed, open up a NoteFile interface.)


			          (if (NOT Don'tCreateInterfaceFlg)
				      then (NC.SetUpNoteFileInterface NoteFile MenuPosition 
									  InterestedWindow))

          (* * Record this as the last NF opened.)


			          (SETQ NC.LastNoteFileOpened NoteFile)
			          (RETURN NoteFile)))
		        (if (type? NoteFile ReturnValue)
			    then 

          (* * Run through OpenNoteFIleFns with param of AFTER. Stop if any returns DON'T)


				   (for Function in NC.OpenNoteFileFns
				      thereis (EQ (QUOTE DON'T)
						      (APPLY* Function FileName NoteFile
								(QUOTE AFTER)
								InterestedWindow)))

          (* * Go home, returning NoteFile)


				   (if (NULL QuietFlg)
				       then (NC.PrintMsg InterestedWindow T "Opening NoteFile: " 
							     FileName (CHARACTER 13)
							     "Done."
							     (CHARACTER 13))
					      (NC.ClearMsg InterestedWindow T))
				   (RETURN NoteFile)
			  else 

          (* * Bail out if open was unsuccessful.)


				 (RETURN NIL])

(NC.StoreNoteFileInHashArray
  [LAMBDA (NoteFileOrFileName)                               (* pmi: "20-May-87 11:59")

          (* * store NoteFile in HashArray, a NoteFiles hash array.)



          (* * fgh 5/23/86 First created.)



          (* * Are there any other NoteFiles of the same fullfilename here? If so, something got messed up.
	  Remove these items.)



          (* * pmi 5/19/87: Removed HashArray argument -
	  this function only applies to NC.NoteFilesHashArray.)


    (DECLARE (GLOBALVARS NC.NoteFilesHashArray))
    (LET [(NoteFile (if (type? NoteFile NoteFileOrFileName)
			then NoteFileOrFileName
		      else (NC.NoteFileFromFileName NoteFileOrFileName]
         (if NoteFile
	     then [MAPHASH NC.NoteFilesHashArray (FUNCTION (LAMBDA (NF UID)
				   (if (EQ (fetch (NoteFile FullFileName) of NoteFile)
					       (fetch (NoteFile FullFileName) of NF))
				       then (PUTHASH UID NIL NC.NoteFilesHashArray]

          (* * Okay, now put in the new entry)


		    (PUTHASH (fetch (NoteFile UID) of NoteFile)
			       NoteFile NC.NoteFilesHashArray])

(NC.FindNextCardPart
  [LAMBDA (NoteFile StartPtr)                                (* rht: "16-May-87 00:59")

          (* * Start searching at the current stream pointer in NoteFile for the next card part. Return a "CardPartRecord" if
	  successful containing file loc, card uid and card part type number. This code largely stolen from 
	  NC.RobustReadCardPart from NCREPAIR. Notice the calls to NCREPAIR fns.)


    (DECLARE (GLOBALVARS NC.TitlesIdentifier NC.PropsIdentifier NC.LinksIdentifier 
			     NC.ItemIdentifier))
    (LET ((Stream (fetch (NoteFile Stream) of NoteFile))
	  EndPtr CardPartPtr IdentifierAndVersionNum IdentifierAtom UID CardPartLength 
	  CardPartTypeNum)
         (SETQ EndPtr (GETEOFPTR Stream))
         (SETQ CardPartPtr (NC.SearchFor### Stream StartPtr))
         (for
	    do                                             (* Keep looping till we find a reasonable card part.)
		 (if (AND (SETQ CardPartLength (NC.ReadPtr Stream 3))
			      (LEQ (PLUS CardPartPtr CardPartLength)
				     EndPtr)
			      (SETQ IdentifierAndVersionNum (NC.RobustReadItemIdentifier Stream))
			      (if (GEQ (CDR IdentifierAndVersionNum)
					   1)
				  then (NC.RobustReadDate Stream)
				else T)
			      (SETQ UID (NC.RobustReadUID Stream)))
		     then (SETQ IdentifierAtom (CAR IdentifierAndVersionNum))
			    (SETQ CardPartTypeNum (COND
				((EQ IdentifierAtom NC.ItemIdentifier)
				  0)
				((EQ IdentifierAtom NC.LinksIdentifier)
				  1)
				((EQ IdentifierAtom NC.TitlesIdentifier)
				  2)
				((EQ IdentifierAtom NC.PropsIdentifier)
				  3)))
			    (RETURN (create CardPartRecord
						FileLoc ← CardPartPtr
						UID ← UID
						CardPartTypeNum ← CardPartTypeNum
						CardPartLength ← CardPartLength))
		   else (if [NULL (SETQ CardPartPtr (NC.SearchFor### Stream
									       (PLUS CardPartPtr 4]
			      then                         (* We've reached EOF without finding a card part.)
				     (RETURN NIL])

(NC.ForceDatabaseClose
  [LAMBDA (NoteFile Don'tMenuFlg)                            (* pmi: "19-Aug-87 15:06")

          (* * Really close the database, i.e.. bypass the ADVISE on CLOSEF that prevents closing of the database.)



          (* * rht 1/10/85: Note new kludgey call to \UPDATEOF recommended by Tayloe to avoid truncation problems.)



          (* * rht 2/5/85: Added resetting of NC.UncachingNotCompleted here so it will happen after compact, repair, etc.)



          (* * rht 7/9/85: Added resetting of NC.LinkLabelsDate.)



          (* * rht 11/10/85: Updated to incorporate new NoteFile scheme.)



          (* * kirk 31Dec85: added Don'tMenuFlg)



          (* * rht 1/8/86: Now smashes old notefile object to remove cycles. Don't you love interlisp gc'er?)



          (* * rht 5/1/86: Save Menu on notefile object when smashing.)



          (* * rht 7/6/86: Only closes notefile's stream if there is an open one.)



          (* * fgh 9/1/86 Now saves the Device vector when cleaning up the NoteFile object.)



          (* * pmi 5/19/87: Replaced call to NC.RemoveNoteFileFromHashArray with NC.RemoveNoteFile as part of general 
	  cleanup.)



          (* * pmi 8/19/87: Added call calls to NC.NoticeNoteFile and NC.ResetNoteFileInterface.)


    (CLOSEF? (fetch (NoteFile Stream) of NoteFile))    (* Smash the cardcache and userdata fields of all card
							     objects for this notefile to remove circular links.)
    (ADD.PROCESS (LIST (FUNCTION NC.CleanupCardObjects)
			   (fetch (NoteFile HashArray) of NoteFile)))
    (replace (NoteFile Stream) of NoteFile with NIL)   (* Smash the notefile object so we don't have cycles -
							     card -> notefile -> card.)
                                                             (* Usually we leave shell in notefiles hash array so 
							     there's a record.)
    (create NoteFile smashing NoteFile UID ← (fetch (NoteFile UID) of NoteFile)
				  FullFileName ← (fetch (NoteFile FullFileName) of NoteFile)
				  Menu ← (fetch (NoteFile Menu) of NoteFile)
				  NoteFileDevice ← (fetch (NoteFile NoteFileDevice) of NoteFile))

          (* * Reset the notefile menu icon to look closed.)


    (NC.ResetNoteFileInterface NoteFile)

          (* * Make sure the notefile has been noticed.)


    (NC.NoticeNoteFile NoteFile)
    (if Don'tMenuFlg
	then (NC.RemoveNoteFile NoteFile))
    NoteFile])

(NC.RemoveNoteFileFromHashArray
  [LAMBDA (NoteFile)                                         (* pmi: "21-May-87 11:16")

          (* * Remove this notefile from the global hash array.)



          (* * pmi 5/21/87: Service function called by NC.RemoveNoteFile.)


    (DECLARE (GLOBALVARS NC.NoteFilesHashArray))
    (LET ((NoteFileUID (fetch (NoteFile UID) of NoteFile)))
         (if (AND NoteFile NoteFileUID)
	     then (PUTHASH NoteFileUID NIL NC.NoteFilesHashArray])

(NC.CreateNoteFile
  [LAMBDA (NoteFileOrFileName SizeInCards Don'tCreateSpecialCards InterestedWindow OperationMsg 
			      QuietFlg PublicOrPrivate OpenFlg ReadOnlyFlg Don'tCreateInterfaceFlg 
			      MenuPosition)                  (* pmi: "24-Jun-87 17:24")

          (* * Create a NoteFile. Most of the work should be done by the device specific create notefile fn.)



          (* * fgh 9/1/86 First created.)



          (* * fgh&rht 9/5/86: Now creates small temporary hash array.)



          (* * pmi 5/20/87: Added call to NC.SetUpNoteFileInterface to create a closed NoteFile Icon after creating the 
	  NoteFile. Now asks if next version should be created if file already exists.)



          (* * pmi 6/24/87: Had to strip version number from filename even when it doesn't exist, in case it came in with the
	  version number of a non-existent file.)


    (DECLARE (GLOBALVARS NC.MsgDelay))
    (PROG (NoteFile NoteFileName NoteFileFullName ReturnValue)

          (* * Get the name from the user if necessary.)


	    [SETQ NoteFileName (if (type? NoteFile NoteFileOrFileName)
				     then (fetch (NoteFile FullFileName) of NoteFileOrFileName)
				   else (OR NoteFileOrFileName
						(NC.DatabaseFileName 
						    "What is the name of the file to be created?"
								       " -- " T T NIL 
								       InterestedWindow]
	    (if (NULL NoteFileName)
		then (RETURN (QUOTE CreateCancelled)))

          (* * Check to see if a file by this name already exists.)


	    [if (FILENAMEFIELD NoteFileName (QUOTE VERSION))
		then 

          (* * A version has been specified -
	  make sure it does not already exist.)


		       (if (SETQ NoteFileFullName (FULLNAME NoteFileName (QUOTE OLD)))
			   then 

          (* * This file already exists as this version.)



          (* * Notify user)


				  (NC.PrintMsg InterestedWindow T "NoteFile " NoteFileFullName 
						 " already exists."
						 (CHARACTER 13))

          (* * If the user wants to create the file, then create the next version of it.)


				  (SETQ NoteFileFullName (FULLNAME (PACKFILENAME (QUOTE
											 VERSION)
										       NIL
										       (QUOTE
											 BODY)
										       
										 NoteFileFullName)
								       (QUOTE NEW)))
				  (if (NC.AskYesOrNo (CONCAT "Do you want to create " 
								   NoteFileFullName 
								   " (next available version)?")
							 " -- " "N" NIL InterestedWindow T NIL)
				    else (NC.PrintMsg InterestedWindow NIL "Create cancelled."
							  (CHARACTER 13))
					   (DISMISS NC.MsgDelay)
					   (NC.ClearMsg InterestedWindow T)
					   (RETURN (QUOTE CreateCancelled)))
			 else 

          (* * This is already a valid new full file name; use it.)


				(SETQ NoteFileFullName NoteFileName))
	      else 

          (* * No version specified, use the next available one.)


		     (SETQ NoteFileFullName (FULLNAME NoteFileName (QUOTE NEW]

          (* * Create a NoteFile object with a UID, etc.)


	    [SETQ NoteFile (if (type? NoteFile NoteFileOrFileName)
				 then NoteFileOrFileName
			       else (OR (NC.NoteFileFromFileName NoteFileFullName)
					    (create NoteFile]
	    (replace (NoteFile UID) of NoteFile with (NC.MakeUID))
	    (replace (NoteFile MonitorLock) of NoteFile with (CREATE.MONITORLOCK
								     (QUOTE Creating% NoteFile)))
	    (replace (NoteFile FullFileName) of NoteFile with NoteFileFullName)
	    (replace (NoteFile ReadOnlyFlg) of NoteFile with NIL)

          (* * only a small hash array for creating a file.)


	    [replace (NoteFile HashArray) of NoteFile
	       with (NC.CreateUIDHashArray (CONSTANT (LENGTH (RECORDFIELDNAMES
								       (QUOTE NoteFileCriticalUIDs]

          (* * Install the appropriate device vector)


	    (NC.InstallDeviceVectorInNoteFile NoteFile PublicOrPrivate)

          (* * Say something to the user.)


	    (OR QuietFlg (NC.PrintMsg InterestedWindow T (OR OperationMsg "")
					  "Creating NoteFile " NoteFileFullName ".  Please wait...  ")
		  )

          (* * Call the device specific create notefile fn.)


	    (if [type? NoteFile (SETQ ReturnValue (CAR (ERSETQ (APPLY*
									   (fetch (NoteFile 
										 CreateNoteFileFn)
									      of NoteFile)
									   NoteFile SizeInCards 
									   InterestedWindow 
									   OperationMsg QuietFlg]
		then 

          (* * Device specific Create NoteFile fn returned okay. Go an an create the special cards.)


		       (if Don'tCreateSpecialCards
			 else (replace (NoteFile NextIndexNum) of NoteFile with 1)
				(NC.InitializeSpecialCards NoteFile))

          (* * Checkpoint the NF, then close it and return the NF objet.)


		       (NC.CheckpointNoteFile NoteFile QuietFlg T InterestedWindow OperationMsg)
		       (if [type? NoteFile (SETQ ReturnValue
					(CAR (ERSETQ (APPLY* (fetch (NoteFile CloseNoteFileFn)
								      of NoteFile)
								   NoteFile SizeInCards 
								   InterestedWindow OperationMsg 
								   QuietFlg]
			   then                            (* Close went okay.)
				  (if (NULL QuietFlg)
				      then (NC.PrintMsg InterestedWindow NIL "Done!"
							    (CHARACTER 13))
					     (NC.ClearMsg InterestedWindow T))
                                                             (* Clean out the NF object and "notice it".)
				  (create NoteFile smashing NoteFile UID ← (fetch (NoteFile
											  UID)
										  of NoteFile)
								FullFileName ← (fetch (NoteFile
											  
										     FullFileName)
										  of NoteFile)
								Menu ← (fetch (NoteFile Menu)
									  of NoteFile)
								NoteFileDevice ← (fetch
								  (NoteFile NoteFileDevice)
										    of NoteFile))

          (* * If needed, create a closed NoteFile interface.)


				  (if (AND (NULL Don'tCreateInterfaceFlg)
					       (NULL OpenFlg))
				      then (NC.SetUpNoteFileInterface NoteFile MenuPosition 
									  InterestedWindow))

          (* * Notice the notefile)


				  (NC.NoticeNoteFile NoteFile) 

          (* * Open the notefile, if requested)


				  (if OpenFlg
				      then (NC.OpenNoteFile NoteFile NIL T NIL NIL NIL 
								Don'tCreateInterfaceFlg NIL 
								InterestedWindow PublicOrPrivate 
								MenuPosition QuietFlg ReadOnlyFlg NIL 
								T))
                                                             (* Set the DatabaseFileNameSuggestion)
				  (SETQ NC.DatabaseFileNameSuggestion (PACKFILENAME
				      (QUOTE VERSION)
				      NIL
				      (QUOTE BODY)
				      (fetch (NoteFile FullFileName) of NoteFile)))
                                                             (* Return the NoteFile.)
				  (RETURN NoteFile)
			 else                              (* Problems with closing the NoteFile -- error)
				(NC.ReportError "NC.CreateNoteFile" (CONCAT 
					"Could not close notefile after it was created because: "
										ReturnValue))
				(RETURN ReturnValue))
	      else 

          (* * There was an error in the device specific create notefile fn.)


		     (NC.ReportError "NC.CreateNoteFile" (CONCAT 
							      "Could not create NoteFile due to "
								     ReturnValue " error."))
		     (RETURN ReturnValue])

(NC.PutNoteFileHeader
  [LAMBDA (NoteFile)                                         (* rht: "15-Nov-85 20:31")

          (* * Write down to the notefile the header information extracted from the NoteFile object.)


    (LET ((Stream (fetch (NoteFile Stream) of NoteFile))
	  (FullFileName (fetch (NoteFile FullFileName) of NoteFile))
	  (UID (fetch (NoteFile UID) of NoteFile))
	  (NextIndexNum (fetch (NoteFile NextIndexNum) of NoteFile))
	  (HashArraySize (fetch (NoteFile HashArraySize) of NoteFile))
	  (NextLinkNum (fetch (NoteFile NextLinkNum) of NoteFile))
	  (CheckptPtr (fetch (NoteFile CheckptPtr) of NoteFile))
	  (Version (fetch (NoteFile Version) of NoteFile)))
         (WITH.MONITOR (NC.FetchMonitor NoteFile)
		       (if (OPENP Stream)
			   then                            (* Fill in the 30 information bytes for the notefile.)
				  (SETFILEPTR Stream 0)    (* 3 bytes for next card ID)
				  (NC.WritePtr Stream NextIndexNum 3) 
                                                             (* 3 bytes for index size)
				  (NC.WritePtr Stream HashArraySize 3) 
                                                             (* One dummy byte so that version number stays in 
							     favorite old place.)
				  (NC.WritePtr Stream -1 1) 
                                                             (* 1 byte for notecards version number)
				  (NC.WritePtr Stream Version 1) 
                                                             (* 3 bytes for next link ID)
				  (NC.WritePtr Stream NextLinkNum 3) 
                                                             (* 3 bytes for pointer to current checkpt ptr.)
				  (NC.WritePtr Stream CheckptPtr 3) 
                                                             (* 14 bytes for NoteFile UID.)
				  (NC.WriteUID NoteFile UID) 
                                                             (* 1 bytes for future needs)
				  (NC.WritePtr Stream -1 1)
				  NoteFile
			 else (NC.ReportError NIL "NC.PutNoteFileHeader: Stream not open!!!"])

(NC.CopyCardPartInPlaceToEOF
  [LAMBDA (NoteFile CardPartRecord TempStream InterestedWindow)
                                                             (* rht: "15-May-87 22:01")

          (* * This copies given card part to the end of the notefile.)


    (LET ((FromPtr (fetch (CardPartRecord FileLoc) of CardPartRecord))
	  (UID (fetch (CardPartRecord UID) of CardPartRecord))
	  (CardPartTypeNum (fetch (CardPartRecord CardPartTypeNum) of CardPartRecord)))
         (WITH.MONITOR (NC.FetchMonitor NoteFile)
		       (LET ((Stream (fetch (NoteFile Stream) of NoteFile))
			     EOFPtr Length)
			    (SETQ EOFPtr (GETEOFPTR Stream))

          (* * Copy the substance out to the {NODIRCORE} stream.)


			    (SETQ Length (NC.CopyCardPart Stream TempStream FromPtr 0 
							      InterestedWindow))

          (* * Now copy to its proper home.)


			    (if (NC.CopyCardPart TempStream Stream 0 EOFPtr InterestedWindow)
				then (NC.UpdateIndexLocIfNeeded NoteFile UID CardPartTypeNum 
								    FromPtr EOFPtr)
				       (PLUS EOFPtr Length])

(NC.GetLinks
  [LAMBDA (Card OverrideStream)                              (* rht: "13-Mar-87 17:06")

          (* * rht 1/31/85: Now reads pointers from index array.)



          (* * rht 2/9/85: Now fixes display formats on links read in.)



          (* * rht 7/9/85: Now gets date if notefile has newer data format.)



          (* * fkr 11/8/85 Updated to handle new Card scheme and NoteFile objects.)



          (* * fgh 11/20/85 Added call to NC.ReadCardPartHeader)



          (* * rht 1/23/86: Now takes optional OverrideStream arg. This, if given, overrides stream of card's notefile.)



          (* * rht 1/28/86: Now passes extra arg to NC.ReadCardPartHeader indicating that when we're overriding the notefile 
	  stream, you shouldn't force UIDs on stream and in card to match.)



          (* * kef 7/16/86: Uses the device vector GetCardPartFn to set up the stream and stream pointer for reading.)



          (* * kef 8/1/86: Moved the check for ACTIVE status to beginning.)



          (* * fgh 8/31/86 Adapted to use NC.DoCardPartFn.)



          (* * pmi 11/4/86 Reinstated Randy's changes (1/23/86 and 1/28/86) which somehow got lost.)



          (* * rht 3/13/87: No longer goes to notefile if card hasn't been saved yet.)


    (DECLARE (GLOBALVARS NC.LinksIdentifier))
    (if (AND (EQ (fetch (Card Status) of Card)
		       (QUOTE ACTIVE))
		 (NOT (NC.FetchNewCardFlg Card)))
	then (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
			     (NC.DoCardPartFn Get Card (QUOTE LINKS)
					      (LET [(Stream (OR (STREAMP OverrideStream)
								  (NC.CoerceToNoteFileStream Card]

          (* * Read the header and set the date)


					           (NC.SetLinksDate Card
								      (NC.ReadCardPartHeader Card 
									       NC.LinksIdentifier 
											   Stream 
										   OverrideStream))

          (* * Read the links)


					           (NC.SetToLinks Card (NC.ReadListOfLinks Stream)
								    )
					           (NC.SetFromLinks Card (NC.ReadListOfLinks
									Stream))
					           (NC.SetGlobalLinks Card (NC.ReadListOfLinks
									  Stream))
					           (NC.SetLinksDirtyFlg Card NIL)
					       Card])

(NC.ReadCardPartHeader
  [LAMBDA (Card Identifier Stream Don'tCheckForIDMismatchFlg)
                                                             (* rht: "28-Jan-86 15:01")

          (* * Read the header for a card part and return the date from the header)



          (* * kirk 22Dec85 added NoteFile local)



          (* * rht 1/23/86: Now takes optional stream arg. This, if given, overrides stream of card's notefile.)



          (* * rht 1/28/86: Now takes Don'tCheckForIDMismatchFlg arg. If non-nil, then don't force UID on stream to match UID
	  of card.)


    (OR (STREAMP Stream)
	  (SETQ Stream (NC.CoerceToNoteFileStream Card)))
    (LET (VersionNumber Date ActualID CardUID)

          (* * Skip the length info)


         (NC.ReadPtr Stream 3)

          (* * Read the identifier and the version)


         (if (NOT (SETQ VersionNumber (NC.ReadIdentifier Stream Identifier)))
	     then (NC.ReportError "NC.ReadCardPartHeader" (CONCAT (NC.FetchTitle Card)
									
								  " Error while reading NoteFile"
									" -- incorrect identifier.")))
         (if (GEQ VersionNumber 1)
	     then (SETQ Date (NC.ReadDate Stream)))
         (SETQ ActualID (NC.ReadUID Stream))
         (if [AND (NOT Don'tCheckForIDMismatchFlg)
		      (NOT (NC.SameUIDP ActualID (SETQ CardUID (fetch (Card UID)
									of Card]
	     then (NC.ReportError "NC.ReadCardPartHeader" (CONCAT 
						 "ID mismatch while reading item.  Expected ID: "
									CardUID "   Found ID: " 
									ActualID)))
     Date])

(NC.PutFromLinks
  [LAMBDA (Card)                                             (* rht: "30-Sep-86 01:00")

          (* * The top level function for writing out only the FROMLINKS of a card. Became a necessary function in the 
	  process of implementing the Server.)



          (* * rht 9/11/86: Now checks for card active via NC.CardActiveP rather than by checking for ACTIVE status.)



          (* * rht 9/30/86: Undid change of 9/11/86. Card may not have ActiveFlg set when we're doing PutFromLinks.)


    (DECLARE (GLOBALVARS NC.LinksIdentifier))            (* Check to make sure this is an active note card.)
    (if (NEQ (NC.FetchStatus Card)
		 (QUOTE ACTIVE))
	then (NC.ReportError "NC.PutFromLinks" (CONCAT (NC.FetchTitle Card)
							     " is not an active note card.")))
    (LET (PutSuccessfulLoc)
         (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
		       (RESETLST (RESETSAVE (APPLY* (fetch (NoteFile PutCardPartFn)
							     of (fetch (Card NoteFile)
								     of Card))
							  Card
							  (QUOTE FROMLINKS)
							  (QUOTE BEFORE))
						(BQUOTE (APPLY* , (fetch (NoteFile 
										    PutCardPartFn)
									 of (fetch (Card NoteFile)
										 of Card))
								    , Card FROMLINKS AFTER)))
				   (LET ((Stream (NC.CoerceToNoteFileStream Card))
					 StartLoc)

          (* * Write the links data at the end of the database file.)


				        (SETQ StartLoc (GETFILEPTR Stream))
				        (NC.WriteCardPartHeader Card NC.LinksIdentifier
								  (NC.SetLinksDate Card (DATE))
								  Stream)
				        (NC.WriteListOfLinks Stream (NC.FetchFromLinks Card))

          (* * Now update the index to point to the link data just written. Done last in case writing of links doesn't 
	  complete okay.)


				        (NC.SetLinksDirtyFlg Card)

          (* * Now, since we were successful, we'll bind the PutSuccessfulLoc variable, which will be used freely by the 
	  AFTER PutCardPartFns to determine first if the Put succeeded, and if so, where in the stream it was Put.)


				        (SETQ PutSuccessfulLoc StartLoc)
				    Card])

(NC.WriteCardPartHeader
  [LAMBDA (Card Identifier Date Stream)                      (* rht: "23-Jan-86 17:50")

          (* * write the header of a card part onto the NoteFile)



          (* * rht 1/23/86: Now takes optional stream arg. This, if given, overrides stream of card's notefile.)


    (OR (STREAMP Stream)
	  (SETQ Stream (NC.CoerceToNoteFileStream Card)))

          (* * leave space for the length information)


    (NC.WritePtr Stream 0 3)

          (* * write the card part identifier)


    (NC.WriteIdentifier Stream Identifier)

          (* * write the date)


    (NC.WriteDate Stream Date)

          (* * write the cards uid)


    (NC.WriteUID Stream (fetch (Card UID) of Card])

(NC.WriteLink
  [LAMBDA (Link Stream)                                      (* rht: " 1-Nov-86 15:06")

          (* * Write a single link DATAYPE instance down to Stream)



          (* * rht 11/1/86: Now uses our readtable when printing.)


    (DECLARE (GLOBALVARS NC.OrigReadTable))
    (LET ((SourceCard (fetch (Link SourceCard) of Link))
	  (DestinationCard (fetch (Link DestinationCard) of Link)))

          (* * This is version 1 link format)


         (NC.WritePtr Stream 1 1)
         (NC.WriteUID Stream (fetch (Link UID) of Link))
         (NC.WriteUID Stream (fetch (Card UID) of SourceCard))
         (NC.WriteUID Stream (fetch (NoteFile UID) of (fetch (Card NoteFile) of SourceCard))
			)
         (NC.WriteUID Stream (fetch (Card UID) of DestinationCard))
         (NC.WriteUID Stream (fetch (NoteFile UID) of (fetch (Card NoteFile) of 
										  DestinationCard)))
         (PRINT (fetch (Link AnchorMode) of Link)
		  Stream NC.OrigReadTable)
         (PRINT (fetch (Link Label) of Link)
		  Stream NC.OrigReadTable)
         (PRINT (fetch (Link DisplayMode) of Link)
		  Stream NC.OrigReadTable])

(NC.PutPropList
  [LAMBDA (Card UseOldDateFlg OverrideStream)                (* rht: " 1-Jul-87 10:23")

          (* * Put the prop list for ID onto the database file.)



          (* * rht 1/30/85: Changed to use index array instead of file.)



          (* * rht 7/9/85: Now puts out date after identifier. If UseOldDateFlg is non-nil, then use old date, otherwise use 
	  current date.)



          (* * rht 11/10/85: Updated to handle NoteFile and Card scheme.)



          (* * fgh 11/20/85 Added call to NC.WriteCardPartHeader and the mechanism to write the start and end pointers of the
	  substance before calling the card type's putfn.)



          (* * rht 1/23/86: Now takes optional OverrideStream arg. This, if given, overrides stream of card's notefile.)



          (* * kef 7/16/86: Makes use of the NoteFile device vector PutCardPartFn.)



          (* * fgh 8/31/86 Adapted to use NC.DoCardPartFn.)



          (* * pmi 11/4/86 Reinstated Randy's change (1/23/86) which somehow got lost.)



          (* * rht 11/14/86: Now makes sure hung var PutSuccessfulLoc is NIL if we were passed an OverrideStream.)



          (* * rht 7/1/87: Now only turns off dirty flg if no OverrideStream.)

                                                             (* Check to make sure this is an active note card.)
    (DECLARE (GLOBALVARS NC.PropsIdentifier))
    (AND (NEQ (fetch (Card Status) of Card)
		  (QUOTE ACTIVE))
	   (NC.ReportError "NC.PutPropList" (CONCAT (NC.FetchTitle Card)
							" is not an active note card.")))
    (LET (PutSuccessfulLoc)
         (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
		       (NC.DoCardPartFn Put Card (QUOTE PROPLIST)
					(LET ((Stream (OR (STREAMP OverrideStream)
							    (NC.CoerceToNoteFileStream Card)))
					      StartLoc EndLoc)

          (* * Write the proplist at the end of the database file.)


					     (SETQ StartLoc (GETFILEPTR Stream))
					     (NC.WriteCardPartHeader Card NC.PropsIdentifier
								       [COND
									 (UseOldDateFlg (
									     NC.FetchPropListDate
											  Card))
									 (T (NC.SetPropListDate
									      Card
									      (DATE]
								       Stream)
					     (NC.WritePropList Stream (NC.FetchPropList Card))

          (* * Update the length field at the beginning of the card info)


					     (SETQ EndLoc (GETFILEPTR Stream))
					     (SETFILEPTR Stream StartLoc)
					     (NC.WritePtr Stream (DIFFERENCE EndLoc StartLoc)
							  3)
					     (SETFILEPTR Stream EndLoc)

          (* * Now update the index to point to the proplist just written. Done last in case writing of proplist doesn't 
	  complete okay.)


					     (OR OverrideStream (NC.SetPropListDirtyFlg Card))

          (* * Now, since we were successful, we'll bind the PutSuccessfulLoc variable, which will be used freely by the 
	  AFTER PutCardPartFns to determine first if the Put succeeded, and if so, where in the stream it was Put.)



          (* * Don't put a reasonable value in the hung variable PutSuccessfulLoc if we were passed OverrideStream.)


					     (SETQ PutSuccessfulLoc
					       (if OverrideStream
						   then NIL
						 else StartLoc))
					 Card])

(NC.GetPropList
  [LAMBDA (Card OverrideStream)                              (* rht: "13-Mar-87 17:03")
                                                             (* Retrieve the prop list for card specified by ID 
							     from the database specified by DatabaseStream)

          (* * rht 1/31/85: Now reads pointers from index array rather than file.)



          (* * rht 7/9/85: Now gets date if notefile has newer data format.)



          (* * rht 11/10/85 Updated to handle new Card scheme and NoteFile objects.)



          (* * fgh 11/20/85 Added call to NC.ReadCardPartHeader)



          (* * rht 1/23/86: Now takes optional OverrideStream arg. This, if given, overrides stream of card's notefile.)



          (* * rht 1/28/86: Now passes extra arg to NC.ReadCardPartHeader indicating that when we're overriding the notefile 
	  stream, you shouldn't force UIDs on stream and in card to match.)



          (* * kef 7/16/86: Uses the device vector GetCardPartFn to set up the stream and stream pointer for reading.)



          (* * kef 8/1/86: Moved the check for ACTIVE status to beginning.)



          (* * fgh 8/31/86 Adapted to use NC.DoCardPartFn.)



          (* * pmi 11/4/86 Reinstated Randy's changes (1/23/86 and 1/28/86) which somehow got lost.)



          (* * rht 3/13/87: No longer goes to notefile if card hasn't been saved yet.)


    (DECLARE (GLOBALVARS NC.PropsIdentifier))
    (if (AND (EQ (fetch (Card Status) of Card)
		       (QUOTE ACTIVE))
		 (NOT (NC.FetchNewCardFlg Card)))
	then (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
			     (NC.DoCardPartFn Get Card (QUOTE PROPLIST)
					      (LET ((Stream (OR (STREAMP OverrideStream)
								  (NC.CoerceToNoteFileStream Card)))
						    Props)

          (* * set the fileptr to the beginning of the data, read the header, then read the prop list)


					           (NC.SetPropListDate Card
									 (NC.ReadCardPartHeader
									   Card NC.PropsIdentifier 
									   Stream OverrideStream))
					           (NC.SetPropList Card (SETQ Props (
									 NC.ReadPropList Stream)))
					       Props])

(NC.GetType
  [LAMBDA (Card)                                             (* rht: "30-May-87 15:55")
                                                             (* Retrieve the NoteCardType of card specified by 
							     NoteCardID from the database specified by 
							     DatabaseStream)

          (* * rht 1/31/85: Now reads pointers from index array rather than file.)



          (* * rht 7/9/85: Now gets date if notefile has newer data format.)



          (* * kirk 10/18/85; Now returns NIL if status not ACTIVE)



          (* * fkr 10/29/85: Fixed to use new numeric ID format. Also added NC.SetTitle call.)



          (* * rht 11/10/85 Updated to handle new Card scheme and NoteFile objects.)



          (* * fgh 11/20/85 Added call to NC.ReadCardPartHeader)



          (* * rht 1/23/86: Now takes optional OverrideStream arg. This, if given, overrides stream of card's notefile.)



          (* * rht 1/28/86: Now passes extra arg to NC.ReadCardPartHeader indicating that when we're overriding the notefile 
	  stream, you shouldn't force UIDs on stream and in card to match.)



          (* * kef 7/16/86: Uses the device vector GetCardPartFn to set up the stream and stream pointer for reading.)



          (* * kef 7/30/86: Changed to use GetCardInfoFn of the device vector.)



          (* * kef 8/1/86: Decided there are some cases, such as new cards, where we may want the Type of the card even 
	  though it isn't ACTIVE yet.)



          (* * fgh 8/31/86 Changed APPLY* to NC.ApplyFn.)



          (* * rht 5/30/87: No longer goes to notefile unless status is ACTIVE and card isn't brand new.)


    (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
		  (if (AND (EQ (NC.FetchStatus Card)
				     (QUOTE ACTIVE))
			       (NOT (fetch (Card NewCardFlg) of Card)))
		      then (LET (CardType)
			          [NC.SetType Card (SETQ CardType
						  (CDR (FASSOC (QUOTE TYPE)
								   (NC.ApplyFn GetCardInfoFn Card
									       (QUOTE TYPE]
			      CardType])

(NC.PutLinks
  [LAMBDA (Card UseOldDateFlg OverrideStream)                (* rht: " 1-Jul-87 10:23")

          (* * Put the link data for ID onto the database file.)



          (* * rht 1/30/85: Changed to use index array instead of file.)



          (* * rht 7/9/85: Now puts out date after identifier. If UseOldDateFlg is non-nil, then use old date, otherwise use 
	  current date.)



          (* * rht 11/10/85: Updated to handle NoteFile and CardID scheme.)



          (* * fgh 11/20/85 Added call to NC.WriteCardPartHeader and the mechanism to write the start and end pointers of the
	  substance before calling the card type's putfn.)



          (* * rht 1/23/86: Now takes optional OverrideStream arg. This, if given, overrides stream of card's notefile.)



          (* * kef 7/16/86: Makes use of the NoteFile device vector PutCardPartFn.)



          (* * fgh 8/31/86 Adapated to use NC.DoCardPartFn.)



          (* * pmi 11/4/86 Reinstated Randy's change (1/23/86) which somehow got lost.)



          (* * rht 11/14/86: Now makes sure hung var PutSuccessfulLoc is NIL if we were passed an OverrideStream.)



          (* * rht 7/1/87: Now only turns off dirty flg if no OverrideStream.)

                                                             (* Check to make sure this is an active note card.)
    (DECLARE (GLOBALVARS NC.LinksIdentifier))
    (AND (NEQ (fetch (Card Status) of Card)
		  (QUOTE ACTIVE))
	   (NC.ReportError "NC.PutLinks" (CONCAT (NC.FetchTitle Card)
						     " is not an active note card.")))
    (LET (PutSuccessfulLoc)
         (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
		       (NC.DoCardPartFn Put Card (QUOTE LINKS)
					(LET ((Stream (OR (STREAMP OverrideStream)
							    (NC.CoerceToNoteFileStream Card)))
					      StartLoc EndLoc)

          (* * Write the links data at the end of the database file.)


					     (SETQ StartLoc (GETFILEPTR Stream))
					     (NC.WriteCardPartHeader Card NC.LinksIdentifier
								       [COND
									 (UseOldDateFlg (
										NC.FetchLinksDate
											  Card))
									 (T (NC.SetLinksDate
									      Card
									      (DATE]
								       Stream)
					     (NC.WriteListOfLinks Stream (NC.FetchToLinks Card))
					     (NC.WriteListOfLinks Stream (NC.FetchFromLinks
								      Card))
					     (NC.WriteListOfLinks Stream (NC.FetchGlobalLinks
								      Card))

          (* * Update the length field at the beginning of the card info)


					     (SETQ EndLoc (GETFILEPTR Stream))
					     (SETFILEPTR Stream StartLoc)
					     (NC.WritePtr Stream (DIFFERENCE EndLoc StartLoc)
							  3)
					     (SETFILEPTR Stream EndLoc)

          (* * Now update the index to point to the link data just written. Done last in case writing of links doesn't 
	  complete okay.)


					     (OR OverrideStream (NC.SetLinksDirtyFlg Card))

          (* * Now, since we were successful, we'll bind the PutSuccessfulLoc variable, which will be used freely by the 
	  AFTER PutCardPartFns to determine first if the Put succeeded, and if so, where in the stream it was Put.)



          (* * Don't put a reasonable value in the hung variable PutSuccessfulLoc if we were passed OverrideStream.)


					     (SETQ PutSuccessfulLoc
					       (if OverrideStream
						   then NIL
						 else StartLoc))
					 Card])

(NC.GetTitle
  [LAMBDA (Card OverrideStream)                              (* rht: "13-Mar-87 17:06")
                                                             (* Retrieve title for card specified by Card from the 
							     database specified by DatabaseStream)

          (* * rht 1/31/85: Now reads pointers from index array rather than file.)



          (* * rht 7/9/85: Now gets date if notefile has newer data format.)



          (* * kirk 10/28/85 Now returns NIL if Status not ACTIVE)



          (* * fkr 10/29/85: Fixed to use new numeric ID format.)



          (* * rht 11/10/85 Updated to handle new Card scheme and NoteFile objects.)



          (* * fgh 11/20/85 Added call to NC.ReadCardPartHeader)



          (* * rht 1/23/86: Now takes optional OverrideStream arg. This, if given, overrides stream of card's notefile.)



          (* * rht 1/28/86: Now passes extra arg to NC.ReadCardPartHeader indicating that when we're overriding the notefile 
	  stream, you shouldn't force UIDs on stream and in card to match.)



          (* * kef 7/16/86: Uses the device vector GetCardPartFn to set the stream and stream pointer in preparation for the 
	  read.)



          (* * kef 7/24/86: Added check of NewCardFlg.)



          (* * fgh 8/31/86 Adtaped to use NC.DoCardPartFn.)



          (* * pmi 11/4/86 Reinstated Randy's changes (1/23/86 and 1/28/86) which somehow got lost.)



          (* * rht 3/13/87: No longer goes to notefile if card hasn't been saved yet.)


    (DECLARE (GLOBALVARS NC.TitlesIdentifier))
    (if (AND (EQ (fetch (Card Status) of Card)
		       (QUOTE ACTIVE))
		 (NOT (fetch (Card NewCardFlg) of Card)))
	then (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
			     (NC.DoCardPartFn Get Card (QUOTE TITLE)

          (* * Now we've actually executed the BEFORE part of the GETFN, while in a RESETLST that will ensure execution of 
	  the AFTER part upon exit. This means that right now the Stream slot of the NoteFile is a random access stream with 
	  the file pointer set to the beginning of the card part.)


					      (LET ((Stream (OR (STREAMP OverrideStream)
								  (NC.CoerceToNoteFileStream Card)))
						    Title)
					           (NC.SetTitleDate Card
								      (NC.ReadCardPartHeader Card 
									      NC.TitlesIdentifier 
											   Stream 
										   OverrideStream))
					           (NC.SetTitle Card (SETQ Title (NC.ReadTitle
								      Stream)))
					       Title])

(NC.PutMainCardData
  [LAMBDA (Card UpdateUpdateListFlg UseOldDateFlg OverrideStream)
                                                             (* Randy.Gobbel "10-Jun-87 17:34")

          (* * Write note card specified by ID to the database specified by Database stream)



          (* * rht 7/9/85: Now puts out date after identifier. If UseOldDateFlg is non-nil, then use old date, otherwise use 
	  current date.)



          (* * rht 11/10/85: Updated to handle NoteFile and Card scheme.)



          (* * fgh 11/20/85 Added call to NC.WriteCardPartHeader and the mechanism to write the start and end pointers of the
	  substance before calling the card type's putfn.)



          (* * kirk 29Nov85 Renamed from NC.PutNoteCard)



          (* * rht 1/23/86: Now takes optional OverrideStream arg. This, if given, overrides stream of card's notefile.)



          (* * fgh 2/5/86 Added call to NC.ApplyFn)



          (* * fgh 2/6/86 Added support for version numbers on the substance put fn.)



          (* * kirk 14Feb86 Merged above two changes)



          (* * rht 2/14/86: Fixed so call to NC.WriteCardType takes Stream as arg.)



          (* * rht 2/17/86: Fixed so calls to NC.WriteCardPartHeader and to NC.WriteRegion take Stream arg.)



          (* * kef 7/16/86: Makes use of the NoteFile device vector PutCardPartFn.)



          (* * kef 8/1/86: Added notification of status change.)



          (* * fgh 8/31/86 Adapted to use NC.DoCardPartFn.)



          (* * pmi 11/4/86 Reinstated Randy's change (1/23/86) which somehow got lost.)



          (* * rht 11/14/86: Now makes sure hung var PutSuccessfulLoc is NIL if we were passed an OverrideStream.)



          (* * rg 6/10/87 adds links cache if none already exists)


    (DECLARE (GLOBALVARS NC.ItemIdentifier))
    (LET (PutSuccessfulLoc)
         (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
		       (NC.DoCardPartFn Put Card (QUOTE SUBSTANCE)
					(LET ((Stream (OR (STREAMP OverrideStream)
							    (NC.CoerceToNoteFileStream Card)))
					      StartDataLoc EndLoc CardType StartSubstanceLoc 
					      SubstanceVersion)

          (* * Record update date on update list if necessary.)


					     (AND UpdateUpdateListFlg (NC.UpdateUpdateList Card))

          (* * First write out the card part header)


					     (SETQ StartDataLoc (GETFILEPTR Stream))
					     (NC.WriteCardPartHeader Card NC.ItemIdentifier
								       [COND
									 (UseOldDateFlg (
										 NC.FetchItemDate
											  Card))
									 (T (NC.SetItemDate
									      Card
									      (DATE]
								       Stream)

          (* * write out the type and region)


					     (NC.WriteCardType Stream (SETQ CardType
								   (NC.RetrieveType Card)))
					     (NC.WriteRegion Card Stream)

          (* * Write out the dummy length pointer for and version byte the actual substance)


					     (SETQ StartSubstanceLoc (GETFILEPTR Stream))
					     (NC.WritePtr Stream 0 4)

          (* * Write out the substance of the card.)


					     (SETQ SubstanceVersion (NC.ApplyFn PutFn Card Stream))

          (* * Update the length pointer at beginning of substance Subtract four so that length is the length of the actual 
	  substance and doesn't include the length pointer and version byte maintained here. Also updated the version number 
	  returned by the put fn.)


					     (SETQ EndLoc (GETFILEPTR Stream))
					     (SETFILEPTR Stream StartSubstanceLoc)
					     (NC.WritePtr Stream (DIFFERENCE (DIFFERENCE EndLoc 
										StartSubstanceLoc)
									       4)
							  3)
					     (SETQ SubstanceVersion (OR SubstanceVersion 0))
					     (NC.WritePtr Stream SubstanceVersion 1)

          (* * Update the length field at the beginning of the card info)


					     (SETFILEPTR Stream StartDataLoc)
					     (NC.WritePtr Stream (DIFFERENCE EndLoc StartDataLoc)
							  3)
					     (SETFILEPTR Stream EndLoc)

          (* * Now update the Index to reflect the new data just written. Done last in case the substance putting bombed for 
	  some reason.)


					     (replace (Card Status) of Card with (QUOTE
											 ACTIVE))
                                                             (* cause links cache to be created if not already in 
							     existence)
					     (OR (fetch (Card Links) of Card)
						   (replace (Card FromLinks) of Card
						      with NIL))

          (* * Don't put a reasonable value in the hung variable PutSuccessfulLoc if we were passed OverrideStream.)


					     (SETQ PutSuccessfulLoc
					       (if OverrideStream
						   then NIL
						 else StartDataLoc))
					 Card])

(NC.GetNoteCard
  [LAMBDA (Card)                                             (* rht: "16-Oct-86 18:07")

          (* * Get a note card from the database.)



          (* * kirk 27Nov85 Changed to call NC.GetMainCardData)



          (* * rht 10/16/86: Now checks that card is active before doing Get.)


    (if (EQ (fetch (Card Status) of Card)
		(QUOTE ACTIVE))
	then (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
			     (PROGN (NC.GetMainCardData Card)
				      (NC.GetLinks Card)
				      (NC.GetTitle Card)
				      (NC.GetPropList Card)
				      (NC.ActivateCard Card)
				      Card])

(NC.GetMainCardData
  [LAMBDA (Card OverrideStream)                              (* rht: "13-Mar-87 17:03")

          (* Get a note card from the database. If IncludeDeletedCardsFlg is NIL, then return immediately if card is deleted 
	  or free. Otherwise, get dekleted but not free cards.)



          (* * rht 1/31/85: Now reads pointers from index array rather than file.)



          (* * rht 7/9/85: Now gets date if notefile has newer data format.)



          (* * rht 11/10/85 Updated to handle new Card scheme and NoteFile objects.)



          (* * fgh 11/20/85 Added call to NC.ReadCardPartHeader and put in code to read Start and End pointers before calling
	  card type's getfn.)



          (* * kirk 27Nov85 abstracted this function out of NC.GetNoteCard)



          (* * rht 1/23/86: Now takes optional OverrideStream arg. This, if given, overrides stream of card's notefile.)



          (* * rht 1/28/86: Now passes extra arg to NC.ReadCardPartHeader indicating that when we're overriding the notefile 
	  stream, you shouldn't force UIDs on stream and in card to match.)



          (* * fgh 2/5/86 Added call to NC.ApplyFn)



          (* * fgh 2/6/86 Added support for version numbers on the substance get fn.)



          (* * kirk 14Feb86 Merged the above 4 changes)



          (* * kef 7/16/86: Uses the device vector GetCardPartFn to set up the stream and stream pointer for reading.)



          (* * kef 8/1/86: Moved the check for ACTIVE status to beginning.)



          (* * fgh 8/31/86 Adpated to use NC.DoCardPartFn.)



          (* * pmi 11/4/86 Reinstated Randy's changes (1/23/86 and 1/28/86) which somehow got lost.)



          (* * rht 3/13/87: No longer goes to notefile if card hasn't been saved yet.)


    (DECLARE (GLOBALVARS NC.ItemIdentifier))
    (if (AND (EQ (fetch (Card Status) of Card)
		       (QUOTE ACTIVE))
		 (NOT (NC.FetchNewCardFlg Card)))
	then (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
			     (NC.DoCardPartFn Get Card (QUOTE SUBSTANCE)
					      (LET ((Stream (OR (STREAMP OverrideStream)
								  (NC.CoerceToNoteFileStream Card)))
						    Length SubstanceVersion)

          (* * Read the header info)


					           (NC.SetItemDate Card (NC.ReadCardPartHeader
								       Card NC.ItemIdentifier Stream 
								       OverrideStream))

          (* * read card type and region)


					           (NC.SetType Card (NC.ReadCardType Stream))
					           (NC.SetRegion Card (NC.ReadRegion Stream))

          (* * Read the length of substance, then call the substance get fn)


					           (SETQ Length (NC.ReadPtr Stream 3))
					           (SETQ SubstanceVersion (NC.GetPtr Stream 1))
					           (NC.SetSubstance Card
								      (NC.ApplyFn GetFn Card Length 
										  Stream 
										 SubstanceVersion))
					       Card])

(NC.SetStatus
  [LAMBDA (Card Status)                                      (* rht: "14-Nov-85 18:25")

          (* * Set the status field of the given Card)


    (replace (Card IndexDirtyFlg) of Card with T)
    (replace (Card Status) of Card with Status])

(NC.InstallCardInNoteFile
  [LAMBDA (Card NoteFile)                                    (* rht: " 2-May-87 17:15")

          (* * Put Card into NoteFile's hash array.)



          (* * rht 5/2/87: Now dies if there's already a card in the hash array having same UID.)


    (LET ((OtherCard (NC.CardFromUID (fetch (Card UID) of Card)
				       NoteFile)))
         (if OtherCard
	     then (SHOULDNT 
		"Two cards in notefile with same UID.  Please notify the nearest NoteCards guru.")
	   else (PUTHASH (fetch (Card UID) of Card)
			     Card
			     (fetch (NoteFile HashArray) of NoteFile))
		  Card])

(NC.LockListOfCards
  [LAMBDA (CardIdentifiers Operation FileLevelFlg)           (* Randy.Gobbel " 2-Jun-87 19:31")

          (* * set locks on cards passed in, return a list of the lock statuses. Status = NIL means lock was free, = 
	  (QUOTE US) means we already had it, = <string> means operation described by the string was already in progress on 
	  that card)



          (* * RG 4/2/87 created)



          (* * rg 6/2/87 added FileLevelFlg)


    (DECLARE (USEDFREE CardListResetVar))
    (WITH.MONITOR NC.LockLock (LET* [(Cards (for CardIdentifier in CardIdentifiers
					       collect (NC.CoerceToCard CardIdentifier)))
				     (LockStatusList (for Card in Cards
							collect (if FileLevelFlg
								      then
								       (NC.NoteFileCheckOpInProgress
									 (fetch (Card NoteFile)
									    of Card))
								    else (NC.CardCheckOpInProgress
									     Card]
				    [for Card in Cards as Status in LockStatusList
				       when (NULL Status)
				       do (if FileLevelFlg
						then
						 [NAMED-RESETSAVE
						   CardListResetVar
						   (NC.NoteFileProp (fetch (Card NoteFile)
									 of Card)
								      (QUOTE OperationInProgress)
								      Operation)
						   (BQUOTE (NC.NoteFileProp ,
										(fetch
										  (Card NoteFile)
										   of Card)
										OperationInProgress ,
										(NC.NoteFileProp
										  NoteFile
										  (QUOTE 
									      OperationInProgress]
						 [NAMED-RESETSAVE
						   CardListResetVar
						   (NC.NoteFileProp (fetch (Card NoteFile)
									 of Card)
								      (QUOTE ProcessInProgress)
								      (THIS.PROCESS))
						   (BQUOTE (NC.NoteFileProp
							       ,
							       (fetch (Card NoteFile) of Card)
							       ProcessInProgress ,
							       (NC.NoteFileProp
								 (fetch (Card NoteFile)
								    of Card)
								 (QUOTE ProcessInProgress]
						 [NAMED-RESETSAVE CardListResetVar
								    (SETQ NC.NoteFileBusyList
								      (CONS (THIS.PROCESS)
									      NC.NoteFileBusyList))
								    (QUOTE (SETQ 
									      NC.NoteFileBusyList
										     (DREMOVE
										       (THIS.PROCESS
											 )
										       
									      NC.NoteFileBusyList]
					      else [NAMED-RESETSAVE
						       CardListResetVar
						       (NC.SetUserDataProp Card (QUOTE 
										ProcessInProgress)
									     (THIS.PROCESS))
						       (BQUOTE (NC.SetUserDataProp
								   , Card ProcessInProgress ,
								   (NC.FetchUserDataProp
								     Card
								     (QUOTE ProcessInProgress]
						     [NAMED-RESETSAVE
						       CardListResetVar
						       (NC.SetUserDataProp Card (QUOTE 
									      OperationInProgress)
									     Operation)
						       (BQUOTE (NC.SetUserDataProp
								   , Card OperationInProgress ,
								   (NC.FetchUserDataProp
								     Card
								     (QUOTE OperationInProgress]
						     [NAMED-RESETSAVE
						       CardListResetVar
						       [NC.NoteFileProp
							 (fetch (Card NoteFile) of Card)
							 (QUOTE CardProcessInProgressList)
							 (CONS (THIS.PROCESS)
								 (NC.NoteFileProp
								   (fetch (Card NoteFile)
								      of Card)
								   (QUOTE CardProcessInProgressList]
						       (BQUOTE (NC.ResetCardProcessInProgress
								   ,
								   (fetch (Card NoteFile)
								      of Card]
						     (NAMED-RESETSAVE CardListResetVar
									(SETQ NC.CardBusyList
									  (CONS (THIS.PROCESS)
										  NC.CardBusyList))
									(QUOTE (SETQ
										   NC.CardBusyList
										   (DREMOVE
										     (THIS.PROCESS)
										     NC.CardBusyList]
				LockStatusList])

(NC.CardCheckOpInProgress
  [LAMBDA (Card)                                             (* Randy.Gobbel " 6-Mar-87 12:04")

          (* * Return the operation in progress if any. Checks session level, then NoteFile level, then Card level.
	  Returns NIL if there is no conflict at any level, otherwise a string describing the conflicting operation.
	  THIS PROCEDURE IS INTERNAL TO THE NOTECARDS GLOBAL MONITOR!)



          (* * rg 3/3/87 First created.)


    (LET (ProcInProgress)
         (COND
	   [(PROCESSP (SETQ ProcInProgress NC.SessionProcessInProgress))
                                                             (* someone doing a session op, check to see if it's 
							     us)
	     (COND
	       ((NEQ ProcInProgress (THIS.PROCESS))      (* if someone else has the session lock, return that 
							     op)
		 NC.SessionOperationInProgress)
	       (T                                            (* we have the session lock)
		  (QUOTE US]
	   [[PROCESSP (SETQ ProcInProgress (NC.NoteFileProp (fetch (Card NoteFile)
								     of Card)
								  (QUOTE ProcessInProgress]
                                                             (* someone doing a NF op, check to see if it's us)
	     (COND
	       ((NEQ ProcInProgress (THIS.PROCESS))      (* if someone else has the NF lock, return that op)
		 (NC.NoteFileProp (fetch (Card NoteFile) of Card)
				    (QUOTE OperationInProgress)))
	       (T                                            (* we have the NF lock)
		  (QUOTE US]
	   [[PROCESSP (SETQ ProcInProgress (NC.FetchUserDataProp Card (QUOTE 
										ProcessInProgress]
                                                             (* if someone has the card lock, see if it's us)
	     (COND
	       ((NEQ ProcInProgress (THIS.PROCESS))      (* if someone else has the card lock, return that op)
		 (NC.FetchUserDataProp Card (QUOTE OperationInProgress)))
	       (T                                            (* we have the card lock)
		  (QUOTE US]
	   (T                                                (* all relevant locks are free)
	      NIL])

(NC.PutRegion
  [LAMBDA (Card)                                             (* fgh: "31-Aug-86 23:03")

          (* * rht 1/31/85: Now reads pointers from index array rather than file.)



          (* * rht 11/12/85: Updated to handle new Notefile and cardID format.)



          (* * fgh 11/20/85 Added call to NC.ReadCardPartHeader)



          (* * rht 1/23/86: Changed to use NC.CoerceToNoteFileStream)



          (* * kef 7/28/86: Changed to play by multi-user device vector rules.)



          (* * fgh 8/31/86 Adpated to use NC.DoCardPartFn.)


    (LET (PutSuccessfulLoc)
         (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
		       (NC.DoCardPartFn Put Card (QUOTE REGION)

          (* * Check to make sure this is an active note card.)


					(AND (NEQ (fetch (Card Status) of Card)
						      (QUOTE ACTIVE))
					       (NC.ReportError "NC.PutRegion" (CONCAT
								   (NC.FetchTitle Card)
								   " is not an active note card.")))
					(NC.WriteRegion Card (NC.CoerceToNoteFileStream Card))
					(SETQ PutSuccessfulLoc T)
					Card])

(NC.PutTitle
  [LAMBDA (Card UseOldDateFlg OverrideStream)                (* rht: " 1-Jul-87 10:23")

          (* * Put the title of card ID onto DatabaseStream)



          (* * rht 7/9/85: Now puts out date after identifier. If UseOldDateFlg is non-nil, then use old date, otherwise use 
	  current date.)



          (* * rht 11/10/85: Updated to handle NoteFile and CardID scheme.)



          (* * fgh 11/20/85 Added call to NC.WriteCardPartHeader and the mechanism to write the start and end pointers of the
	  substance before calling the card type's putfn.)



          (* * rht 1/23/86: Now takes optional OverrideStream arg. This, if given, overrides stream of card's notefile.)



          (* * kef 7/16/86: Makes use of the NoteFile device vector PutCardPartFn.)



          (* * fgh 8/31/86 Adpated to use NC.DoCardPartFn.)



          (* * pmi 11/4/86 Reinstated Randy's change (1/23/86) which somehow got lost.)



          (* * rht 11/14/86: Now makes sure hung var PutSuccessfulLoc is NIL if we were passed an OverrideStream.)



          (* * rht 7/1/87: Now only turns off dirty flg if no OverrideStream.)

                                                             (* Check to make sure this is an active note card.)
    (DECLARE (GLOBALVARS NC.TitlesIdentifier))
    (AND (NEQ (fetch (Card Status) of Card)
		  (QUOTE ACTIVE))
	   (NC.ReportError "NC.PutTitle" (CONCAT (NC.FetchTitle Card)
						     " is not an active note card.")))
    (LET (PutSuccessfulLoc)
         (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
		       (NC.DoCardPartFn Put Card (QUOTE TITLE)
					(LET ((Stream (OR (STREAMP OverrideStream)
							    (NC.CoerceToNoteFileStream Card)))
					      StartLoc EndLoc)

          (* * First write out the title.)


					     (SETQ StartLoc (GETFILEPTR Stream))
					     (NC.WriteCardPartHeader Card NC.TitlesIdentifier
								       [COND
									 (UseOldDateFlg (
										NC.FetchTitleDate
											  Card))
									 (T (NC.SetTitleDate
									      Card
									      (DATE]
								       Stream)
					     (NC.WriteTitle Stream (NC.FetchTitle Card))

          (* * Update the length field at the beginning of the card info)


					     (SETQ EndLoc (GETFILEPTR Stream))
					     (SETFILEPTR Stream StartLoc)
					     (NC.WritePtr Stream (DIFFERENCE EndLoc StartLoc)
							  3)
					     (SETFILEPTR Stream EndLoc)

          (* * Now update the Index to reflect the new data just written. Done last in case the substance putting bombed for 
	  some reason.)


					     (OR OverrideStream (NC.SetTitleDirtyFlg Card))

          (* * Now, since we were successful, we'll bind the PutSuccessfulLoc variable, which will be used freely by the 
	  AFTER PutCardPartFns to determine first if the Put succeeded, and if so, where in the stream it was Put.)



          (* * Don't put a reasonable value in the hung variable PutSuccessfulLoc if we were passed OverrideStream.)


					     (SETQ PutSuccessfulLoc
					       (if OverrideStream
						   then NIL
						 else StartLoc))
					 Card])

(NC.CloseNoteFile
  [LAMBDA (NoteFile InterestedWindow QuietFlg AutoConfirmFlg)
                                                             (* pmi: "14-Aug-87 10:57")

          (* * Close a NoteFIle)



          (* * rht 10/23/84: Now gives user option of closing and saving all open cards on the screen.)



          (* * rht 11/8/84: Put RESETLST around NC.CacheTitles call.)



          (* * rht 1/9/85: Clear the NC.UncachingNotCompleted variable when close successfully completes.)



          (* * rht 1/31/85: Added call to checkpoint database. That in turn dumps the next nodeID and next linkID.)



          (* * rht 7/14/85: Replaced the call to reset the main menu with call to NC.ResetMainMenu. Also took out redundant 
	  reset of PSA.Database, since NC.ForceDatabaseClose is doing that.)



          (* * fgh 10/16/85 removed call to CacheTypesAndTitles because uncacheing now done automatically by cache 
	  mechanism.)



          (* * fkr 10/29/85: Now kills caching process from database streamprop.)



          (* * fkr 11/8/85 Updated to handle new NoteFile object and new CardID scheme.)



          (* * kirk 23Jan86 Changed to use NC.AskYesOrNo)



          (* * rht 3/26/86: Now searches for active cards over whole notefile not just among cards up on screen.
	  Uses NC.MapCards.)



          (* * kirk 28Apr86 Now returns NoteFile if successful.)



          (* * fgh 5/2/86 Cleaned up. Ask user to confirm only if there are cards on the screen, not if there are active, but
	  not displayed ones. Added calls to the NC.CloseNoteFileFns before and after the closeing.)



          (* * fgh 5/26/86 Revamp for device vector implementation.)



          (* * kef 7/24/86: Changed the last expression at the end that smashes the NoteFile device out of the NoteFile data 
	  structure. This is so that the Interface will not bomb trying to apply an OPENP function with a NIL Device.)



          (* * kef 8/4/86: Added something to obtain the write lock on the parts of the active NoteCards that deactivating 
	  will release. This is also so that any changes may be written to the server.)



          (* * fgh 8/31/86 Reimplemented changes in system made since 5/23/86 conversion. Reimplemented changes include: 
	  (* * fgh 6/4/86 Fixed so that shrunken cards are counted as open when asking for confirmation when there are open 
	  cards on screen.) (* * fgh 6/13/86 Now checks for card operations in progress and kills them if necessary.) 
	  (* * fgh 6/25/86 Added NC.ProtectedNoteFileOperation macro call. Added Don'tCheckOperationInProgressFlg args.) 
	  (* * rht 7/4/86: Added check for readonly notefile.) (* * rht 7/13/86: Added QuietFlg arg. Note that this will 
	  cause open cards on the screen to be closed and saved without asking user for confirmation.) 
	  (* * rpr 11/13/86: After closing active cards, checks to see if any special cards were made active and closes 
	  them.))



          (* * pmi 12/22/86 Made test for open notefile consistent with other NoteFile operations (ie. Abort Checkpoint,))



          (* * rht 2/16/87: Added AutoConfirmFlg argument to prevent user having to confirm whether to close and save open 
	  cards. Note that QuietFlg is stronger than AutoConfirmFlg in that other messages are suppressed as well.)



          (* * rg 3/4/87 changes for new concurrency machinery)



          (* * rht 3/25/87: Now calls NC.CoerceToInterestedWindow.)



          (* * rg 3/27/87 redid concurrency wrapper)



          (* * pmi 8/14/87: Added call to NC.NoticeNoteFile to make sure this file has been noticed. Also, added parameters 
	  in call to NC.AbortSession to stop confirmation and pass on the QuietFlg.)


    (DECLARE (GLOBALVARS NC.MsgDelay NC.CloseNoteFileFns))
    (NC.ProtectedNoteFileOperation
      NoteFile "Close NoteFile" InterestedWindow (OR (OPENWP InterestedWindow)
						       (SETQ InterestedWindow (
							   NC.CoerceToInterestedWindow NoteFile)))
      (if (NC.ReadOnlyNoteFileP NoteFile)
	  then (NC.AbortSession NoteFile InterestedWindow T QuietFlg)
	else
	 (ALLOW.BUTTON.EVENTS)
	 (PROG ((FullFileName (fetch (NoteFile FullFileName) of NoteFile))
		  CardTotal ActiveCards ReturnValue (OperationMsg ""))

          (* * Make sure NF is open)


	         (if [NULL (ERSETQ (SETQ ReturnValue (NC.NoteFileOpenP NoteFile]
		     then (SETQ ReturnValue (QUOTE OpenPFailed)))
	         (if (NULL ReturnValue)
		     then 

          (* * NoteFile is not open.)


			    (NC.PrintMsg InterestedWindow T "Can't close a closed notefile."
					   (CHARACTER 13))
			    (DISMISS NC.MsgDelay)
			    (NC.ClearMsg InterestedWindow T)
			    (RETURN NIL)
		   elseif (NOT (type? NoteFile ReturnValue))
		     then 

          (* * Error return from NoteFileOpenPFn)


			    (if [NULL (ERSETQ (NC.ReportError NIL (CONCAT "OpenP test on " 
										    FullFileName 
										"failed because "
										    ReturnValue
										    (CHARACTER
										      13)
										    
							"OK to continue Close. ↑ to abort Close."]
				then (RETURN ReturnValue)))
	         (RETURN
		   (PROG NIL
		           (RESETSAVE NIL (BQUOTE (NC.ClearMsg , InterestedWindow T)))

          (* * Delete the types and titles caching process if still alive. Have to do it now in order to make checking 
	  operations that follow suitably efficient. Note its a bit too early since we can still cancel this close.
	  But any harm done is loss of speed if NoteFile remains open when close iss cancelled.)


		           (DEL.PROCESS (fetch (NoteFile CachingProcess) of NoteFile))

          (* * See if any cards have operations in progress. If so, kill them after confirming with user.)


		           (OR QuietFlg (NC.PrintMsg InterestedWindow T (OR OperationMsg "")
							 
						   "Checking for card operations in progress ..."
							 (CHARACTER 13)))
		           (if (EQ (QUOTE ABORT)
				       (NC.CardOperationsInProgress NoteFile T))
			       then (RETURN NIL))
		           (NC.ClearMsg InterestedWindow NIL)

          (* * If NULL QuietFlg then look for cards on the screen. If there are active cards ask the user if they still want 
	  to close. When there's a non-NIL QuietFlg we just close the active cards.)


		           (if
			     (AND (NULL QuietFlg)
				    (NULL AutoConfirmFlg)
				    [for Window in (OPENWINDOWS)
				       thereis
					(LET (Card)
					     (AND [SETQ Card
						      (OR (NC.CardFromWindow Window)
							    (AND (WINDOWP (WINDOWPROP
										Window
										(QUOTE ICONFOR)))
								   (NC.CardFromWindow
								     (WINDOWPROP Window
										   (QUOTE ICONFOR]
						    (NC.SameNoteFileP NoteFile (fetch
									  (Card NoteFile)
										    of Card]
				    (NULL (NC.AskYesOrNo (CONCAT 
					"There are still cards on the screen from this NoteFile "
								       FullFileName "." (CHARACTER
									 13)
								       
								  "Want to close and save them? ")
							     " -- "
							     (QUOTE Yes)
							     NIL InterestedWindow NIL NIL)))
			       then (RETURN NIL))

          (* * Run through CloseNoteFileFns with param of BEFORE. Exit if any returns DON'T)


		           (if [for Function in NC.CloseNoteFileFns
				    thereis (OR (EQ Function (QUOTE DON'T))
						    (EQ (QUOTE DON'T)
							  (APPLY* Function NoteFile (QUOTE BEFORE]
			       then (RETURN NIL))

          (* * Close all the active cards)


		           (OR QuietFlg (NC.PrintMsg InterestedWindow T (OR OperationMsg "")
							 "Checking for active cards ..."
							 (CHARACTER 13)))
		           [if (SETQ ActiveCards (NC.MapCards NoteFile (FUNCTION [LAMBDA (Card)
								      Card])
								  (FUNCTION NC.ActiveCardP)))
			       then (if (NULL QuietFlg)
					  then (NC.PrintMsg InterestedWindow T 
							   "Closing and saving active cards ... "))
				      (RESETLST (RESETSAVE NC.ForceSourcesFlg NIL)
						  (RESETSAVE NC.ForceFilingFlg NIL)
						  (RESETSAVE NC.ForceTitlesFlg NIL)
						  (NC.CloseListOfActiveCards ActiveCards 
									       InterestedWindow 
									       QuietFlg)
						  (NC.CloseListOfActiveCards (for Card
										  in (
									     NC.FetchSpecialCards
											 NoteFile)
										  when
										   (NC.ActiveCardP
										     Card)
										  collect Card)
									       InterestedWindow 
									       QuietFlg))
				      (OR QuietFlg (NC.PrintMsg InterestedWindow NIL "Done."
								    (CHARACTER 13]

          (* * Checkpoint the NoteFile.)


		           (OR QuietFlg (NC.PrintMsg InterestedWindow T "Closing Notefile ... "
							 (CHARACTER 13)))
		           (if [NULL (CAR (ERSETQ (SETQ ReturnValue
							    (NC.CheckpointNoteFile NoteFile 
										     QuietFlg T 
										 InterestedWindow 
										     OperationMsg]
			       then (SETQ ReturnValue (QUOTE CheckpointFailed)))

          (* * Process error returns from in NC.CheckpointNoteFile)


		           (if (NOT (type? NoteFile ReturnValue))
			       then (if [NULL (ERSETQ (NC.ReportError NIL
										(CONCAT
										  
									"Checkpoint of NoteFile "
										  FullFileName 
									       " failed because "
										  ReturnValue "."
										  (CHARACTER 13)
										  
							"OK to continue Close. ↑ to abort Close."]
					  then (RETURN ReturnValue)))

          (* * Close the file.)


		           (if [NULL (CAR (ERSETQ (SETQ ReturnValue
							    (APPLY* (fetch (NoteFile 
										  CloseNoteFileFn)
									 of NoteFile)
								      NoteFile InterestedWindow]
			       then (SETQ ReturnValue (QUOTE CloseFailed)))

          (* * Process error returns from the close.)


		           [if (NOT (type? NoteFile ReturnValue))
			       then (SELECTQ
					ReturnValue
					(NoteFileNotOpen
					  (if [NULL (ERSETQ (NC.ReportError
								    NIL
								    (CONCAT "NoteFile" FullFileName 
									      " is not open."
									      (CHARACTER 13)
									      
							"OK to continue Close. ↑ to abort Close."]
					      then (RETURN ReturnValue)))
					(PROGN [ERSETQ (NC.ReportError NIL
									     (CONCAT 
									     "Close of NoteFile "
										       FullFileName 
									       " failed because "
										       ReturnValue 
										       "."
										       (CHARACTER
											 13]
						 (RETURN ReturnValue]

          (* * Run through CloseNoteFileFns with param of AFTER. Stop if any returns DON'T)


		           [for Function in NC.CloseNoteFileFns
			      thereis (EQ (QUOTE DON'T)
					      (APPLY* Function NoteFile (QUOTE AFTER]

          (* * Reset the interface, make sure the notefile has been noticed, and notify the user.)


		           (NC.ResetNoteFileInterface NoteFile)
		           (NC.NoticeNoteFile NoteFile)
		           (OR QuietFlg (NC.PrintMsg InterestedWindow T FullFileName " closed."))

          (* * * Cleanup a bit.)

                                                             (* Clean off the card cache's)
		           (ADD.PROCESS (LIST (FUNCTION NC.CleanupCardObjects)
						  (fetch (NoteFile HashArray) of NoteFile)))
                                                             (* Clean off the NoteFile object to remove any 
							     circularities.)
		           (create NoteFile smashing NoteFile Stream ← NIL UID ←
							 (fetch (NoteFile UID) of NoteFile)
							 FullFileName ← FullFileName Menu ←
							 (fetch (NoteFile Menu) of NoteFile)
							 NoteFileDevice ← (fetch (NoteFile 
										   NoteFileDevice)
									     of NoteFile))

          (* * Return the NF)


		           (RETURN NoteFile])

(NC.CleanupCardObjects
  [LAMBDA (HashArray)                                        (* fgh: " 5-Sep-86 17:11")

          (* * For every cardobject in HashArray, smash CardCache and UserData fields cause they might cause circular links.)



          (* * fgh 9/5/86 Chack to make sure HashArray is real to avoid problems caused by MAPHASH of NIL.)


    (if (HARRAYP HashArray)
	then (MAPHASH HashArray (FUNCTION (LAMBDA (Card Key)
			      (replace (Card CardCache) of Card with NIL)
			      (replace (Card UserData) of Card with NIL])

(NC.CloseListOfActiveCards
  [LAMBDA (ActiveCards InterestedWindow QuietFlg)            (* rht: "30-Mar-87 14:49")

          (* * Close a list of active cards.)



          (* * rg 3/4/87 added NC.ProtectedSessionOperation wrapper)



          (* * rg 3/12/87 Oops. REMOVED NC.ProtectedSessionOperation wrapper)



          (* * rht 3/30/87: Now passes NIL InterestedWindow arg to NC.QuitCard so it will try to use card's prompt window.)


    (for Card in ActiveCards bind Window
       do [for CardPart in (QUOTE (SUBSTANCE TOLINKS GLOBALTOLINKS PROPLIST))
	       do (OR (NC.ApplyFn ObtainWritePermissionFn Card CardPart)
			  (until (NC.ApplyFn ObtainWritePermissionFn Card CardPart)
			     do (OR QuietFlg (NC.PrintMsg InterestedWindow T
								(CONCAT 
						    "Waiting to obtain write permission for the "
									  CardPart " on card "
									  (NC.FetchTitle Card)
									  "...")))
				  (BLOCK)
			     finally (OR QuietFlg (NC.PrintMsg InterestedWindow NIL "done."]
	    (NC.QuitCard Card T NIL T NIL NIL QuietFlg)
	    (if (SETQ Window (NC.FetchWindow Card))
		then (bind (Process ← (WINDOWPROP Window (QUOTE PROCESS)))
			  until (OR (NULL Process)
					(PROCESS.FINISHEDP Process))
			  do (BLOCK])

(NC.PutNoteCard
  [LAMBDA (Card UpdateUpdateListFlg UseOldDateFlg)           (* rht: "17-Feb-86 16:11")

          (* * Put down each of the card's parts to its notefile.)


    (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
		  (NC.PutMainCardData Card UpdateUpdateListFlg UseOldDateFlg)
		  (NC.PutLinks Card UseOldDateFlg)
		  (NC.PutTitle Card UseOldDateFlg)
		  (NC.PutPropList Card UseOldDateFlg])

(NC.SetMainLoc
  [LAMBDA (Card MainLoc)                                     (* rht: "14-Nov-85 18:26")

          (* * Set the MainLoc field of the given cardID.)


    (replace (Card IndexDirtyFlg) of Card with T)
    (replace (Card MainLoc) of Card with MainLoc])

(NC.SetLinksLoc
  [LAMBDA (Card LinksLoc)                                    (* rht: "14-Nov-85 18:26")

          (* * Set the LinksLoc field of the given cardID.)


    (replace (Card IndexDirtyFlg) of Card with T)
    (replace (Card LinksLoc) of Card with LinksLoc])

(NC.SetTitleLoc
  [LAMBDA (Card TitleLoc)                                    (* rht: "14-Nov-85 18:27")

          (* * Set the TitleLoc field of the given Card)


    (replace (Card IndexDirtyFlg) of Card with T)
    (replace (Card TitleLoc) of Card with TitleLoc])

(NC.SetPropListLoc
  [LAMBDA (Card PropListLoc)                                 (* rht: "14-Nov-85 18:27")

          (* * Set the PropListLoc field of the given Card)


    (replace (Card IndexDirtyFlg) of Card with T)
    (replace (Card PropListLoc) of Card with PropListLoc])

(NC.CopyCards
  [LAMBDA (Cards DestNoteFileOrFileBox RootCards QuietFlg InterestedWindow CopyExternalToLinksMode)
                                                             (* rht: "22-Jun-87 13:15")

          (* * Create copies of cards in Cards. If DestNoteFileOrFileBox is a notefile, then destination will be the contents
	  box in that notefile, else the FileBox's notefile. RootCards should be NIL or a subset of Cards.
	  If NIL, then file all Cards in the dest filebox. Otherwise, just file RootCards in that filebox and assume others 
	  are linked somehow to the RootCards. Links between cards in Cards are copied, but links from or to outside cards 
	  aren't.)



          (* * Currently all Cards must be in same notefile, but this perhaps could be relaxed if could prevent possibility 
	  of two cards in different notefiles having the same UID.)



          (* * kirk 24Apr86 Added calls to select cards if none provided)



          (* * rht 9/2/86: Added InterestedWindow arg.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rg 3/18/87 added NC.CardSelectionOperation wrapper)



          (* * rg 4/2/87 changed NC.CardSelectionOperation to NCP.WithLockedCards ; added NC.IfAllCardsFree wrapper)



          (* * rht&rg&pmi 4/22/87: No longer calls ERROR!)



          (* * rg 6/2/87 was checking for CANCELLED instead of DON'T)



          (* * rg 6/5/87 deletes new cards if we cancel out halfway through)



          (* * rht 6/6/87: Now optionally copies "external" links. Passes extra new args to NC.FixUpLinksInCardCopy.)



          (* * rht 6/22/87: Now returns list of cards copied, like it used to.)


    (NCP.WithLockedCards (NC.IfAllCardsFree
			   (NC.LockListOfCards Cards "Copy Cards")
			   (PROG (NumCards SourceNoteFile DestNoteFile BoxToFileIn TempStream 
					     CardHashArray LinksHashArray CurrentLinkLabels 
					     NewLinkLabels NewCardsAndLocsOnStream 
					     CopyExternalToLinksFlg)

          (* * Make sure the arguments are valid.)


			           (if (NULL Cards)
				       then (if (NULL (SETQ Cards
							      (NC.SelectNoteCards NIL NIL 
									    NC.SelectingCardsMenu NIL 
					     "Shift-select from the same NoteFile cards to copy:"
										    NIL)))
						  then (RETURN NIL)))
			           (SETQ Cards (MKLIST Cards))
			           (SETQ NumCards (LENGTH Cards))
                                                             (* All Cards to copy must live in same notefile.)
			           (SETQ SourceNoteFile (fetch (Card NoteFile)
							     of (CAR Cards)))
			           (if [NOT (AND (type? NoteFile SourceNoteFile)
						       (OPENP (fetch (NoteFile Stream)
								   of SourceNoteFile]
				       then (NC.ReportError "NC.CopyCards"
								(CONCAT (fetch (NoteFile 
										     FullFileName)
									     of SourceNoteFile)
									  " not an open notefile.")))
			           (if (NOT (for Card in Cards
						   always (NC.SameNoteFileP (fetch
										  (Card NoteFile)
										   of Card)
										SourceNoteFile)))
				       then (NC.ReportError "NC.CopyCards" 
					"All cards in Cards arg don't live in the same notefile."))
                                                             (* Compute dest notefile and dest filebox.)
			           (if (NOT DestNoteFileOrFileBox)
				       then (if (EQ (QUOTE DON'T)
							  (SETQ DestNoteFileOrFileBox
							    (NC.SelectNoteCards T NIL 
									     NC.SelectingCardMenu NIL 
					       "Shift-select the FileBox to contain these cards."
										  T)))
						  then (RETURN NIL)))
			           (if (type? NoteFile DestNoteFileOrFileBox)
				       then (SETQ DestNoteFile DestNoteFileOrFileBox)
					      (SETQ BoxToFileIn (fetch (NoteFile 
									      TableOfContentsCard)
								     of DestNoteFile))
				     elseif (NCP.FileBoxP DestNoteFileOrFileBox)
				       then (SETQ BoxToFileIn DestNoteFileOrFileBox)
					      (SETQ DestNoteFile (fetch (Card NoteFile)
								      of BoxToFileIn))
				     else (NC.ReportError "NC.CopyCards" (CONCAT 
								  "Arg not notefile or filebox: "
										       
									    DestNoteFileOrFileBox)))
			           (if [NOT (AND (type? NoteFile DestNoteFile)
						       (OPENP (fetch (NoteFile Stream)
								   of DestNoteFile]
				       then (NC.ReportError "NC.CopyCards"
								(CONCAT (fetch (NoteFile 
										     FullFileName)
									     of DestNoteFile)
									  " not an open notefile.")))
			           (if (LDIFFERENCE (SETQ RootCards (MKLIST RootCards))
							Cards)
				       then (NC.ReportError "NC.CopyCards" 
					       "RootCards argument not subset of Cards argument."))
			           (if (NULL RootCards)
				       then (SETQ RootCards Cards))

          (* * Figure out whether to copy "external" links.)


			           [SETQ CopyExternalToLinksFlg
				     (SELECTQ CopyExternalToLinksMode
						(COPY T)
						(DON'TCOPY NIL)
						(SELECTQ (NC.AskUserWithMenu (QUOTE
										   (Yes No Cancel))
										 (CONCAT
										   
									  "You've asked to copy "
										   (LENGTH Cards)
										   " cards."
										   (CHARACTER
										     13)
										   
					  "Links among these cards will be automatically copied."
										   (CHARACTER
										     13)
										   
			"Do you also want to copy links pointing from these cards to elsewhere? ")
										 InterestedWindow)
							   (Yes T)
							   (No NIL)
							   (RETURN NIL]

          (* * Now get to work.)


			           (SETQ TempStream (OPENSTREAM (QUOTE {NODIRCORE})
								    (QUOTE BOTH)))
			           (SETQ CurrentLinkLabels (NC.RetrieveLinkLabels DestNoteFile))
			           (SETQ NewLinkLabels (TCONC NIL))
			           (SETQ LinksHashArray (HASHARRAY NC.CopyCardsLinksHashArraySize 
								       NIL (FUNCTION NC.MakeHashKey)
								       (FUNCTION NC.SameUIDP)))
			           (SETQ CardHashArray (HASHARRAY NumCards NIL
								      (FUNCTION 
									NC.MakeHashKeyFromCard)
								      (FUNCTION NC.SameCardP)))

          (* * Create new cards in DestNoteFile for each card. Make these cards by copying original cards to a temp stream.
	  Keep track of UID mappings between original cards and card copies using CardHashArray.)


			           (OR QuietFlg (NC.PrintMsg InterestedWindow T 
							  "Copying cards: creating empty copies."
								 (CHARACTER 13)
								 "Processing item " 1 " out of " 
								 NumCards "..." (CHARACTER 13)))
			           (SETQ NewCardsAndLocsOnStream NIL)
			           [RESETLST
				     [RESETSAVE NIL
						  (QUOTE (PROGN
							     (if RESETSTATE
								 then (for CardAndLoc
									   in 
									  NewCardsAndLocsOnStream
									   do (
									NC.DeleteNoteCardInternal
										  (CAR CardAndLoc)
										  T InterestedWindow))
									(NC.ClearMsg 
										 InterestedWindow T]
				     (for Card in Cards as i from 1
					bind NewCard WasActiveFlg HadStatusNILFlg IndexLocs
					eachtime (BLOCK) unless (NC.CrossFileLinkCardP Card)
					do [OR QuietFlg (if (ZEROP (REMAINDER i 100))
								then (NC.PrintMsg 
										 InterestedWindow T 
							  "Copying cards: creating empty copies."
										      (CHARACTER
											13)
										      
									       "Processing item "
										      i " out of " 
										      NumCards "..."
										      (CHARACTER
											13]
					     (if (NOT (SETQ WasActiveFlg (NC.ActiveCardP
							      Card)))
						 then (NC.GetNoteCard Card))
					     (if (SETQ HadStatusNILFlg
						     (NULL (fetch (Card Status) of Card)))
						 then      (* Have to have Status slot ACTIVE in order that Put 
							     to stream won't break.)
							(replace (Card Status) of Card
							   with (QUOTE ACTIVE)))
					     (SETQ IndexLocs (NC.PutNoteCardToStream Card NIL T 
										       TempStream))
					     (if HadStatusNILFlg
						 then (replace (Card Status) of Card
							   with NIL))
					     (if (NOT WasActiveFlg)
						 then (NC.DeactivateCard Card))
                                                             (* Make new empty card for copy.)
					     (SETQ NewCard (NC.GetNewCard DestNoteFile)) 
                                                             (* Map old cards to card copies.)
					     (PUTHASH Card NewCard CardHashArray)
					     (push NewCardsAndLocsOnStream (CONS NewCard 
										     IndexLocs]

          (* * For each card, get it off the temp stream, fix its links, fix browser info if necessary, and write it down to 
	  the dest notefile.)


			           (SETFILEPTR TempStream 0)
			           (OR QuietFlg (NC.PrintMsg InterestedWindow T 
						 "Copying cards: fixing links and browser cards."
								 (CHARACTER 13)
								 "Processing item " 1 " out of " 
								 NumCards "..." (CHARACTER 13)))
			           (for NewCardAndLocsOnStream in NewCardsAndLocsOnStream
				      as i from 1 eachtime (BLOCK)
				      bind (CrossFileLinkModePropList ← (LIST DestNoteFile NIL))
				      do [OR QuietFlg (if (ZEROP (REMAINDER i 100))
							      then (NC.PrintMsg InterestedWindow 
										    T 
						 "Copying cards: fixing links and browser cards."
										    (CHARACTER
										      13)
										    
									       "Processing item "
										    i " out of " 
										    NumCards "..."
										    (CHARACTER
										      13]
					   (LET ((NewCard (CAR NewCardAndLocsOnStream))
						 (IndexLocs (CDR NewCardAndLocsOnStream)))
                                                             (* Have to make status active for Get fns to work.)
					        (NC.SetStatus NewCard (QUOTE ACTIVE))
					        (NC.GetNoteCardFromStream NewCard TempStream 
									    IndexLocs)
					        (NC.FixUpLinksInCardCopy NewCard CardHashArray 
									   LinksHashArray 
									   CurrentLinkLabels 
									   NewLinkLabels 
									   InterestedWindow 
									   CopyExternalToLinksFlg 
									CrossFileLinkModePropList)
					        (if (NC.IsSubTypeOfP (NC.FetchType NewCard)
									 (QUOTE Browser))
						    then (NC.FixUpBrowserCardCopy NewCard 
										    CardHashArray))
					        (NC.PutNoteCard NewCard)))

          (* * Link RootCards under filebox in DestNotefile.)


			           (OR QuietFlg (NC.PrintMsg InterestedWindow T 
								 "Copying cards: filing "
								 (LENGTH RootCards)
								 " new cards in "
								 (NC.FetchTitle BoxToFileIn)
								 "..."
								 (CHARACTER 13)))
			           (NC.FileBoxCollectChildren NIL BoxToFileIn
								(for RootCard in RootCards
								   eachtime (BLOCK)
								   collect (GETHASH RootCard 
										    CardHashArray))
								T)

          (* * Put out any new link labels to the dest notefile.)


			           (AND (SETQ NewLinkLabels (CDAR NewLinkLabels))
					  (NC.StoreLinkLabels DestNoteFile (APPEND NewLinkLabels 
										CurrentLinkLabels)))
			           (OR QuietFlg (NC.ClearMsg InterestedWindow T))
			           (RETURN Cards])

(NC.PutNoteCardToStream
  [LAMBDA (Card UpdateUpdateListFlg UseOldDateFlg Stream)    (* rht: "28-Jan-86 14:12")

          (* * Put all the card parts of Card down to Stream and return an IndexLocs record containing locations of each of 
	  the card parts just written down.)


    (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
		  (LET (MainCardDataLoc LinksLoc TitleLoc PropListLoc)
		       (SETQ MainCardDataLoc (GETFILEPTR Stream))
		       (NC.PutMainCardData Card UpdateUpdateListFlg UseOldDateFlg Stream)
		       (SETQ LinksLoc (GETFILEPTR Stream))
		       (NC.PutLinks Card UseOldDateFlg Stream)
		       (SETQ TitleLoc (GETFILEPTR Stream))
		       (NC.PutTitle Card UseOldDateFlg Stream)
		       (SETQ PropListLoc (GETFILEPTR Stream))
		       (NC.PutPropList Card UseOldDateFlg Stream)
		       (create IndexLocs
				 MainCardDataLoc ← MainCardDataLoc
				 LinksLoc ← LinksLoc
				 TitleLoc ← TitleLoc
				 PropListLoc ← PropListLoc])

(NC.GetNoteCardFromStream
  [LAMBDA (Card Stream IndexLocs)                            (* rht: "28-Jan-86 14:17")

          (* * Like NC.GetNoteCard except gets card from given Stream instead of its notefile. Uses IndexLocs record to know 
	  where to look for card parts.)


    (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile) of Card))
		  (SETFILEPTR Stream (fetch (IndexLocs MainCardDataLoc) of IndexLocs))
		  (NC.GetMainCardData Card Stream)
		  (SETFILEPTR Stream (fetch (IndexLocs LinksLoc) of IndexLocs))
		  (NC.GetLinks Card Stream)
		  (SETFILEPTR Stream (fetch (IndexLocs TitleLoc) of IndexLocs))
		  (NC.GetTitle Card Stream)
		  (SETFILEPTR Stream (fetch (IndexLocs PropListLoc) of IndexLocs))
		  (NC.GetPropList Card Stream)
		  (NC.ActivateCard Card)
		  Card])

(NC.MakeHashKeyFromCard
  [LAMBDA (Card)                                             (* rht: "28-Jan-86 15:54")

          (* * Create a hash key from the card's UID.)


    (NC.MakeHashKey (fetch (Card UID) of Card])

(NC.UpdateIndexLocIfNeeded
  [LAMBDA (NoteFile UID CardPartTypeNum OldLoc NewLoc)       (* rht: "15-May-87 22:00")

          (* * See if the current index pointer for given UID's card part points to OldLoc. If so, then change to point to 
	  NewLoc. Else do nothing, the card part version is not currently in use.)


    (LET ((Card (NC.CardFromUID UID NoteFile)))
         (if Card
	     then (AND (SELECTQ CardPartTypeNum
				      (0 (if (EQUAL (fetch (Card MainLoc) of Card)
							OldLoc)
					     then (replace (Card MainLoc) of Card with NewLoc)
					       ))
				      (1 (if (EQUAL (fetch (Card LinksLoc) of Card)
							OldLoc)
					     then (replace (Card LinksLoc) of Card
						       with NewLoc)))
				      (2 (if (EQUAL (fetch (Card TitleLoc) of Card)
							OldLoc)
					     then (replace (Card TitleLoc) of Card
						       with NewLoc)))
				      (3 (if (EQUAL (fetch (Card PropListLoc) of Card)
							OldLoc)
					     then (replace (Card PropListLoc) of Card
						       with NewLoc)))
				      (PROGN (FLASHW PROMPTWINDOW)
					       (NC.PrintMsg NIL T 
						       "Bad NoteFile. Please Inspect and Repair."
							      (CHARACTER 13))
					       NIL))
			   (replace (Card IndexDirtyFlg) of Card with T])

(NC.FixUpLinksInCardCopy
  [LAMBDA (CardCopy CardHashArray LinksHashArray CurrentLinkLabels NewLinkLabels InterestedWindow 
		    CopyExternalToLinksFlg CrossFileLinkModePropList)
                                                             (* rht: " 8-Jun-87 14:07")

          (* * For all the links from or to CardCopy, change other endpoint's card according to mapping table in 
	  CardHashArray. If other endpoint is a card not found in the hash array, then drop that link altogether.
	  The mapping from old link UIDs to new ones is in LinksHashArray. Any new link labels not in CurrentLinkLabels get 
	  TCONC'ed onto NewLinkLabels.)



          (* * rht 2/17/86: Now uses NC.ApplyFn instead of APPLY* for deleting and collecting references.)



          (* * rht 11/1/86: Added missing var bindings and a BLOCK)



          (* * rht 6/6/87: Added new args InterestedWindow, CopyExternalToLinksFlg, and CrossFileLinkModePropList to handle 
	  optional copying of external links.)


    (LET ((CardCopyType (NC.FetchType CardCopy)))

          (* * Fix all the From links.)


         (NC.SetFromLinks CardCopy (for Link in (NC.FetchFromLinks CardCopy) eachtime
										      (BLOCK)
					bind SourceCard OldLinkUID LinkLabel
					when (SETQ SourceCard (GETHASH (fetch (Link 
										       SourceCard)
										of Link)
									     CardHashArray))
					collect (replace (Link DestinationCard) of Link
						     with CardCopy)
						  (replace (Link SourceCard) of Link
						     with SourceCard)
						  (replace (Link UID) of Link
						     with (OR (GETHASH (SETQ OldLinkUID
									       (fetch (Link UID)
										  of Link))
									     LinksHashArray)
								  (PUTHASH OldLinkUID (NC.MakeUID)
									     LinksHashArray)))
                                                             (* Keep track of link labels in case any are new.)
						  (OR (FMEMB (SETQ LinkLabel
								   (fetch (Link Label)
								      of Link))
								 CurrentLinkLabels)
							(NC.SystemLinkLabelP LinkLabel)
							(FMEMB LinkLabel (CAR NewLinkLabels))
							(TCONC NewLinkLabels LinkLabel))
						  Link))

          (* * Do it all again for the To links.)


         (NC.SetToLinks CardCopy (for Link in (NC.FetchToLinks CardCopy) eachtime (BLOCK)
				      bind DestCard OldLinkUID LinkLabel
				      when (SETQ DestCard (GETHASH (fetch (Link 
										  DestinationCard)
									    of Link)
									 CardHashArray))
				      collect (replace (Link SourceCard) of Link with 
											 CardCopy)
						(replace (Link DestinationCard) of Link
						   with DestCard)
						(replace (Link UID) of Link
						   with (OR (GETHASH (SETQ OldLinkUID
									     (fetch (Link UID)
										of Link))
									   LinksHashArray)
								(PUTHASH OldLinkUID (NC.MakeUID)
									   LinksHashArray)))
                                                             (* Keep track of link labels in case any are new.)
						(OR (FMEMB (SETQ LinkLabel (fetch
								   (Link Label) of Link))
							       CurrentLinkLabels)
						      (NC.SystemLinkLabelP LinkLabel)
						      (FMEMB LinkLabel (CAR NewLinkLabels))
						      (TCONC NewLinkLabels LinkLabel))
						Link))

          (* * Now fix the links inside imageobj's in the card's substance.)


         (AND (fetch (Card LinkAnchorModesSupported) of CardCopy)
		(for Link in (CAR (NC.ApplyFn CollectLinksFn CardCopy)) eachtime (BLOCK)
		   bind PreviousLink do (LET ((DestCard (fetch (Link DestinationCard)
							       of Link))
						  (LinkLabel (fetch (Link Label) of Link))
						  OldLinkUID DestCardCopy NewLink)
					         (COND
						   ((SETQ DestCardCopy (GETHASH DestCard 
										    CardHashArray))
						     (replace (Link SourceCard) of Link
							with CardCopy)
						     (replace (Link DestinationCard) of Link
							with DestCardCopy)
						     (replace (Link UID) of Link
							with (OR (GETHASH
								       (SETQ OldLinkUID
									 (fetch (Link UID)
									    of Link))
								       LinksHashArray)
								     (PUTHASH OldLinkUID (
										  NC.MakeUID)
										LinksHashArray)))
                                                             (* Keep track of link labels in case any are new.)
						     (OR (FMEMB LinkLabel CurrentLinkLabels)
							   (NC.SystemLinkLabelP LinkLabel)
							   (FMEMB LinkLabel (CAR NewLinkLabels))
							   (TCONC NewLinkLabels LinkLabel))
						     (SETQ PreviousLink Link))
						   ([AND CopyExternalToLinksFlg
							   (if (NC.CrossFileLinkCardP DestCard)
							       then (SETQ DestCard
									(NC.GetCrossFileLinkDestCard
									  DestCard InterestedWindow))
							     else DestCard)
							   (SETQ NewLink
							     (NC.MakeLink NIL LinkLabel DestCard 
									    CardCopy
									    (fetch (Link 
										      DisplayMode)
									       of Link)
									    (fetch (Link AnchorMode)
									       of Link)
									    NIL NIL PreviousLink
									    (
								      NC.ComputeCrossFileLinkMode
									      DestCard 
									CrossFileLinkModePropList 
									      InterestedWindow]
                                                             (* It's an external link. Try to make a copy, possibly
							     resulting in a cross-file link.)
                                                             (* Smash the imageobj's link with contents of new one 
							     we just made.)
						     [for FieldName in (RECORDFIELDNAMES
									     (QUOTE Link))
							do (RECORDACCESS
							       FieldName Link (RECLOOK
								 (QUOTE Link))
							       (QUOTE REPLACE)
							       (RECORDACCESS FieldName NewLink
									       (RECLOOK
										 (QUOTE Link))
									       (QUOTE FETCH]
						     (SETQ PreviousLink Link))
						   (T (NC.ApplyFn DeleteLinksFn CardCopy Link])

(NC.OperationInProgress
  [LAMBDA (Card)                                             (* fgh: "25-Jun-86 19:55")

          (* * Return the process for the operation in prgress on Card, if any)



          (* * fgh 6/13/86 First created.)


    (OR (AND (PROCESSP (NC.FetchUserDataProp Card (QUOTE ProcessInProgress)))
		 (NC.FetchUserDataProp Card (QUOTE OperationInProgress)))
	  (AND (PROCESSP (NC.NoteFileProp (fetch (Card NoteFile) of Card)
						(QUOTE ProcessInProgress)))
		 (NC.NoteFileProp (fetch (Card NoteFile) of Card)
				    (QUOTE OperationInProgress])

(NC.GetNewCard
  [LAMBDA (NoteFile Type OverrideUID)                        (* rht: "22-Jan-87 11:46")

          (* * See NCLocalDevice.NewCardUID.)



          (* * kef 7/17/86: Updated to use the device vector function to grab an IndexLoc in the local case, and the UID in 
	  all cases.)



          (* * kef 8/4/86: Now takes Type argument and passes it onto the NewCardUIDFn)



          (* * fgh 8/31/86 Changed APPLY* to NC.ApplyFn.)



          (* * rht 1/22/87: Added OverrideUID argument. Use with GREAT care!)


    (LET ((Card (create Card
			  NoteFile ← NoteFile
			  UID ← OverrideUID))
	  ReturnValue)
         (COND
	   ((type? Card (SETQ ReturnValue (NC.ApplyFn NewCardUIDFn Card Type)))
	     (NC.InstallCardInNoteFile Card NoteFile))
	   (T (NC.ReportError (QUOTE NC.GetNewCard)
				ReturnValue)))
     Card])

(NC.InstallCriticalUIDsInNoteFile
  [LAMBDA (NoteFile CriticalUIDs)                            (* fgh: "24-May-86 12:23")

          (* * Install the contents of the critical UIDs record into the NoteFile object.)


    (LET [(HashArray (HARRAYP (fetch (NoteFile HashArray) of NoteFile]
         (if (NOT (NC.SameUIDP (fetch (NoteFile UID) of NoteFile)
				     (fetch (NoteFileCriticalUIDs NoteFile) of CriticalUIDs)))
	     then (ERSETQ (NC.ReportError NIL "Mismatch in NoteFile UIDs."))
	   else [replace (NoteFile TableOfContentsCard) of NoteFile
		     with (if HashArray
				then (NC.CardFromUID (fetch (NoteFileCriticalUIDs 
										  TableOfContents)
							    of CriticalUIDs)
							 NoteFile)
			      else (create Card
					       UID ← (fetch (NoteFileCriticalUIDs TableOfContents)
							of CriticalUIDs]
		  [replace (NoteFile OrphansCard) of NoteFile
		     with (if HashArray
				then (NC.CardFromUID (fetch (NoteFileCriticalUIDs Orphans)
							    of CriticalUIDs)
							 NoteFile)
			      else (create Card
					       UID ← (fetch (NoteFileCriticalUIDs Orphans)
							of CriticalUIDs]
		  [replace (NoteFile ToBeFiledCard) of NoteFile
		     with (if HashArray
				then (NC.CardFromUID (fetch (NoteFileCriticalUIDs ToBeFiled)
							    of CriticalUIDs)
							 NoteFile)
			      else (create Card
					       UID ← (fetch (NoteFileCriticalUIDs ToBeFiled)
							of CriticalUIDs]
		  [replace (NoteFile LinkLabelsCard) of NoteFile
		     with (if HashArray
				then (NC.CardFromUID (fetch (NoteFileCriticalUIDs LinkLabels)
							    of CriticalUIDs)
							 NoteFile)
			      else (create Card
					       UID ← (fetch (NoteFileCriticalUIDs LinkLabels)
							of CriticalUIDs]
		  (replace (NoteFile RegistryCard) of NoteFile
		     with (if HashArray
				then (NC.CardFromUID (fetch (NoteFileCriticalUIDs Registry)
							    of CriticalUIDs)
							 NoteFile)
			      else (create Card
					       UID ← (fetch (NoteFileCriticalUIDs Registry)
							of CriticalUIDs])
)
(* * changes to NCLOCALDEVICE)

(DEFINEQ

(NCLocalDevice.GetNoteFileHeader
  [LAMBDA (NoteFile)                                         (* kirk: "21-Dec-86 16:57")

          (* * Fill in the NoteFile object with stuff from the file.)


    (LET ((Stream (fetch (NoteFile Stream) of NoteFile)))
                                                             (* Recover the 30 information bytes for the notefile.)
         (SETFILEPTR Stream 0)                             (* 3 bytes for next card ID)
         (replace (NoteFile NextIndexNum) of NoteFile with (NC.ReadPtr Stream 3))
                                                             (* 3 bytes for index size)
         (replace (NoteFile HashArraySize) of NoteFile with (NC.ReadPtr Stream 3))
                                                             (* One dummy byte so that version number stays in 
							     favorite old place.)
         (NC.ReadPtr Stream 1)                               (* 1 byte for notecards version number)
         (replace (NoteFile Version) of NoteFile with (NC.ReadPtr Stream 1))
                                                             (* 3 bytes for next link ID)
         (replace (NoteFile NextLinkNum) of NoteFile with (NC.ReadPtr Stream 3))
                                                             (* 3 bytes for pointer to current checkpt ptr.)
         (replace (NoteFile CheckptPtr) of NoteFile with (NC.ReadPtr Stream 3))
                                                             (* 14 bytes for NoteFile UID.)
         (replace (NoteFile UID) of NoteFile with (NC.ReadUID NoteFile))
                                                             (* 2 bytes for future needs)
         (NC.ReadPtr Stream 2)
     NoteFile])

(NCLocalDevice.OpenNoteFile
  [LAMBDA (NoteFile PromptWindow Don'tCheckForTruncationFlg)
                                                             (* rht: " 7-Jul-87 18:08")

          (* * OpenNoteFileFn for the local, single user device.)



          (* * fgh 5/22/86 First created.)



          (* * fgh 9/1/86 Reimplemented ReadOnly notefile.)



          (* * rht 10/31/86: Added Don'tCheckForTruncationFlg arg.)



          (* * rht 6/8/87: Switched order of checks of version num and plausibility. It was also ignoring the error value 
	  returned by NCLocalDevice.CheckForPlausibleNoteFileHeader.)



          (* * rht 7/7/87: Undid first half of previous change. I.e. order of checks of version num and plausibility is back 
	  to the way it used to be.)


    (OR [CAR (ERSETQ (PROG ((FullName (INFILEP (fetch (NoteFile FullFileName)
							    of NoteFile)))
				    EofPtr CriticalUIDs Stream ReturnVal)

          (* * First check for possible errors.)


			           (if (NULL FullName)
				       then 

          (* * Error: NoteFileNotFound, Return)


					      (RETURN (QUOTE NoteFileNotFound))
				     elseif (OPENP FullName)
				       then 

          (* * Error: NoteFile already open, Return)


					      (RETURN (QUOTE NoteFileAlreadyOpen))
				     elseif [NULL (ERSETQ (SETQ Stream
								  (OPENSTREAM
								    FullName
								    (if (fetch (NoteFile 
										      ReadOnlyFlg)
									     of NoteFile)
									then (QUOTE INPUT)
								      else (QUOTE BOTH))
								    (QUOTE OLD)
								    (QUOTE ((TYPE BINARY]
				       then 

          (* * Error: File won't open)


					      (RETURN (QUOTE NoteFileOpenFailed)))

          (* * All is okay for now, create fill in the NoteFile object a bit.)


			           (replace (NoteFile Stream) of NoteFile with Stream)
			           (replace (NoteFile FullFileName) of NoteFile with FullName)
			           (NC.SetMonitor NoteFile (CREATE.MONITORLOCK FullName))

          (* * Make sure stream is not closed by CLOSEALLs)


			           (WHENCLOSE Stream (QUOTE CLOSEALL)
						(QUOTE NO))

          (* * Get the header and check for correct version, correct checkpoint, & plausibility.)


			           (NCLocalDevice.GetNoteFileHeader NoteFile)
			           (SETQ EofPtr (GETEOFPTR (fetch (NoteFile Stream)
								  of NoteFile)))
			           [COND
				     [(NOT (NCLocalDevice.NoteFileVersionOkayP NoteFile))
				       (RETURN (NCLocalDevice.OpenFailed NoteFile (QUOTE 
									  NoteFileNeedsConversion]
				     ([NOT (type? NoteFile (SETQ ReturnVal (
						    NCLocalDevice.CheckForPlausibleNoteFileHeader
							  NoteFile EofPtr]
				       (RETURN (NCLocalDevice.OpenFailed NoteFile ReturnVal)))
				     ((AND (NULL Don'tCheckForTruncationFlg)
					     (NCLocalDevice.NoteFileNeedsTruncationP NoteFile 
										       EofPtr))
				       (RETURN (NCLocalDevice.OpenFailed NoteFile (QUOTE 
									  NoteFileNeedsTruncation]

          (* * Go get the first six card UIDs on the file.)


			           (SETQ CriticalUIDs (NCLocalDevice.GetSpecialCardUIDs NoteFile))
			           (replace (NoteFileCriticalUIDs NoteFile) of CriticalUIDs
				      with (fetch (NoteFile UID) of NoteFile))

          (* * Return with list of special uids and NF-UID.)


			           (RETURN CriticalUIDs]
	  (PROGN 

          (* * Open must have failed. Return a message to that effect.)


		   (NCLocalDevice.OpenFailed NoteFile])

(NCLocalDevice.PutNoteFileHeader
  [LAMBDA (NoteFile)                                         (* fgh: "26-May-86 23:13")

          (* * Write down to the notefile the header information extracted from the NoteFile object.)



          (* * fgh 5/26/86 Renamed from NC.PutNoteFileHeader)


    (LET ((Stream (fetch (NoteFile Stream) of NoteFile))
	  (FullFileName (fetch (NoteFile FullFileName) of NoteFile))
	  (UID (fetch (NoteFile UID) of NoteFile))
	  (NextIndexNum (fetch (NoteFile NextIndexNum) of NoteFile))
	  (HashArraySize (fetch (NoteFile HashArraySize) of NoteFile))
	  (NextLinkNum (fetch (NoteFile NextLinkNum) of NoteFile))
	  (CheckptPtr (fetch (NoteFile CheckptPtr) of NoteFile))
	  (Version (fetch (NoteFile Version) of NoteFile)))
         (WITH.MONITOR (NC.FetchMonitor NoteFile)
		       (if (OPENP Stream)
			   then                            (* Fill in the 30 information bytes for the notefile.)
				  (SETFILEPTR Stream 0)    (* 3 bytes for next card ID)
				  (NC.WritePtr Stream NextIndexNum 3) 
                                                             (* 3 bytes for index size)
				  (NC.WritePtr Stream HashArraySize 3) 
                                                             (* One dummy byte so that version number stays in 
							     favorite old place.)
				  (NC.WritePtr Stream -1 1) 
                                                             (* 1 byte for notecards version number)
				  (NC.WritePtr Stream Version 1) 
                                                             (* 3 bytes for next link ID)
				  (NC.WritePtr Stream NextLinkNum 3) 
                                                             (* 3 bytes for pointer to current checkpt ptr.)
				  (NC.WritePtr Stream CheckptPtr 3) 
                                                             (* 14 bytes for NoteFile UID.)
				  (NC.WriteUID NoteFile UID) 
                                                             (* 1 bytes for future needs)
				  (NC.WritePtr Stream -1 1)
				  NoteFile
			 else (NC.ReportError NIL "NC.PutNoteFileHeader: Stream not open!!!"])

(NCLocalDevice.NewCardUID
  [LAMBDA (Card)                                             (* rht: "15-May-87 19:00")

          (* * The local single user device vector function, which installs the UID and IndexLoc into the Card Object.)



          (* * kef 8/6/86: Incorporated kirk's change: Kirk 7/25/86: Fixed overflow check to catch GEQ, gave warning message 
	  a window to show message, changed warning message and changed break call to ERROR!.)



          (* * rht 1/22/87: Now only calls NC.MakeUID if Card doesn't already have one. Made small change to calculation of 
	  PercentUsed. Prevented NextIndexNum from being incremented in the case of full index.)



          (* * rht 5/15/87: Now calls NC.CheckForExpandIndex to handle cases when index is full or nearly full.)


    (LET ((NoteFile (fetch (Card NoteFile) of Card))
	  NextIndexNum IndexNumsFreeList IndexNum PercentUsed NumUsed)
         (NC.CheckForExpandIndex NoteFile)
         (SETQ NextIndexNum (fetch (NoteFile NextIndexNum) of NoteFile))
         (SETQ IndexNumsFreeList (fetch (NoteFile IndexNumsFreeList) of NoteFile))
         (if IndexNumsFreeList
	     then (SETQ IndexNum (pop IndexNumsFreeList))
		    (replace (NoteFile IndexNumsFreeList) of NoteFile with IndexNumsFreeList)
	   else (SETQ IndexNum NextIndexNum)
		  (replace (NoteFile NextIndexNum) of NoteFile with (ADD1 NextIndexNum)))
         (replace (Card IndexLoc) of Card with (NC.NoteFileLocFromIndexNum IndexNum))
         (replace (Card IndexDirtyFlg) of Card with T)
         (OR (type? UID (fetch (Card UID) of Card))
	       (replace (Card UID) of Card with (NC.MakeUID)))
     Card])

(NCLocalDevice.GetCardInfo
  [LAMBDA (Card Aspects)                                     (* kirk: "10-Sep-86 16:02")

          (* * Returns an ALIST of all of the Aspects requested.)



          (* * fgh 9/3/86 Added TITLE aspect to help spped up caching on server.)



          (* * kirk 9/10/86 Deleted call on NC.FetchType testing before going to device because caused stack overflow in 
	  CacheTypesAndTitles)


    (for Aspect in [MKLIST (OR Aspects (QUOTE (STATUS TYPE]
       collect (CONS Aspect (SELECTQ Aspect
					   [TYPE (WITH.MONITOR
						   (NC.FetchMonitor (fetch (Card NoteFile)
									 of Card))
						   (LET [(Stream (fetch (NoteFile Stream)
								    of (fetch (Card NoteFile)
									    of Card]
						        (SETFILEPTR Stream (fetch (Card MainLoc)
										of Card))
						        (NC.ReadCardPartHeader Card 
										NC.ItemIdentifier 
										 Stream)
						        (NC.SetType Card (NC.ReadCardType Stream))
						        (NC.FetchType Card]
					   (STATUS (NC.FetchStatus Card))
					   (TITLE (NC.RetrieveTitle Card))
					   (SHOULDNT (CONCAT "Unknown card aspect:  " Aspect])

(NCLocalDevice.PutCardPart
  [LAMBDA (Card CardPartName WhenFlg)                        (* rht: "12-Sep-86 00:52")

          (* * This is the local single user device put card part function.)



          (* * The free variable PutSuccessfulLoc is bound in the calling function, either NC.PutTitle or NC.PutLinks, etc. 
	  If NIL, then the Put wasn't successful, so report the error. If non-NIL, then it should be the position in the file
	  where we put the card part, so now we can set the appropriate card part loc slot to be that number.)



          (* * kef 7/28/86: Added REGION possibility to CardPartName.)



          (* * rht&fgh 9/12/86: Now doesn't try to read links card parts if card is new in FROMLINKS/BEFORE case.)


    (DECLARE (GLOBALVARS NC.LinksIdentifier))
    (SELECTQ WhenFlg
	       [BEFORE (SELECTQ CardPartName
				  (FROMLINKS

          (* * In this case, let's grab the TOLINKS and GLOBALTOLINKS as they exist on the file still, and save them on the 
	  Card's UserProps, so that we can use them in the AFTER function to write them.)


				    (WITH.MONITOR (NC.FetchMonitor (fetch (Card NoteFile)
									of Card))
						  (LET (ToLinks GlobalLinks)
						       [if (NOT (NC.FetchNewCardFlg Card))
							   then
							    (SETFILEPTR (fetch (NoteFile Stream)
									     of
									      (fetch (Card NoteFile)
										 of Card))
									  (fetch (Card LinksLoc)
									     of Card))
							    (NC.ReadCardPartHeader
							      Card NC.LinksIdentifier
							      (fetch (NoteFile Stream)
								 of (fetch (Card NoteFile)
									 of Card)))
							    [SETQ ToLinks
							      (NC.ReadListOfLinks
								(fetch (NoteFile Stream)
								   of (fetch (Card NoteFile)
									   of Card]
							    (NC.ReadListOfLinks
							      (fetch (NoteFile Stream)
								 of (fetch (Card NoteFile)
									 of Card)))
							    (SETQ GlobalLinks
							      (NC.ReadListOfLinks
								(fetch (NoteFile Stream)
								   of (fetch (Card NoteFile)
									   of Card]
						       (NC.PutProp Card (QUOTE OldLinks)
								     (CONS ToLinks GlobalLinks)))
						  (SETFILEPTR (fetch (NoteFile Stream)
								   of (fetch (Card NoteFile)
									   of Card))
								-1)))
				  ((TITLE SUBSTANCE LINKS PROPLIST)
				    (SETFILEPTR (fetch (NoteFile Stream)
						     of (fetch (Card NoteFile) of Card))
						  -1))
				  [REGION                    (* In the region case, set the file pointer to the 
							     spot in the NoteFile just past the Card Type in the 
							     header information.)
					  (SETFILEPTR (fetch (NoteFile Stream)
							   of (fetch (Card NoteFile)
								   of Card))
							(fetch (Card MainLoc) of Card))
					  (NC.ReadCardPartHeader Card NC.ItemIdentifier
								   (fetch (NoteFile Stream)
								      of (fetch (Card NoteFile)
									      of Card)))
					  (NC.ReadCardType (fetch (NoteFile Stream)
								of (fetch (Card NoteFile)
									of Card]
				  (SHOULDNT (CONCAT "Bad card part name:  " CardPartName]
	       [AFTER (AND PutSuccessfulLoc (SELECTQ CardPartName
							 (TITLE (NC.SetTitleLoc Card 
										 PutSuccessfulLoc))
							 (SUBSTANCE (NC.SetMainLoc Card 
										 PutSuccessfulLoc))
							 (LINKS (NC.SetLinksLoc Card 
										 PutSuccessfulLoc))
							 (PROPLIST (NC.SetPropListLoc Card 
										 PutSuccessfulLoc))
							 (FROMLINKS (NCLocalDevice.PutFromLinks
									Card PutSuccessfulLoc))
							 (REGION NIL)
							 (SHOULDNT (CONCAT 
									  "Bad card part name:  "
									       CardPartName]
	       (SHOULDNT (CONCAT "Don't understand WhenFlg argument:  " WhenFlg])

(NCLocalDevice.GetCardPart
  [LAMBDA (Card CardPartName WhenFlg)                        (* Feuerman "16-Jul-86 08:26")

          (* * The local single user GetCardPartFn.)


    (COND
      ((EQ WhenFlg (QUOTE BEFORE))
	(SETFILEPTR (fetch (NoteFile Stream) of (fetch (Card NoteFile) of Card))
		      (SELECTQ CardPartName
				 (TITLE (fetch (Card TitleLoc) of Card))
				 (SUBSTANCE (fetch (Card MainLoc) of Card))
				 (TYPE (fetch (Card MainLoc) of Card))
				 (LINKS (fetch (Card LinksLoc) of Card))
				 (PROPLIST (fetch (Card PropListLoc) of Card))
				 (SHOULDNT (CONCAT "Unrecognized card part:  " CardPartName])

(NCLocalDevice.GetHashArray
  [LAMBDA (NoteFile QuietFlg InterestedWindow OperationMsg)
                                                             (* fgh: " 1-Sep-86 17:50")

          (* * Read the hash array off of a local device notefile, building the hash array along the way.)



          (* * fgh 5/23/86 First created on the basis of the old NC.GetHashArray.)



          (* * fgh 9/1/86 Reimplemented QuietFlg InterestedWindow OperationMsg args.)



          (* * Get the hash array.)


    (if (NOT (OPENP (fetch (NoteFile Stream) of NoteFile)))
	then 

          (* * NoteFile isn't open, Error.)


	       (QUOTE NoteFileNotOpen)
      else 

          (* * Grab the monitor lock and read the index.)


	     (WITH.MONITOR (NC.FetchMonitor NoteFile)
			   (LET ((Stream (fetch (NoteFile Stream) of NoteFile))
				 (CardTotal (SUB1 (fetch (NoteFile NextIndexNum) of NoteFile)))
				 IndexNumsFreeList)

          (* * Set fileptr to beginning of the index.)


			        [SETFILEPTR Stream (CONSTANT (fetch (NoteFileVersion 
									       NoteFileHeaderSize)
								    of (
								     NCLocalDevice.CurrentVersion]

          (* * Read in the index entries, creating a card for each and installing it in the hash array.)


			        [for IndexNum from 1 to CardTotal bind Card
				   eachtime (if (AND (NULL QuietFlg)
							   (EQ (IMOD IndexNum 100)
								 1))
						  then (NC.PrintMsg InterestedWindow T
									(OR OperationMsg "")
									"Building index array."
									(CHARACTER 13)
									"Processing number " IndexNum 
									" of "
									CardTotal "." (CHARACTER
									  13)))
					      (BLOCK)
				   do (SETQ Card (NCLocalDevice.ReadIndexEntry NoteFile))
					(if (EQ (fetch (Card Status) of Card)
						    (QUOTE FREE))
					    then (push IndexNumsFreeList IndexNum)
					  else (NC.InstallCardInNoteFile Card NoteFile))
				   finally (AND (NULL QuietFlg)
						    (NC.PrintMsg InterestedWindow T
								   (OR OperationMsg "")
								   "Building index array."
								   (CHARACTER 13)
								   "Done."
								   (CHARACTER 13]

          (* * Set the free list)


			        (replace (NoteFile IndexNumsFreeList) of NoteFile with 
										IndexNumsFreeList)

          (* * Return the NoteFile NoteFile, indicating everything is okay.)


			    NoteFile])

(NCLocalDevice.PutHashArray
  [LAMBDA (NoteFile InterestedWindow AllCardsFlg OperationMsg QuietFlg)
                                                             (* rht: "24-May-87 00:32")

          (* * Write down the hash array's contents to the notefile.)



          (* * kirk 27Nov85 Added AllCardsFlg for use by the compactor.)



          (* * fgh 5/26/86 Adapted from NC.PutHashArray with minor changes.)



          (* * fgh 9/1/86 Reimplemented QuietFlg.)



          (* * fgh 9/5/86 Put in check for HARRAYP of NoteFile's HashArray becuase MAPHASH of NIL will map hash down an 
	  arbitrary array.)



          (* * rht 3/13/87: Fixed the "TPutting" print msg. Changed AllActiveCardsFlg to be AllCardsFlg.
	  This allows cards with Deleted status to be written down with Free status.)



          (* * rht 5/24/87: Now sets InterestedWindow if was passed in nil.)


    (OR InterestedWindow (SETQ InterestedWindow (NC.CoerceToInterestedWindow NoteFile)))
    (if (HARRAYP (fetch (NoteFile HashArray) of NoteFile))
	then (LET ((CardTotal (SUB1 (fetch (NoteFile NextIndexNum) of NoteFile)))
		     (Num 0))
		    (OR QuietFlg (NC.PrintMsg InterestedWindow T (OR OperationMsg "")
						  "Putting index array."
						  (CHARACTER 13)
						  "Processing item number " 1 " out of " CardTotal 
						  "."
						  (CHARACTER 13)))
		    (NC.MapCards NoteFile (FUNCTION (LAMBDA (Card)
				     [OR QuietFlg (PROGN (SETQ Num (ADD1 Num))
							     (AND (ZEROP (IREMAINDER Num 100))
								    (NC.PrintMsg InterestedWindow T
										   (OR OperationMsg 
											 "")
										   
									   "Putting index array."
										   (CHARACTER
										     13)
										   
									"Processing item number "
										   Num " out of " 
										   CardTotal "."
										   (CHARACTER
										     13]
                                                             (* Turn deleted slots into free ones.)
				     (if (AND AllCardsFlg (NEQ (fetch (Card Status)
									of Card)
								     (QUOTE ACTIVE)))
					 then (replace (Card Status) of Card
						   with (QUOTE FREE)))
				     (if (OR AllCardsFlg (fetch (Card IndexDirtyFlg)
								of Card))
					 then (NCLocalDevice.PutIndexEntry Card])

(NCLocalDevice.PutIndexEntry
  [LAMBDA (Card)                                             (* fgh: "26-May-86 23:20")

          (* * Write down to the file the index entry for this card.)



          (* * fgh 5/26/86 Renamed from NC.PutIndexEntry.)


    (LET ((NoteFile (fetch (Card NoteFile) of Card)))
         (WITH.MONITOR (NC.FetchMonitor NoteFile)
		       (LET ((Stream (fetch (NoteFile Stream) of NoteFile)))
			    (SETFILEPTR Stream (fetch (Card IndexLoc) of Card))
			    (NC.WriteStatus Stream (fetch (Card Status) of Card))
			    (NC.WriteUID NoteFile (fetch (Card UID) of Card))
			    (NC.WritePtr Stream (fetch (Card MainLoc) of Card)
					 3)
			    (NC.WritePtr Stream (fetch (Card LinksLoc) of Card)
					 3)
			    (NC.WritePtr Stream (fetch (Card TitleLoc) of Card)
					 3)
			    (NC.WritePtr Stream (fetch (Card PropListLoc) of Card)
					 3)
			    (replace (Card IndexDirtyFlg) of Card with NIL])

(NCLocalDevice.PutFromLinks
  [LAMBDA (Card StreamLoc)                                   (* rht: " 4-Nov-86 19:32")

          (* * Assuming that Card has on it UserProps the old TOLINKS and GLOBALLINKS, this function rewrites over the end of
	  the NoteFile stream starting at StreamLoc the Links Info merged with the new FromLinks, which are already on the 
	  Stream.)



          (* * rht&rg 11/4/86: Now sets length field properly after writing down the links.)


    (DECLARE (GLOBALVARS NC.LinksIdentifier))
    (LET ((STREAM (fetch (NoteFile Stream) of (fetch (Card NoteFile) of Card)))
	  FromLinks EndLoc DataLoc)
         (SETFILEPTR STREAM StreamLoc)
         (NC.ReadCardPartHeader Card NC.LinksIdentifier STREAM)
         (SETQ DataLoc (GETFILEPTR STREAM))
         (SETQ FromLinks (NC.ReadListOfLinks STREAM))
         (SETFILEPTR STREAM DataLoc)
         [NC.WriteListOfLinks STREAM (CAR (NC.GetProp Card (QUOTE OldLinks]
         (NC.WriteListOfLinks STREAM FromLinks)
         [NC.WriteListOfLinks STREAM (CDR (NC.GetProp Card (QUOTE OldLinks]
         (SETQ EndLoc (GETFILEPTR STREAM))
         (SETFILEPTR STREAM StreamLoc)
         (NC.WritePtr STREAM (DIFFERENCE EndLoc StreamLoc)
		      3)
         (SETFILEPTR STREAM EndLoc)
         (NC.SetLinksLoc Card StreamLoc])

(NCLocalDevice.ReadIndexEntry
  [LAMBDA (NoteFile)                                         (* fgh: "25-May-86 18:36")

          (* * Get a card from current position of file and install it into notefile.)



          (* * fgh 5/23/86 First created on the basis of the old NC.ReadIndexEntry)


    (LET ((Stream (fetch (NoteFile Stream) of NoteFile)))
         (create Card
		   IndexLoc ← (GETFILEPTR Stream)
		   Status ← (NC.ReadStatus Stream)
		   UID ← (NC.ReadUID NoteFile)
		   MainLoc ← (NC.ReadPtr Stream 3)
		   LinksLoc ← (NC.ReadPtr Stream 3)
		   TitleLoc ← (NC.ReadPtr Stream 3)
		   PropListLoc ← (NC.ReadPtr Stream 3)
		   IndexDirtyFlg ← NIL
		   NoteFile ← NoteFile])
)
(* * changes to NCCONVERTVERSION2TO3)

(DEFINEQ

(NC.ConvertNoteFileVersion2To3
  [LAMBDA (StreamOrFileName InterestedWindow)                (* rht: " 6-Nov-86 12:47")

          (* * Convert this notefile to version 3 outputting the version 3 notefile to new version with same filename.)



          (* * fgh 12/17/85 fixed call to CreateDatabaseFile to lop the version off of the file name.)



          (* * rht 12/18/85: Now clears Version2HashArray in case uncollectable garbage is left around.)



          (* * rht 5/7/86: No longer just passes IndexSizeInEntries on to NC.CreateDatabaseFile. Uses NextIndexNum and 
	  NC.DefaultIndexSizeInEntries to compute a reasonable hasharray size (hopefully smaller than 10240, the largest 
	  allowable.))



          (* * rht 7/16/86: Added InterestedWindow arg.)



          (* * rht 11/6/86: Now autoload apply's NC.ScavengeDatabaseFile in case NCREPAIR not loaded.)


    (DECLARE (GLOBALVARS NC.DefaultIndexSizeInEntries))
    (LET ((OperationMsg "Converting file to version 3.")
	  CardTotal FileName FromStream FromNoteFile ToNoteFile Version2HashArray Version 
	  NextIndexNum IndexSizeInEntries NextLinkNum CheckptPtr ToFileName)
         [if (STREAMP StreamOrFileName)
	     then (SETQ FromStream StreamOrFileName)
		    (SETQ FileName (FULLNAME StreamOrFileName))
	   else (SETQ FileName StreamOrFileName)
		  (SETQ FromStream (OPENSTREAM FileName (QUOTE BOTH]
         (SETFILEPTR FromStream 7)
         (if (EQ (SETQ Version (NC.ReadPtr FromStream 1))
		     2)
	     then                                          (* FromStream is indeed version 2.0)
                                                             (* Get all the header info off the 1.2 stream.)
		    (SETFILEPTR FromStream 0)
		    (SETQ NextIndexNum (NC.ReadPtr FromStream 2))
		    (SETQ CardTotal (SUB1 NextIndexNum))
		    (SETQ IndexSizeInEntries (NC.ReadPtr FromStream 2))
		    (SETQ NextLinkNum (NC.ReadPtr FromStream 3)) 
                                                             (* Skip version number.)
		    (NC.ReadPtr FromStream 1)
		    (SETQ CheckptPtr (NC.ReadPtr FromStream 3)) 

          (* * Create a dummy notefile object for the 1.2 source notefile.)


		    (SETQ FromNoteFile (create NoteFile
						   UID ← (NC.MakeUID)
						   Stream ← FromStream
						   FullFileName ← (FULLNAME FileName)
						   NextIndexNum ← NextIndexNum
						   Version ← Version
						   NextLinkNum ← NextLinkNum
						   CheckptPtr ← CheckptPtr))
		    (SETQ ToNoteFile (NC.CreateDatabaseFile (PACKFILENAME (QUOTE VERSION)
										NIL
										(QUOTE BODY)
										FileName)
								(MAX NC.DefaultIndexSizeInEntries
								       (TIMES 2 NextIndexNum))
								OperationMsg T NIL NIL 
								InterestedWindow))
		    (SETQ ToFileName (fetch (NoteFile FullFileName) of ToNoteFile))
		    (if (AND (type? NoteFile ToNoteFile)
				 (NC.OpenDatabaseFile ToNoteFile NIL T T NIL NIL NIL NIL T NIL 
							InterestedWindow))
			then 

          (* * Fill in NewNoteFile's hash array with new UIDs. Return a hash array mapping version 2 style ID atoms to 
	  version 3 style Cards.)


			       (NC.PrintMsg InterestedWindow T 
					      "Reading index of version 2 notefile ...")
			       (SETQ Version2HashArray (NC.BuildVersion2HashArray FromNoteFile 
										      ToNoteFile 
										      CardTotal))

          (* * For each card in the old notefile, fill in a version 3 card object for it and put the filled in card down to 
	  NewNoteFile.)


			       (NC.PrintMsg InterestedWindow T OperationMsg (CHARACTER 13)
					      "Processing card ID 1 out of " CardTotal)
			       (for IDNum from 1 to CardTotal eachtime (BLOCK)
				  do (if (ZEROP (REMAINDER IDNum 10))
					   then (NC.PrintMsg InterestedWindow T OperationMsg
								 (CHARACTER 13)
								 "Processing card ID " IDNum 
								 " out of "
								 CardTotal))
				       (NC.GetAndPutVersion2Card FromStream (NC.IDFromNumber
								     IDNum)
								   Version2HashArray FromNoteFile 
								   ToNoteFile))
                                                             (* Clear hash array to be sure uncollectable garbage 
							     isn't left around.)
			       (CLRHASH Version2HashArray)
			       (NC.CheckpointDatabase ToNoteFile T)
			       (NC.ForceDatabaseClose ToNoteFile)
			       (CLOSEF FromStream)         (* Rebuild To and From links.)
			       (NC.AutoloadApply* (FUNCTION NC.ScavengeDatabaseFile)
						  ToNoteFile NIL NIL NIL InterestedWindow)
			       (NC.PrintMsg InterestedWindow T "Done.")
			       ToFileName)
	   else (NC.ReportError "NC.ConvertNoteFileVersion2To3" (CONCAT "Filename " FileName 
									      " is version "
									      Version 
						       ".  Can only convert version 2 notefiles."))
		  NIL])

(NC.ConvertVersion2LinkIcon
  [LAMBDA (LinkIcon SourceCard Version2HashArray)            (* rht: "26-Nov-85 21:03")

          (* * Convert the link inside LinkIcon into a version 3 link. Use Version2HashArray to convert the Destination ID 
	  into a card object.)


    (LET ((Version2Link (fetch (IMAGEOBJ OBJECTDATUM) of LinkIcon)))
                                                             (* Make sure that version 2 link is in TYPERECORD 
							     format.)
         (if (NEQ (CAR Version2Link)
		      (QUOTE NOTECARDLINK))
	     then (SETQ Version2Link (CONS (QUOTE NOTECARDLINK)
						 Version2Link)))
                                                             (* Create and plug in a new link.)
         (replace (IMAGEOBJ OBJECTDATUM) of LinkIcon with (create Link
									  UID ← (NC.MakeUID)
									  SourceCard ← SourceCard
									  DestinationCard ←
									  (
								    NC.Version3CardFromVersion2ID
									    (fetch (NOTECARDLINK
										       DESTINATIONID)
									       of Version2Link)
									    Version2HashArray)
									  AnchorMode ←
									  (fetch (NOTECARDLINK
										     ANCHORMODE)
									     of Version2Link)
									  Label ←
									  (fetch (NOTECARDLINK
										     LINKLABEL)
									     of Version2Link)
									  DisplayMode ←
									  (fetch (NOTECARDLINK
										     DISPLAYMODE)
									     of Version2Link)))
                                                             (* Change display mode to record format if it's 
							     currently atomic.)
         (NC.CheckDisplayModeFormat Version2Link])

(NC.ConvertLinkFormat
  [LAMBDA (ListOfLinks Version2HashArray)                    (* fgh: "25-May-86 18:08")

          (* * Convert links from NOTECARDLINK record to Link datatype. Note the conversion of NoSource from a dangling link 
	  to a property list item.)



          (* * fgh 5/21/86 First created.)


    (bind NewLink ConvertedLinks PropList Card for Link in ListOfLinks
       do (OR (EQ (CAR Link)
			(QUOTE NOTECARDLINK))
		  (SETQ Link (CONS (QUOTE NOTECARDLINK)
				       Link)))
	    [if (NEQ (fetch (NOTECARDLINK DESTINATIONID) of Link)
			 (QUOTE NC00000))
		then (SETQ NewLink (create Link
						 UID ← (NC.MakeUID)
						 SourceCard ← (GETHASH (fetch (NOTECARDLINK
										    SOURCEID)
									    of Link)
									 Version2HashArray)
						 DestinationCard ← (GETHASH (fetch (NOTECARDLINK
											 
										    DESTINATIONID)
										 of Link)
									      Version2HashArray)
						 AnchorMode ← (fetch (NOTECARDLINK ANCHORMODE)
								 of Link)
						 Label ← (fetch (NOTECARDLINK LINKLABEL)
							    of Link)
						 DisplayMode ← (fetch (NOTECARDLINK DISPLAYMODE)
								  of Link)))
		       (NC.CheckDisplayModeFormat NewLink)
		       (SETQ ConvertedLinks (CONS NewLink ConvertedLinks))
	      elseif (SETQ Card (GETHASH (fetch (NOTECARDLINK SOURCEID) of Link)
					       Version2HashArray))
		then 

          (* * This is the old form of NoSource. Convert to new form by putting on the prop list.)


		       [SETQ PropList (NC.FetchPropList (SETQ Card (GETHASH
								(fetch (NOTECARDLINK SOURCEID)
								   of Link)
								Version2HashArray]
		       (NC.SetPropList Card (if PropList
						  then (LISTPUT PropList (QUOTE NoSource)
								    T)
							 PropList
						else (LIST (QUOTE NoSource)
							       T]
       finally (RETURN ConvertedLinks])

(NC.ReadVersion2MainCardData
  [LAMBDA (Stream ID Card Version2HashArray FromNoteFile ToNoteFile)
                                                             (* fgh: "27-May-86 20:43")

          (* * Stream should be positioned at the main data card part of ID. Get the main data and fill in for Card.)



          (* * fgh 12/17/85 changed Apply of CollectReferencesFn to be done only if there is a CollectReferencesFn for the 
	  card type)



          (* * rht 5/7/86: Now only does the horrible kludge of smashing absolute pointers in the 1.2 file if the TEdit is 
	  judged to be formatted. We check that by looking for the TEdit password at the end of the substance.)



          (* * fgh 5/27/86 Added INTERSECTION call during conversion of links due to problems with browsers which have same 
	  link icon represented twice in the browser.)


    (LET (CardType Region StartPtr EndPtr Length TEditBasedFlg StartFormatPtr CollectReferencesFn 
		   FormattedTEditP LinkIcons)
         (NC.SetItemDate Card (NC.ReadVersion2CardPartHeader Stream ID NC.Version2ItemIdentifier))

          (* * Read card type and region)


         (NC.SetType Card (SETQ CardType (READ Stream)))
         (SETQ TEditBasedFlg (NC.TEditBasedP CardType))
         (READC Stream)
         (NC.SetRegion Card (NC.ReadVersion2Region Stream))

          (* * Read the substance pointers, compute the length, then call the substance get fn)


         (SETQ StartPtr (NC.ReadPtr Stream 3))
         (SETQ EndPtr (NC.ReadPtr Stream 3))
         (SETQ Length (DIFFERENCE EndPtr StartPtr))

          (* * Figure out whether the substance is TEdit formatted. In that case we have to smush absolute pointers.)


         (SETQ FormattedTEditP (AND TEditBasedFlg (GREATERP Length 2)
					(SETFILEPTR Stream (DIFFERENCE EndPtr 2))
					(EQ (QUOTIENT (NC.ReadPtr Stream 2)
							  100)
					      NC.TEditPasswordDividedBy100)))

          (* * A horrible kludge: Change the infamous file absolute pointer in the text stream to be file relative for 
	  duration of the GetSubstance call.)


         (if FormattedTEditP
	     then (SETFILEPTR Stream (DIFFERENCE EndPtr 8))
		    (SETQ StartFormatPtr (NC.ReadPtr Stream 4))
		    (SETFILEPTR Stream (DIFFERENCE EndPtr 8))
		    (NC.WritePtr Stream (DIFFERENCE StartFormatPtr StartPtr)
				 4))
         (SETFILEPTR Stream StartPtr)
         (NC.SetSubstance Card (NC.ApplyFn GetFn Card Length Stream -1))

          (* * Now put back the infamous file absolute pointer.)


         (if FormattedTEditP
	     then (SETFILEPTR Stream (DIFFERENCE EndPtr 8))
		    (NC.WritePtr Stream StartFormatPtr 4)
		    (SETFILEPTR Stream EndPtr))

          (* * Now convert each link in the embedded link icons in the substance.)


         (if (fetch (Card CollectLinksFn) of Card)
	     then (for LinkIcon in (INTERSECTION (SETQ LinkIcons
							   (CAR (NC.ApplyFn CollectLinksFn Card NIL 
									      T)))
							 LinkIcons)
		       eachtime (BLOCK) do (NC.ConvertVersion2LinkIcon LinkIcon Card 
									       Version2HashArray])
)
(* * changes to NCCOMPACT)

(DEFINEQ

(NC.CompactNoteFileToTarget
  [LAMBDA (FromNoteFile ToFileName InterestedWindow)         (* pmi: "13-Aug-87 18:58")

          (* * In sorted order, copy card parts to lower addresses in the file.)



          (* * fgh 5/1/86 Now returns the ToNoteFile in order to be compatible with compact in place.)



          (* * rht 11/3/86: Now opens FromNoteFile read-only. Also now takes InterestedWindow arg.)



          (* * rht 1/22/87: Slight change to computation of new index size.)



          (* * rht 3/17/87: Added RESETLST to make sure notefiles get closed in case of bombing out.)



          (* * rht 5/15/87: No longer calls NC.ComputeNewDatabaseIndexSize. Target notefile's index will be same size as 
	  source notefile's.)



          (* * pmi 5/27/87: Removed HashArray argument in calls to NC.OpenNoteFile. Added call to NC.NoticeNoteFile to notice
	  the original and target notefiles. Also stopped creation of a notefile interface for the target notefile before 
	  compaction -
	  it should be done at the end of compaction instead.)



          (* * pmi 6/24/87: Now returns NIL if can't create the target notefile.)



          (* * pmi 6/25/87: Now passes NIL for Can'tTruncateFlg in call to NC.OpenNoteFile.)



          (* * pmi 8/13/87: Removed calls to NC.NoticeNoteFile; they are now done further up in NC.CompactNoteFile.)


    (PROG (ToNoteFile OperationMsg)
	    (if (SETQ FromNoteFile
		    (NC.OpenNoteFile FromNoteFile T T T NIL NIL T T InterestedWindow NIL NIL NIL T))
		then (SETQ OperationMsg (CONCAT "Compacting " (fetch (NoteFile FullFileName)
								       of FromNoteFile)
						      (CHARACTER 13)))
		       (SETQ ToNoteFile (NC.CreateDatabaseFile ToFileName (fetch (NoteFile
											 
										    HashArraySize)
										 of FromNoteFile)
								   OperationMsg T NIL T 
								   InterestedWindow NIL NIL NIL NIL T)
			 )
		       (if (EQ ToNoteFile (QUOTE CreateCancelled))
			   then (RETURN NIL)
			 else (SETQ ToNoteFile
				  (NC.OpenNoteFile ToNoteFile T T T T T T T InterestedWindow NIL 
						     NIL NIL NIL NIL T)))
		       [RESETLST (RESETSAVE NIL (BQUOTE (NC.ForceDatabaseClose , FromNoteFile)
							      ))
				   (RESETSAVE NIL (BQUOTE (NC.ForceDatabaseClose , ToNoteFile)))
				   (LET ((OriginalStream (fetch (NoteFile Stream) of FromNoteFile)
							 )
					 (TargetStream (fetch (NoteFile Stream) of ToNoteFile))
					 FromFileLength TargetFileLength BytesRecovered)
				        (replace (NoteFile NextIndexNum) of ToNoteFile
					   with (fetch (NoteFile NextIndexNum) of FromNoteFile))
				        (SETFILEPTR TargetStream (NC.TotalIndexSize
							(fetch (NoteFile HashArraySize)
							   of ToNoteFile)))
                                                             (* truncate ToNoteFile after the index)
				        (if (NC.CopySortedCardParts (NC.SortIndexEntries 
										     FromNoteFile)
									ToNoteFile NIL NIL NIL 
									InterestedWindow OperationMsg)
					    then           (* all useable card parts got copied)
						   (SETQ FromFileLength (GETEOFPTR OriginalStream)
						     )

          (* * fool NC.PutHashArray into writing out the index for the new NoteFile)


						   (replace (NoteFile Stream) of FromNoteFile
						      with TargetStream)
						   (NCLocalDevice.PutHashArray FromNoteFile 
										 InterestedWindow T 
										 OperationMsg)
						   (replace (NoteFile Stream) of FromNoteFile
						      with OriginalStream)

          (* * Put out the new ChkptPtr to the file.)


						   (replace (NoteFile CheckptPtr) of ToNoteFile
						      with (SETQ TargetFileLength (GETEOFPTR
								 TargetStream)))

          (* * Steal the UID from the original file so links will work. Write out the header.)


						   (replace (NoteFile UID) of ToNoteFile
						      with (fetch (NoteFile UID) of 
										     FromNoteFile))
						   (NC.PutNoteFileHeader ToNoteFile)
						   (SETQ BytesRecovered (DIFFERENCE 
										   FromFileLength 
										 TargetFileLength))
						   (NC.PrintMsg NIL T (fetch (NoteFile 
										     FullFileName)
									   of FromNoteFile)
								  " compacted to "
								  (fetch (NoteFile FullFileName)
								     of ToNoteFile)
								  (CHARACTER 13)
								  "Recovered " BytesRecovered 
								  " bytes ("
								  (FIX (TIMES 100
										  (FQUOTIENT 
										   BytesRecovered 
										   FromFileLength)))
								  "%%)"
								  (CHARACTER 13))
						   (NC.ClearMsg InterestedWindow T]
		       (RETURN ToNoteFile])

(NC.GetCardPartLength
  [LAMBDA (Card FromPtr)                                     (* kirk: " 2-Jan-86 06:36")
                                                             (* Comment)
    (LET ((NoteFile (fetch (Card NoteFile) of Card)))
         (SETFILEPTR (fetch (NoteFile Stream) of NoteFile)
		       FromPtr)
         (FIXP (NC.ReadPtr (fetch (NoteFile Stream) of NoteFile)
			     3])

(NC.SortIndexEntries
  [LAMBDA (NoteFile)                                         (* kirk: " 6-Aug-86 14:13")

          (* * Using the IndexArray for Stream, return the sorted list of index entries as triples of fileptr, ID, and 
	  EntryType.)



          (* * fkr 11/8/85: Now uses notefile object and hash arrays instead of index arrays.)



          (* * kirk 8Dec85 Took out PROGN around FUNCTION returning CollectionList)



          (* * If we add any card parts must change inference of total active cards in NC.CompactNoteFile)


    (LET (CardParts)
         [NC.MapCards NoteFile (FUNCTION (LAMBDA (Card)
			  (if (EQ (fetch (Card Status) of Card)
				      (QUOTE ACTIVE))
			      then (push CardParts (create SortingRecord
								 FileLoc ← (fetch (Card MainLoc)
									      of Card)
								 Card ← Card
								 CardPartTypeNum ← 0))
				     (push CardParts (create SortingRecord
								 FileLoc ← (fetch (Card LinksLoc)
									      of Card)
								 Card ← Card
								 CardPartTypeNum ← 1))
				     (push CardParts (create SortingRecord
								 FileLoc ← (fetch (Card TitleLoc)
									      of Card)
								 Card ← Card
								 CardPartTypeNum ← 2))
				     (push CardParts (create SortingRecord
								 FileLoc ← (fetch (Card PropListLoc)
									      of Card)
								 Card ← Card
								 CardPartTypeNum ← 3]
         (SORT CardParts T])

(NC.UpdateCardLoc
  [LAMBDA (Card CardPartTypeNum ToPtr)                       (* rht: " 2-May-87 16:34")

          (* * rht 5/2/87: Now returns NIL if bad notefile.)


    (SELECTQ CardPartTypeNum
	       (0 (replace (Card MainLoc) of Card with ToPtr))
	       (1 (replace (Card LinksLoc) of Card with ToPtr))
	       (2 (replace (Card TitleLoc) of Card with ToPtr))
	       (3 (replace (Card PropListLoc) of Card with ToPtr))
	       (PROGN (FLASHW PROMPTWINDOW)
			(NC.PrintMsg NIL T "Bad NoteFile. Please Inspect and Repair." (CHARACTER
					 13))
			NIL])

(NC.CopySortedCardPart
  [LAMBDA (SortingRecord ToNoteFile InterestedWindow)        (* rht: " 1-May-87 14:46")

          (* * Copy some portion of a card; title, links, substance, proplist, to ptr in Stream and update index 
	  accordingly.)



          (* * fkr 11/8/85: No longer worries about link labels part. Also updated to hadle new CradID and NoteFileobject.)



          (* * kirk 23Nov85: restructured to reduce redundant code)



          (* * rht 1/22/87: Added InterestedWindow arg.)



          (* * rht 5/1/87: Changed mention of FromNoteFile to ToNoteFile.)


    (WITH.MONITOR (NC.FetchMonitor ToNoteFile)
		  (LET ((FromPtr (fetch (SortingRecord FileLoc) of SortingRecord))
			(Card (fetch (SortingRecord Card) of SortingRecord))
			(CardPartTypeNum (fetch (SortingRecord CardPartTypeNum) of SortingRecord))
			(ToStream (fetch (NoteFile Stream) of ToNoteFile))
			ToPtr)
		       (SETQ ToPtr (GETFILEPTR ToStream))
		       (if (NC.CopyCardPart (fetch (NoteFile Stream)
						   of (fetch (Card NoteFile) of Card))
						ToStream FromPtr ToPtr InterestedWindow)
			   then (NC.UpdateCardLoc Card CardPartTypeNum ToPtr])

(NC.CopySortedCardPartInPlace
  [LAMBDA (SortingRecord BufferStream ToPtr EOFBufferLoc InterestedWindow)
                                                             (* rht: " 2-May-87 16:36")

          (* * Copy some portion of a card; title, links, substance, proplist, to ptr in Stream and update index 
	  accordingly.)



          (* * fkr 11/8/85: No longer worries about link labels part. Also updated to hadle new CradID and NoteFileobject.)



          (* * kirk 23Nov85: added ToNoteFile parameter and restructured to reduce redundant code and to blindly COPYBYTES)



          (* * rht 1/22/87: Now properly handles case when NC.CopyCardPart returns NIL. This function no longer called under 
	  NC.ExpandIndexInPlace. Added InterestedWindow arg.)



          (* * rht 5/2/87: Now returns nil if last call to NC.UpdateCardLoc fails.)


    (LET ((FromPtr (fetch (SortingRecord FileLoc) of SortingRecord))
	  (Card (fetch (SortingRecord Card) of SortingRecord))
	  (CardPartTypeNum (fetch (SortingRecord CardPartTypeNum) of SortingRecord))
	  NoteFile)
         (if (EQUAL ToPtr FromPtr)
	     then (PLUS ToPtr (NC.GetCardPartLength Card FromPtr))
	   else (WITH.MONITOR (NC.FetchMonitor (SETQ NoteFile (fetch (Card NoteFile)
								       of Card)))
				(LET ((Stream (fetch (NoteFile Stream) of NoteFile))
				      EndPtr Length)

          (* * Copy the substance out to the {NODIRCORE} stream.)


				     (SETQ Length (NC.CopyCardPart Stream BufferStream FromPtr 0 
								       InterestedWindow))

          (* * Copy to end of file if needed for safety. That way, if we crash during second copy, all nearby card parts are 
	  still okay.)


				     (SETQ EndPtr (PLUS ToPtr Length))
				     (if (OR (GEQ FromPtr EndPtr)
						 (AND (NC.CopyCardPart BufferStream Stream 0 
									   EOFBufferLoc 
									   InterestedWindow)
							(NC.UpdateCardLoc Card CardPartTypeNum 
									    EOFBufferLoc)))
					 then 

          (* * Now copy to its proper home.)


						(AND (NC.CopyCardPart BufferStream Stream 0 ToPtr 
									  InterestedWindow)
						       (NC.UpdateCardLoc Card CardPartTypeNum ToPtr)
						       EndPtr])
)
(* * changes to NCUTILITIES)

(DEFINEQ

(NC.CoerceToNoteFileStream
  [LAMBDA (CardOrNoteFileOrStream)                           (* rht: "23-Jan-86 17:40")

          (* * Get stream from whatever it is.)


    (COND
      ((STREAMP CardOrNoteFileOrStream))
      ((type? NoteFile CardOrNoteFileOrStream)
	(fetch (NoteFile Stream) of CardOrNoteFileOrStream))
      ((type? Card CardOrNoteFileOrStream)
	(fetch (NoteFile Stream) of (fetch (Card NoteFile) of CardOrNoteFileOrStream])

(NC.CoerceToInterestedWindow
  [LAMBDA (WinOrCardOrNoteFile)                              (* rht: "25-Mar-87 18:18")

          (* * Try to return a window that can be used for NC.PrintMsg, NC.AskUser, etc. If arg is an open win, use that.
	  If displayed card, then use its window. If notefile, then use its notefile icon if open. Last hope is to use the 
	  session icon if open. Returning nil means that main prompt window will have to be used.)


    (DECLARE (GLOBALVARS NC.NoteCardsIconWindow))
    (LET (Card NoteFile)
         (COND
	   ((OPENWP WinOrCardOrNoteFile)
	     WinOrCardOrNoteFile)
	   [(AND (type? NoteFile WinOrCardOrNoteFile)
		   (OPENWP (NCP.NoteFileIconWindow WinOrCardOrNoteFile]
	   [(AND (OR (NC.CardP WinOrCardOrNoteFile)
			 (TEXTSTREAMP WinOrCardOrNoteFile))
		   (NC.CardP (SETQ Card (NC.CoerceToCard WinOrCardOrNoteFile)))
		   (OPENWP (NC.FetchWindow Card]
	   [(AND (NC.CardP Card)
		   (SETQ NoteFile (fetch (Card NoteFile) of Card))
		   (OPENWP (NCP.NoteFileIconWindow NoteFile]
	   ((OPENWP NC.NoteCardsIconWindow))
	   (T NIL])
)
(* * changes to NCINTERFACE)

(DEFINEQ

(NC.AskLinkLabel
  [LAMBDA (MainWindow MultipleFlg SystemLinksFlg NewLinkFlg CancelOkayFlg ReverseLinksFlg 
		      OldLinkLabels ReturnListOfListFlg)     (* pmi: " 1-Apr-87 12:12")
                                                             (* Asks for label on notecard links)

          (* * rht 8/2/84: Added double columns for when called by the browser, i.e. ReverseLinksFlg=T.
	  Reverse links have prefix "←".)



          (* * rht 11/19/84: Changed strings from "pointer" to "link" and from "label" to "type".)



          (* * rht 2/14/85: Added extra arg OldLinkLabels in the Multiple selection case to display previous choices.)



          (* * rht 10/11/85: Took out printing to prompt window. It's a waste of screen space.)



          (* * rht 10/22/85: Added ReturnListOfListFlg so caller can tell difference between aborting from Stylesheet and 
	  choosing NULL set of links.)



          (* * fgh 11/14/85 Updated to handle NoteFile and card objects.)



          (* * pmi 12/5/86: Modified so that clicking outside of Link type menu is equivalent to choosing **CANCEL** from 
	  menu.)



          (* * pmi 3/25/87: Added NC.MenuFont to all menus)


    (DECLARE (GLOBALVARS NC.MenuFont NC.UCASESystemLinkLabels NC.UnspecifiedLinkLabel))
    (PROG (Menu Choice Choices LabelsList LinkLabels Position Card NoteFile)
	    (SETQ Card (NC.CoerceToCard MainWindow))
	    (SETQ NoteFile (fetch (Card NoteFile) of Card))
	    (SETQ LinkLabels (NC.RetrieveLinkLabels NoteFile SystemLinksFlg))
	    [SETQ Position (AND (WINDOWP MainWindow)
				    (create POSITION
					      XCOORD ← (fetch (REGION LEFT)
							  of (WINDOWPROP MainWindow (QUOTE
									       REGION)))
					      YCOORD ← (fetch (REGION TOP) of (WINDOWREGION
										    MainWindow]
	    [COND
	      (MultipleFlg [SETQ Choices
			     (STYLESHEET (CREATE.STYLE
					     (QUOTE ITEMS)
					     [COND
					       [ReverseLinksFlg
						 (LIST (create MENU
								   ITEMS ← LinkLabels)
							 (create MENU
								   ITEMS ←
								   (for Link in LinkLabels
								      collect (PACK*
										  (QUOTE ←)
										  Link]
					       (T (LIST (create MENU
								    ITEMS ← LinkLabels]
					     (QUOTE NEED.NOT.FILL.IN)
					     (QUOTE MULTI)
					     (QUOTE POSITION)
					     Position
					     (QUOTE TITLE)
					     "Link Types?"
					     (QUOTE SELECTIONS)
					     (LIST (for Label in OldLinkLabels
							when (NEQ (NTHCHAR Label 1)
								      (QUOTE ←))
							collect Label)
						     (for Label in OldLinkLabels
							when (EQ (NTHCHAR Label 1)
								     (QUOTE ←))
							collect Label]
			   (RETURN (COND
				       ((NULL Choices)     (* User aborted from stylesheet.)
					 NIL)
				       [(AND ReverseLinksFlg ReturnListOfListFlg)
					 (LIST (NCONC (CAR Choices)
							  (CADR Choices]
				       (ReverseLinksFlg (NCONC (CAR Choices)
								 (CADR Choices)))
				       (ReturnListOfListFlg Choices)
				       (T (CAR Choices]
	    (SETQ Menu (create MENU
				   TITLE ← " Link Type "
				   ITEMS ← [NCONC (COND
						      [ReverseLinksFlg (for Link in LinkLabels
									  join (LIST
										   Link
										   (CONCAT "←" Link]
						      (T (COPY LinkLabels)))
						    (AND NewLinkFlg (LIST (QUOTE 
									      --New% Link% Type--)))
						    (AND CancelOkayFlg (LIST (QUOTE **CANCEL**]
				   CENTERFLG ← T
				   MENUPOSITION ← Position
				   MENUCOLUMNS ← (AND ReverseLinksFlg 2)
				   MENUFONT ← NC.MenuFont
				   ITEMHEIGHT ← (IPLUS (FONTPROP NC.MenuFont (QUOTE HEIGHT))
							 1)))

          (* * Allow user to cancel by selecting outside of Links menu)


	    (SETQ Choice (OR (MKATOM (MENU Menu))
				 (QUOTE **CANCEL**)))
	    [COND
	      ((EQ Choice (QUOTE **CANCEL**))
		(SETQ Choice))
	      ((EQ Choice (QUOTE --New% Link% Type--))
		(NC.ClearMsg MainWindow NIL)
		(until (COND
			   ((NOT (FMEMB [U-CASE (SETQ Choice
							(MKATOM (NC.AskUser 
									  "Enter new link type: "
										NIL NIL NIL 
										MainWindow NIL]
					    NC.UCASESystemLinkLabels))
			     T)
			   (T (NC.PrintMsg MainWindow T Choice " is a system reserved link type."
					     (CHARACTER 13)
					     "Please choose another link type."
					     (CHARACTER 13))
			      NIL)))
		(OR Choice (SETQ Choice NC.UnspecifiedLinkLabel))
		(AND (NOT (FMEMB Choice LinkLabels))
		       (NC.StoreLinkLabels NoteFile (CONS Choice LinkLabels]
	    (RETURN Choice])

(NC.SelectNoteCards
  [LAMBDA (SingleCardFlg SelectionPredicate Menu InstigatingCardOrWindow Msg CheckForCancelFlg 
			 FileLevelLockFlg)                   (* Randy.Gobbel "12-Aug-87 16:18")

          (* Select a set of note cards or a single note card, depending on SingleCardFlg. Works by interpreting all mouse 
	  presses until a card has been chosen (if SingleCardFlg is T) or until the Done button has been pressed 
	  (if SingleCardFlg is NIL). If the mouse press occus within a Title bar of a notecard, add that note card to the 
	  selected list. Otherwise, if you are pointing into a note card, call the BUTTONEVENTFN for that note card.
	  The Selection in Progress flag has been set, so all note card BUTTONEVENTFNs should know to ignore all presses 
	  except those that occur on link icons. Link icon presses should simply add the desination of that link to the 
	  selected note cards list. This function should always be called from inside of an NC.CardSelectionOperation 
	  wrapper.)



          (* * rht 8/1/84: Changed second RESETSAVE call to give NC.ClearMsg a NIL argument.)



          (* * rht 1/9/85: Fixed so now prints name of selected item even it's a link.)



          (* * rht 2/15/85: Now can backspace over last selection chosen. Added new arg Msg so that when we reprint the list,
	  we can reprint the message as well.)



          (* * rht 3/23/85: Added the CheckForCancelFlg arg, which if non-nil causes Cancel to be handled differently then 
	  Done after no selections. Namely, Cancel will return the atom CANCELLED whereas Done with no selections returns 
	  NIL. If CheckForCancelFlg is NIL then NIL is returned in both cases.)



          (* * fgh 11/14/85 Updated to handle Card and NoteFile objects.)



          (* * rht 11/18/85: Fixed so able to select when InstigatingNoteFile is NIL.)



          (* * fgh 12/20/85 Totally rewritten for 1.3 selection mechanism. Based on COPYINSERT now rather than on takingf 
	  over the mouse process.)



          (* * fgh 1/15/86 Added call to SPAWN.MOUSE in case this is called under the mouse process)



          (* * kirk 25Apr86 Changed to use SessionIcon (NC.NoteCardsIconWindow) rather than PROMPTWINDOW if no Instigating 
	  window is supplied.)



          (* * fgh 7/5/86 Added code to put CRs into printout of selected cards in order to keep prompt window from getting 
	  infinitely wide to accomdate the printout.)



          (* * rht 10/5/86: Now allows choice of cards from remote notefile.)



          (* * rht 10/18/86: Give TTY process to process that originally had it if possible.)



          (* * rht & pmi 11/14/86: Now checks for valid card before testing SelectionPredicate.)



          (* * pmi 12/5/86 Modified prompt messages to mention SHIFT-selection.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument.)



          (* * rg 3/18/87 reworked for NC.CardSelectionOperation: added NAMED-RESETSAVE forms for Card locking.)



          (* * 3/23/87: Changed to call REMOVEWINDOW instead of DETACHWINDOW before deleting the attached menu.
	  Also changed so that menu is attached to InstigatingWindow rather than to PromptWindow. This makes it possible for 
	  windows to "slide down" when selection ends.)



          (* * rht 3/24/87: Now calls NC.CoerceToInterestedWindow)



          (* * RG 4/1/87 changed CANCELLED to DON'T)



          (* * rg 4/22/87 changed some names,)



          (* * rht&rg&pmi 4/22/87: Moved location of ALLOW.BUTTON.EVENTS.)



          (* * rg 6/2/87 added FileLevelLockFlg)



          (* * rht 6/6/87: If user selects a cross-file link card, then try to follow it.)


    (DECLARE (USEDFREE CardListResetVar))

          (* * if we are running under the mouse process, start up a new mouse process)


    (ALLOW.BUTTON.EVENTS)
    (LET (Window Card ButtonEventFn InstigatingWindow InstigatingCard InstigatingNoteFile MenuWindow 
		 PromptWindow CopyInsertEvent CardProcessedEvent SelectedCards BinLoopProcess 
		 OldTTYProcess OpInProgress ResetItems TTYResetVar InternalResetVar)
         (NAMED-RESETLST
	   InternalResetVar
	   (OR SelectionPredicate (SETQ SelectionPredicate (FUNCTION TRUE)))
	   (SETQ PromptWindow (OR (NC.AttachPromptWindow (SETQ InstigatingWindow
								 (NC.CoerceToInterestedWindow
								   InstigatingCardOrWindow)))
				      PROMPTWINDOW))
	   (SETQ InstigatingCard (NC.CoerceToCard InstigatingCardOrWindow))
	   (SETQ InstigatingNoteFile (AND InstigatingCard (fetch (Card NoteFile) of 
										  InstigatingCard)))
	   (NC.PrintMsg InstigatingWindow T (COND
			    (Msg (CONCAT Msg (CHARACTER 13)))
			    (T ""))
			  "Items shift-selected:  ")
	   (SETQ OldTTYProcess (TTY.PROCESS))

          (* * Set up the prompt window for proper use by the CopyInsertFn)


	   (NAMED-RESETSAVE InternalResetVar (WINDOWPROP PromptWindow (QUOTE SelectCardsMonitor)
							     (CREATE.MONITORLOCK (QUOTE 
										      SelectCards)))
			      (BQUOTE (WINDOWPROP , PromptWindow SelectCardsMonitor NIL)))
	   [WINDOWPROP PromptWindow (QUOTE CopyInsertEvent)
			 (SETQ CopyInsertEvent (CREATE.EVENT (QUOTE CopyInsertEvent]
	   (WINDOWPROP PromptWindow (QUOTE NewCardsProcessed)
			 T)
	   [WINDOWPROP PromptWindow (QUOTE CardProcessedEvent)
			 (SETQ CardProcessedEvent (CREATE.EVENT (QUOTE CardProcessedEvent]
	   (WINDOWPROP PromptWindow (QUOTE SelectNoteCardsProcess)
			 (THIS.PROCESS))
	   (WINDOWPROP PromptWindow (QUOTE COPYINSERTFN)
			 (FUNCTION NC.SelectNoteCardsCopyInsertFn))
	   (NAMED-RESETSAVE InternalResetVar (WINDOWPROP PromptWindow (QUOTE SelectedCards)
							     NIL)
			      (BQUOTE (WINDOWPROP , PromptWindow (QUOTE SelectedCards)
						      NIL)))
	   (NAMED-RESETSAVE InternalResetVar (WINDOWPROP PromptWindow (QUOTE SelectingCards)
							     T)
			      (BQUOTE (WINDOWPROP , PromptWindow SelectingCards NIL)))

          (* * make sure ↑E aborts properly)


	   (NAMED-RESETSAVE InternalResetVar (RESET.INTERRUPTS (LISPINTERRUPTS)
								   T))

          (* * Make the process behind the prompt window including control for a blinking cursor)


	   [WINDOWPROP PromptWindow (QUOTE PROCESS)
			 (SETQ BinLoopProcess (ADD.PROCESS
			     (QUOTE (PROG NIL (BLOCK)
					      (TTYDISPLAYSTREAM (PROCESSPROP (THIS.PROCESS)
										 (QUOTE WINDOW)))
					      XXXX
					      (BIN)
					      (BLOCK)
					      (GO XXXX)))
			     (QUOTE WINDOW)
			     PromptWindow
			     (QUOTE NAME)
			     (QUOTE BinLoopProcess)
			     (QUOTE TTYENTRYFN)
			     (FUNCTION [LAMBDA (Process)
				 (PROCESSPROP Process (QUOTE OldCaret)
						(CARET CROSSHAIRS))
				 (ECHOMODE])
			     (QUOTE TTYEXITFN)
			     (FUNCTION (LAMBDA (Process)
				 (CARET (PROCESSPROP Process (QUOTE OldCaret)))
				 (ECHOMODE T]
	   (NAMED-RESETSAVE InternalResetVar NIL (BQUOTE (DEL.PROCESS , BinLoopProcess)))

          (* * Insure the prompt window is cleared on the way out)


	   [NAMED-RESETSAVE InternalResetVar NIL
			      (BQUOTE (PROGN (AND (HASTTYWINDOWP , BinLoopProcess)
							(TTY.PROCESS (if (AND (PROCESSP
										      , OldTTYProcess)
										    (HASTTYWINDOWP
										      , OldTTYProcess)
										    )
									   then , OldTTYProcess
									 else T)))
						 (NC.ClearMsg , InstigatingWindow T]
	   (WINDOWADDPROP PromptWindow (QUOTE CLOSEFN)
			    (FUNCTION NC.ZapBinLoopProcess))

          (* * Set up the menu above the prompt window)

                                                             (* fix in case MENUPOSITION is set incorrectly in menu
							     passed down)
	   (replace (MENU MENUPOSITION) of Menu
	      with (CONSTANT (create POSITION
					   XCOORD ← 0
					   YCOORD ← 0)))
	   [NAMED-RESETSAVE InternalResetVar (PROGN (ATTACHMENU
							  Menu
							  (OR InstigatingWindow PROMPTWINDOW)
							  (if InstigatingWindow
							      then (QUOTE TOP)
							    else (QUOTE BOTTOM))
							  (if (AND (WINDOWP InstigatingWindow)
								       (WINDOWP PromptWindow))
							      then (CDR (WINDOWPROP
									      PromptWindow
									      (QUOTE WHEREATTACHED))
									    )
							    else (QUOTE LEFT)))
							(WINDOWPROP (WFROMMENU Menu)
								      (QUOTE SelectionPromptWindow)
								      PromptWindow))
			      (BQUOTE (PROGN (REMOVEWINDOW (WFROMMENU , Menu]

          (* * If there is an instigating window, make sure it and all its attachments are visible on the screen.)


	   (if InstigatingWindow
	       then (NC.MoveWindowOntoScreen InstigatingWindow))

          (* * Give the prompt window the tty process)


	   (TTY.PROCESS (WINDOWPROP PromptWindow (QUOTE PROCESS)))

          (* * Loop as long as necessary)


	   [WITH.MONITOR
	     (WINDOWPROP PromptWindow (QUOTE SelectCardsMonitor))
	     (until (OR (EQ SelectedCards (QUOTE DON'T))
			    (AND SingleCardFlg SelectedCards)
			    (EQ (CAR SelectedCards)
				  (QUOTE DONE)))
		do
		 (                                           (* Wait for the user to respond by copy inserting 
							     something into the prompt window)
		  (until [OR (NOT (PROCESSP BinLoopProcess))
				 (NOT (EQ SelectedCards (WINDOWPROP PromptWindow (QUOTE
									    SelectedCards]
		     do (MONITOR.AWAIT.EVENT (WINDOWPROP PromptWindow (QUOTE 
									       SelectCardsMonitor))
						 CopyInsertEvent 1000))
                                                             (* Get the latest selection list)
		  (SETQ SelectedCards (WINDOWPROP PromptWindow (QUOTE SelectedCards)))
		  (WINDOWPROP PromptWindow (QUOTE NewCardsProcessed)
				T)
		  (NOTIFY.EVENT CardProcessedEvent T)
		  (OR (PROCESSP BinLoopProcess)
			(SETQ SelectedCards (QUOTE DON'T)))
		  (NAMED-RESETLST
		    TTYResetVar                              (* Turn off the caret)
		    (NAMED-RESETSAVE TTYResetVar (TTY.PROCESS (THIS.PROCESS)))
                                                             (* If the last thing wasn't a done or cancel, process 
							     the new selection)
		    (SETQ Card (CAR SelectedCards))
		    (WITH.MONITOR
		      NC.LockLock
		      (COND
			((AND (NEQ Card (QUOTE DONE))
				(NEQ SelectedCards (QUOTE DON'T))
				(NEQ Card (QUOTE *New% Card*)))
                                                             (* Try to follow cross-file links.)
			  [if (AND (NC.ValidCardP Card)
				       (NC.CrossFileLinkCardP Card))
			      then (SETQ Card (NC.GetCrossFileLinkDestCard Card 
										InstigatingWindow))
				     (WINDOWPROP PromptWindow (QUOTE SelectedCards)
						   (SETQ SelectedCards (CONS Card (CDR 
										    SelectedCards]
                                                             (* Check to make sure that the selection is valid)
			  [COND
			    ((EQ Card (QUOTE *Undo% Selection*))
                                                             (* Chop off two elements from the list -
							     the indicator and the previous item.)
			      (SETQ Card (CADR SelectedCards))
			      (WINDOWPROP PromptWindow (QUOTE SelectedCards)
					    (SETQ SelectedCards (CDDR SelectedCards)))
                                                             (* now get our hands off of all the locks we've 
							     acquired for this card)
			      (if Card
				  then (NAMED-RESETUNSAVE CardListResetVar (NC.FetchUserDataProp
								Card
								(QUOTE ResetItems)))
					 (NC.SetUserDataProp Card (QUOTE ResetItems)
							       NIL))
			      (NC.ClearMsg InstigatingWindow NIL))
			    [(OR (NOT (NC.ValidCardP Card))
				   (NULL (APPLY* SelectionPredicate Card)))
                                                             (* Does this card match the slection predicate)
			      (NC.PrintMsg InstigatingWindow T "*** Invalid selection. ***"
					     (CHARACTER 13))
			      (WINDOWPROP PromptWindow (QUOTE SelectedCards)
					    (SETQ SelectedCards (CDR SelectedCards]
			    ((AND (SETQ OpInProgress (if FileLevelLockFlg
							     then (NC.NoteFileCheckOpInProgress
								      (fetch (Card NoteFile)
									 of Card))
							   else (NC.CardCheckOpInProgress Card)))
				    (NEQ OpInProgress (QUOTE US)))
			      (NC.PrintOperationInProgressMsg InstigatingWindow "Select Card" 
								OpInProgress)
			      (DISMISS 1000)
			      (WINDOWPROP PromptWindow (QUOTE SelectedCards)
					    (SETQ SelectedCards (CDR SelectedCards)))
			      (NC.ClearMsg InstigatingWindow NIL))
			    (T                               (* A valid selection.)
			       (NC.ClearMsg InstigatingWindow NIL)
			       [if FileLevelLockFlg
				   then [SETQ ResetItems
					    (LIST (NAMED-RESETSAVE
						      CardListResetVar
						      (NC.NoteFileProp (fetch (Card NoteFile)
									    of Card)
									 (QUOTE OperationInProgress)
									 "Select Card")
						      (BQUOTE (NC.NoteFileProp
								  ,
								  (fetch (Card NoteFile)
								     of Card)
								  OperationInProgress NIL)))
						    (NAMED-RESETSAVE
						      CardListResetVar
						      (NC.NoteFileProp (fetch (Card NoteFile)
									    of Card)
									 (QUOTE ProcessInProgress)
									 (THIS.PROCESS))
						      (BQUOTE (NC.NoteFileProp
								  ,
								  (fetch (Card NoteFile)
								     of Card)
								  ProcessInProgress NIL)))
						    (NAMED-RESETSAVE CardListResetVar
								       (SETQ NC.NoteFileBusyList
									 (CONS (THIS.PROCESS)
										 NC.NoteFileBusyList))
								       (QUOTE (SETQ
										  NC.NoteFileBusyList
										  (DREMOVE
										    (THIS.PROCESS)
										    
									      NC.NoteFileBusyList]
				 else (SETQ ResetItems
					  (LIST [NAMED-RESETSAVE CardListResetVar
								     (SETQ NC.CardBusyList
								       (CONS (THIS.PROCESS)
									       NC.CardBusyList))
								     (QUOTE (SETQ
										NC.CardBusyList
										(DREMOVE (
										     THIS.PROCESS)
											   
										  NC.CardBusyList]
						  [NAMED-RESETSAVE
						    CardListResetVar
						    [NC.NoteFileProp
						      (fetch (Card NoteFile) of Card)
						      (QUOTE CardProcessInProgressList)
						      (CONS (THIS.PROCESS)
							      (NC.NoteFileProp (fetch
										   (Card NoteFile)
										    of Card)
										 (QUOTE 
									CardProcessInProgressList]
						    (BQUOTE (NC.ResetCardProcessInProgress
								,
								(fetch (Card NoteFile)
								   of Card]
						  (NAMED-RESETSAVE CardListResetVar
								     (NC.SetUserDataProp
								       Card
								       (QUOTE OperationInProgress)
								       "Select Card")
								     (BQUOTE (NC.SetUserDataProp
										 , Card 
									      OperationInProgress NIL)
									       ))
						  (NAMED-RESETSAVE CardListResetVar
								     (NC.SetUserDataProp
								       Card
								       (QUOTE ProcessInProgress)
								       (THIS.PROCESS))
								     (BQUOTE (NC.SetUserDataProp
										 , Card 
										ProcessInProgress NIL]
			       (NAMED-RESETSAVE InternalResetVar (NC.SetUserDataProp
						    Card
						    (QUOTE ResetItems)
						    ResetItems)
						  (BQUOTE (NC.SetUserDataProp , Card ResetItems 
										  NIL]

          (* * Print the results in the prompt window)


			  (NC.PrintMsg InstigatingWindow NIL (COND
					   (Msg (CONCAT Msg (CHARACTER 13)))
					   (T ""))
					 "Items selected:  ")
			  (for ThisCard in (REVERSE SelectedCards)
			     do (NC.PrintMsg InstigatingWindow NIL (NC.RetrieveTitle ThisCard)
						 ",  ")
				  (if [AND InstigatingWindow (GREATERP
						 (DSPXPOSITION NIL PromptWindow)
						 (TIMES 1.25 (WINDOWPROP InstigatingWindow
									     (QUOTE WIDTH]
				      then (NC.PrintMsg InstigatingWindow NIL (CHARACTER 13]

          (* * Return the result)


	   (PROG1 [COND
		      ((EQ SelectedCards (QUOTE DON'T))
			(COND
			  (CheckForCancelFlg (QUOTE DON'T))
			  (T NIL)))
		      (SingleCardFlg (if (EQ (CAR SelectedCards)
						 (QUOTE DONE))
					 then NIL
				       else (CAR SelectedCards)))
		      (T (if (EQ (CAR SelectedCards)
				     (QUOTE DONE))
			     then (DREVERSE (CDR SelectedCards))
			   else (DREVERSE SelectedCards]
		    (WINDOWPROP PromptWindow (QUOTE SelectedCards)
				  NIL])

(NC.AttachNoteFileName
  [LAMBDA (CardWindow OffFlg)                                (* rht: "25-Mar-87 14:46")

          (* * Attach an indicator of the NoteFile for this Card to the Card)



          (* * fgh 5/29/86 Changed collection of old attached windows to prevent NILs in collection result.)



          (* * fgh 6/13/86 Put detachment and reattachment of previous attached windows into a RESETLST.
	  Added FREEATTACHEDWINDOW as the CLOSEFN of the indicator window. Added code to reset PASSTOMAINWINDOW COMS of the 
	  previously attachwed windows. Changed MINSIZE of indicator window to allow small fonts. Added a REPAINTFN to the 
	  indicator window.)



          (* * fgh 7/2/86 Replaced the CLEARW call in the indicator window REPAINTFN with a DSPRESET for two reasons: reset 
	  the X coor befre printining and CLEARW is not allowed in REPAINTFNS.)



          (* * fgh&rht 7/5/86: Changed the name "FileName" to "NameToPrint".)



          (* * rht 3/20/87: Moved Frank's hack that temporarily detaches windows into a macro called 
	  NC.WithWindowsUnattached.)



          (* * rht 3/25/87: Now calls NC.NoteFileIndicatorWinHeight.)


    (LET ((Card (NC.CardFromWindow CardWindow))
	  AttachedWindows FileName Window)
         (if (NC.CardP Card)
	     then (SETQ AttachedWindows (ATTACHEDWINDOWS CardWindow))
		    (if OffFlg
			then [CLOSEW (for window in AttachedWindows
					    thereis (WINDOWPROP window (QUOTE NoteFileIndicator]
			       (REPOSITIONATTACHEDWINDOWS CardWindow)
		      else (TOTOPW CardWindow)
			     (if [SETQ Window (for window in AttachedWindows
						     thereis (WINDOWPROP window (QUOTE 
										NoteFileIndicator]
				 then 

          (* * There already is an indicator window, open and redisplay it.)


					(OR (OPENWP Window)
					      (OPENW Window))
					(REDISPLAYW Window)
			       else 

          (* * No existing indicator window, make one.)


				      (NC.WithTopWindowsUnattached
					CardWindow

          (* * Make the indicator window.)


					(LET (NoteFile NameToPrint YSize IndicatorWindow)
					     (SETQ NoteFile (fetch (Card NoteFile) of Card))
					     (SETQ NameToPrint (NC.MakeNoteFileNameIndicator
						 NoteFile))
					     (SETQ YSize (NC.NoteFileIndicatorWinHeight))
					     (SETQ IndicatorWindow
					       (CREATEW (CREATEREGION 0 0 100 YSize)
							  NIL T))
					     (WINDOWPROP IndicatorWindow (QUOTE MAXSIZE)
							   (CONS 1000 YSize))
					     (WINDOWPROP IndicatorWindow (QUOTE MINSIZE)
							   (CONS 20 YSize))
					     (ATTACHWINDOW IndicatorWindow CardWindow (QUOTE
							       TOP)
							     (QUOTE JUSTIFY)
							     (QUOTE LOCALCLOSE))
					     [WINDOWPROP IndicatorWindow (QUOTE BUTTONEVENTFN)
							   (FUNCTION (LAMBDA (window)
							       (INVERTW window)
							       [NC.SetUpNoteFileInterface
								 (fetch (Card NoteFile)
								    of (NC.CardFromWindow
									   (MAINWINDOW window]
							       (INVERTW window]
					     (WINDOWPROP IndicatorWindow (QUOTE NameToPrint)
							   NameToPrint)
					     (WINDOWADDPROP IndicatorWindow (QUOTE CLOSEFN)
							      (FUNCTION FREEATTACHEDWINDOW)
							      T)
					     [WINDOWPROP IndicatorWindow (QUOTE REPAINTFN)
							   (FUNCTION (LAMBDA (Window Region)
							       (DSPRESET Window)
							       (PRIN1 (WINDOWPROP Window
										      (QUOTE 
										      NameToPrint))
									Window]
					     (DSPFONT NC.NoteFileIndicatorFont IndicatorWindow)
					     (PRIN1 NameToPrint IndicatorWindow)
					     (OPENW IndicatorWindow)
					     (WINDOWPROP IndicatorWindow (QUOTE NoteFileIndicator)
							   (QUOTE Showing])

(NC.CardImageObjP
  [LAMBDA (ImageObj)                                         (* fgh: "19-Dec-85 23:34")
    (type? Card (IMAGEOBJPROP ImageObj (QUOTE OBJECTDATUM])

(NC.CopyStructure
  [LAMBDA (RootCards DestinationFileBox TraversalSpecs InterestedWindow QuietFlg)
                                                             (* Randy.Gobbel " 3-Jun-87 10:15")

          (* * Copy a NoteCard structure into a filebox)



          (* * kirk 13/7/86: Placed TraversalSpecs after RootCards selection and changed prompt message)



          (* * rht 9/2/86: Threw away CheckFlg arg. Wasn't being used. Changed to call NCP.CollectCards instead of outdated 
	  NC.CollectCards. Changed arg named ToPosition to DestinationFileBox. Also changed FromCard to RootCard.
	  Passes two link types to NC.AskTraversalSpecs.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 3/9/87: Now accepts multiple root cards.)



          (* * rg 3/9/87 added NC.ProtectedSessionOperation wrapper)



          (* * RG 3/18/87 changed NC.ProtectedSessionOperation to NCP.WithLockedCards ; added NC.IfAllCardsFree wrapper)



          (* * rht&rg&pmi 4/22/87: Removed calls to ERROR!)



          (* * rg 6/2/87 added check for DON'T to selection of dest filebox)


    (DECLARE (GLOBALVARS NC.SelectingCardsMenu NC.SelectingCardMenu))
    (NCP.WithLockedCards (SETQ RootCards (MKLIST RootCards))
			 (NC.IfAllCardsFree
			   (NC.LockListOfCards RootCards "Copy Structure")
			   (if [AND (OR RootCards (SETQ RootCards
						(NC.SelectNoteCards NIL NIL NC.SelectingCardsMenu 
								      NIL 
						   "Shift-select the root cards of the structure")))
					[OR TraversalSpecs (SETQ TraversalSpecs
						(NC.AskTraversalSpecs (fetch (Card NoteFile)
									   of (CAR RootCards))
									(QUOTE (SubBox FiledCard]
					(OR DestinationFileBox
					      (NEQ (SETQ DestinationFileBox
						       (NC.SelectNoteCards T
									     (FUNCTION [LAMBDA (
										   Card)
										 (NC.FileBoxP
										   Card T])
									     NC.SelectingCardMenu NIL 
					     "Shift-select the FileBox to contain the structure."
									     T))
						     (QUOTE DON'T]
			       then (NC.CopyCards (NCP.CollectCards RootCards
									  (fetch (TRAVERSALSPECS
										     LinkTypes)
									     of TraversalSpecs)
									  (fetch (TRAVERSALSPECS
										     Depth)
									     of TraversalSpecs))
						      DestinationFileBox RootCards QuietFlg 
						      InterestedWindow])

(NC.CloseStructure
  [LAMBDA (RootCards TraversalSpecs InterestedWindow QuietFlg)
                                                             (* Randy.Gobbel " 2-Apr-87 15:38")

          (* * rht 9/2/86: Replaced call to outdated NC.CollectCards with NCP.CollectCards. Threw away useless NoCheckFlg and
	  Don'tClearFlg args.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 3/9/87: Now accepts multiple root cards.)



          (* * rg 3/9/87 added NC.ProtectedSessionOperation wrapper)



          (* * rg 4/1/87 changes NC.ProtectedSessionOperation to NCP.WithLockedCards ; added NC.IfAllCardsFree wrapper)


    (NCP.WithLockedCards (SETQ RootCards (MKLIST RootCards))
			 (NC.IfAllCardsFree (NC.LockListOfCards RootCards "Close Structure")
					    (OR RootCards (SETQ RootCards
						    (NC.SelectNoteCards NIL NIL 
									  NC.SelectingCardsMenu NIL 
						   "Shift-select the root cards of the structure"))
						  (ERROR!))
					    [OR TraversalSpecs (SETQ TraversalSpecs
						    (NC.AskTraversalSpecs (fetch (Card NoteFile)
									       of (CAR RootCards))
									    (QUOTE (SubBox 
											FiledCard]
					    (if (AND RootCards TraversalSpecs)
						then (OR QuietFlg (NC.PrintMsg InterestedWindow 
										     T 
								  "Collecting cards to close ..."))
						       (NC.CloseNoteCards
							 (NCP.CollectCards RootCards
									     (fetch (TRAVERSALSPECS
											LinkTypes)
										of TraversalSpecs)
									     (fetch (TRAVERSALSPECS
											Depth)
										of TraversalSpecs))
							 NIL NIL InterestedWindow)
						       (OR QuietFlg (NC.ClearMsg InterestedWindow 
										     T))
						       RootCards])

(NC.DeleteStructure
  [LAMBDA (RootCards TraversalSpecs InterestedWindow QuietFlg Don'tPutToBeDeletedCardsFlg)
                                                             (* Randy.Gobbel " 2-Apr-87 15:38")

          (* * rht 8/29/86: Reorganized and changed to call NCP.CollectCards which is more efficient than the old 
	  NCP.ComputeTransitiveClosure. Also now takes QuietFlg and Don'tPutToBeDeletedCardsFlg args.
	  Threw away Don'tClearFlg.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rht 3/9/87: Now accepts multiple root cards.)



          (* * rg 3/9/87 added NC.ProtectedSessionOperation wrapper)



          (* * rg 4/2/87 turned NC.ProtectedSessionOperation into NC.CardSelectionOperation)


    (NCP.WithLockedCards (SETQ RootCards (MKLIST RootCards))
			 (NC.IfAllCardsFree (NC.LockListOfCards RootCards "Delete Structure")
					    (OR RootCards (SETQ RootCards
						    (NC.SelectNoteCards NIL NIL 
									  NC.SelectingCardsMenu NIL 
						   "Shift-select the root cards of the structure"))
						  (ERROR!))
					    [OR TraversalSpecs (SETQ TraversalSpecs
						    (NC.AskTraversalSpecs (fetch (Card NoteFile)
									       of (CAR RootCards))
									    (QUOTE (SubBox 
											FiledCard]
					    (if (AND RootCards TraversalSpecs)
						then (OR QuietFlg (NC.PrintMsg InterestedWindow 
										     T 
								 "Collecting cards to delete ..."))
						       (NC.DeleteNoteCards
							 (NCP.CollectCards RootCards
									     (fetch (TRAVERSALSPECS
											LinkTypes)
										of TraversalSpecs)
									     (fetch (TRAVERSALSPECS
											Depth)
										of TraversalSpecs))
							 T NIL InterestedWindow QuietFlg NIL 
							 Don'tPutToBeDeletedCardsFlg)
						       (OR QuietFlg (NC.ClearMsg InterestedWindow 
										     T))
						       RootCards])
)
(* * changes to NCREPAIR)

(DEFINEQ

(NC.RobustGetSubstance
  [LAMBDA (Card Length Stream SubstanceVersion)              (* rht: " 8-May-87 14:20")

          (* * Try to get substance robustly. RESETVAR prevents breaks. Returns either substance or nil if unsuccessful.)



          (* * rht 12/1/85: Updated to use card and notefile format.)



          (* * fgh 2/5/86 Added call to NC.ApplyFn)



          (* * rht 3/22/86: Now passes substance version %#s and Stream to GetFn.)



          (* * rht 5/8/87: Changed to use LET rather than RESETVAR to temporarily nullify HELPFLAG value.)


    (LET ((HELPFLAG NIL))
         (NLSETQ (NC.ApplyFn GetFn Card Length Stream SubstanceVersion])

(NC.WorthlessCardP
  [LAMBDA (Card)                                             (* rht: " 8-Dec-85 16:03")

          (* * Return non-nil if card is totally worthless, i.e. is not a top level card, has no valid versions of any of its
	  parts in scavenger array, has zeroes in all the fields of the index array, and has status NIL or DELETED.)



          (* * rht 12/7/85: Modified to reflect new card and notefile object formats.)


    (LET ((NoteFile (fetch (Card NoteFile) of Card)))
         (AND (FMEMB (fetch (Card Status) of Card)
			 (QUOTE (NIL DELETED)))
		(ZEROP (fetch (Card MainLoc) of Card))
		(ZEROP (fetch (Card LinksLoc) of Card))
		(ZEROP (fetch (Card TitleLoc) of Card))
		(ZEROP (fetch (Card PropListLoc) of Card))
		(NOT (NC.UndeletableCardP Card))
		(NULL (NC.FetchScavengerMainDataInfo Card))
		(NULL (NC.FetchScavengerTitleInfo Card))
		(NULL (NC.FetchScavengerLinksInfo Card))
		(NULL (NC.FetchScavengerPropListInfo Card])

(NC.CheckIndexLocs
  [LAMBDA (Card MessageWin CheckptPtr CanModifyFlg)          (* rht: " 8-Dec-85 12:18")

          (* * Check if Card's index locs agree with the scavenger info. Also may possibly modify index locs if latest 
	  version of a card part is beyond checkpoint ptr. Return list of atoms indicating the problems we found or NIL if 
	  none.)


    (LET ((MainDataInfo (NC.FetchScavengerMainDataInfo Card))
	  (LinksInfo (NC.FetchScavengerLinksInfo Card))
	  (TitleInfo (NC.FetchScavengerTitleInfo Card))
	  (PropListInfo (NC.FetchScavengerPropListInfo Card)))
         (if CanModifyFlg
	     then (NC.CheckForLocBeyondCheckptPtr Card MainDataInfo (FUNCTION NC.SetMainLoc)
						      CheckptPtr MessageWin)
		    (NC.CheckForLocBeyondCheckptPtr Card LinksInfo (FUNCTION NC.SetLinksLoc)
						      CheckptPtr MessageWin)
		    (NC.CheckForLocBeyondCheckptPtr Card TitleInfo (FUNCTION NC.SetTitleLoc)
						      CheckptPtr MessageWin)
		    (NC.CheckForLocBeyondCheckptPtr Card PropListInfo (FUNCTION NC.SetPropListLoc)
						      CheckptPtr MessageWin))
         (LSUBST NIL NIL (LIST (NC.CheckIndexLoc Card MainDataInfo (fetch (Card MainLoc)
									    of Card)
						       (QUOTE MAINDATA)
						       CheckptPtr)
				   (NC.CheckIndexLoc Card LinksInfo (fetch (Card LinksLoc)
									 of Card)
						       (QUOTE LINKS)
						       CheckptPtr)
				   (NC.CheckIndexLoc Card TitleInfo (fetch (Card TitleLoc)
									 of Card)
						       (QUOTE TITLE)
						       CheckptPtr)
				   (NC.CheckIndexLoc Card PropListInfo (fetch (Card PropListLoc)
									    of Card)
						       (QUOTE PROPLIST)
						       CheckptPtr])

(NC.BuildTitlesInspectorMenu
  [LAMBDA (Card CardType CheckptPtr)                         (* rht: "16-Jul-86 23:18")

          (* * Make a menu containing items for each title version on Stream for Card. Menu item contains date and title.
	  There is no further detail obtainable for titles. Return cons of menu and current selection.)



          (* * rht 12/8/85: Modified to reflect new card and notefile object formats.)


    (LET ((Versions (NC.FetchScavengerTitleInfo Card))
	  (CurTitleLoc (fetch (Card TitleLoc) of Card))
	  MenuItems SelectionNum Menu)
         [SETQ MenuItems (for TitleInfo in Versions as ItemNum from 1
			      collect (LET ((Loc (CAR TitleInfo))
					      (Date (CADR TitleInfo))
					      (Title (CADDR TitleInfo))
					      Item)
					     (PROG1 (SETQ Item
							(LIST (CONCAT (if (GEQ Loc CheckptPtr)
									      then "*"
									    else "")
									  "["
									  (SUBATOM
									    Title 1
									    (MIN 10 (NCHARS
										     Title)))
									  "] "
									  (OR Date 
									      "NO DATE AVAILABLE"))
								Loc))
						      (if (EQUAL Loc CurTitleLoc)
							  then (SETQ SelectionNum ItemNum]
         (if (NULL SelectionNum)
	     then (SETQ MenuItems (CONS (LIST (QUOTE BADTITLE)
						      CurTitleLoc)
					      MenuItems))
		    (SETQ SelectionNum 1))
         (PROG1 (CONS (SETQ Menu (create MENU
						 ITEMS ← MenuItems
						 TITLE ← (CONCAT (if (EQ (NC.FetchStatus
										 Card)
									       (QUOTE DELETED))
								       then "DELETED "
								     else "")
								   CardType " | Title Versions")
						 WHENSELECTEDFN ← (FUNCTION 
						   NC.CardPartsMenusWhenSelectedFn)))
			  SelectionNum)                      (* Seems like the only way to communicate to the 
							     whenselectedfn is through menuprops.)
		  (PUTMENUPROP Menu (QUOTE VERSIONS)
				 Versions)
		  (PUTMENUPROP Menu (QUOTE INSPECTORFN)
				 (FUNCTION NC.CardTitleVersionInspector])

(NC.BuildSubstancesInspectorMenu
  [LAMBDA (Card CardType CheckptPtr CardsMenuWindow)         (* rht: " 8-Dec-85 16:35")

          (* * Make a menu containing items for each title version on Stream for Card. Menu item contains date and title.
	  There is no further detail obtainable for titles. Return cons of menu and current selection.)



          (* * rht 12/8/85: Modified to reflect new card and notefile object formats.)


    (LET ((Versions (NC.FetchScavengerMainDataInfo Card))
	  (CurMainDataLoc (fetch (Card MainLoc) of Card))
	  [BadTypeFlg (FMEMB CardType (WINDOWPROP (MAINWINDOW CardsMenuWindow)
						      (QUOTE UNKNOWNCARDTYPESLIST]
	  SelectionNum MenuItems Menu)
         [OR BadTypeFlg (SETQ MenuItems
		 (for SubstanceInfo in Versions as ItemNum from 1
		    collect (LET ((Loc (CAR SubstanceInfo))
				    (Date (CADR SubstanceInfo))
				    (Type (CADDR SubstanceInfo))
				    (SubstanceLength (CADDDR SubstanceInfo))
				    Item)
			           (PROG1 (SETQ Item (LIST (CONCAT (if (GEQ Loc 
										       CheckptPtr)
									       then "*"
									     else "")
									   "[" SubstanceLength "] "
									   (OR Date 
									      "NO DATE AVAILABLE"))
								 Loc))
					    (if (EQUAL Loc CurMainDataLoc)
						then (SETQ SelectionNum ItemNum]
         (if (NULL SelectionNum)
	     then (SETQ MenuItems (CONS (LIST (if BadTypeFlg
							  then (QUOTE UNKNOWNCARDTYPE)
							else (QUOTE BADMAINDATA))
						      CurMainDataLoc)
					      MenuItems))
		    (SETQ SelectionNum 1))
         (PROG1 (CONS (SETQ Menu (create MENU
						 ITEMS ← MenuItems
						 TITLE ← "Substance Versions"
						 WHENSELECTEDFN ← (FUNCTION 
						   NC.CardPartsMenusWhenSelectedFn)))
			  SelectionNum)                      (* Seems like the only way to communicate to the 
							     whenselectedfn is through menuprops.)
		  (PUTMENUPROP Menu (QUOTE VERSIONS)
				 Versions)
		  (PUTMENUPROP Menu (QUOTE INSPECTORFN)
				 (FUNCTION NC.CardSubstanceVersionInspector])

(NC.BuildLinksInspectorMenu
  [LAMBDA (Card CheckptPtr)                                  (* rht: " 8-Dec-85 16:37")

          (* * Make a menu containing items for each title version on Stream for Card. Menu item contains date and title.
	  There is no further detail obtainable for titles. Return cons of menu and current selection.)



          (* * rht 12/8/85: Modified to reflect new card and notefile object formats.)


    (LET ((Versions (NC.FetchScavengerLinksInfo Card))
	  (CurLinksLoc (fetch (Card LinksLoc) of Card))
	  MenuItems SelectionNum Menu)
         [SETQ MenuItems (for LinksInfo in Versions as ItemNum from 1
			      collect (LET ((Loc (CAR LinksInfo))
					      (Date (CADR LinksInfo))
					      (LinkListsLengths (CADDR LinksInfo))
					      Item)
					     (PROG1 (SETQ Item
							(LIST (CONCAT (if (GEQ Loc CheckptPtr)
									      then "*"
									    else "")
									  "["
									  (CAR LinkListsLengths)
									  "|"
									  (CADR LinkListsLengths)
									  "|"
									  (CADDR LinkListsLengths)
									  "] "
									  (OR Date 
									      "NO DATE AVAILABLE"))
								Loc))
						      (if (EQUAL Loc CurLinksLoc)
							  then (SETQ SelectionNum ItemNum]
         (if (NULL SelectionNum)
	     then (SETQ MenuItems (CONS (LIST (QUOTE BADLINKS)
						      CurLinksLoc)
					      MenuItems))
		    (SETQ SelectionNum 1))
         (PROG1 (CONS (SETQ Menu (create MENU
						 ITEMS ← MenuItems
						 TITLE ← "Links Versions"
						 WHENSELECTEDFN ← (FUNCTION 
						   NC.CardPartsMenusWhenSelectedFn)))
			  SelectionNum)                      (* Seems like the only way to communicate to the 
							     whenselectedfn is through menuprops.)
		  (PUTMENUPROP Menu (QUOTE VERSIONS)
				 Versions)
		  (PUTMENUPROP Menu (QUOTE INSPECTORFN)
				 (FUNCTION NC.CardLinksVersionInspector])

(NC.BuildPropListsInspectorMenu
  [LAMBDA (Card CheckptPtr)                                  (* rht: " 8-Dec-85 19:04")

          (* * Make a menu containing items for each title version on Stream for Card. Menu item contains date and title.
	  There is no further detail obtainable for titles. Return cons of menu and current selection.)



          (* * rht 12/8/85: Modified to reflect new card and notefile object formats.)


    (LET ((Versions (NC.FetchScavengerPropListInfo Card))
	  (CurPropListLoc (fetch (Card PropListLoc) of Card))
	  MenuItems SelectionNum Menu)
         [SETQ MenuItems (for PropListInfo in Versions as ItemNum from 1
			      collect (LET ((Loc (CAR PropListInfo))
					      (Date (CADR PropListInfo))
					      (PropListLength (CADDR PropListInfo))
					      Item)
					     (PROG1 (SETQ Item
							(LIST (CONCAT (if (GEQ Loc CheckptPtr)
									      then "*"
									    else "")
									  "[" PropListLength "] "
									  (OR Date 
									      "NO DATE AVAILABLE"))
								Loc))
						      (if (EQUAL Loc CurPropListLoc)
							  then (SETQ SelectionNum ItemNum]
         (if (NULL SelectionNum)
	     then (SETQ MenuItems (CONS (LIST (QUOTE BADPROPLIST)
						      CurPropListLoc)
					      MenuItems))
		    (SETQ SelectionNum 1))
         (PROG1 (CONS (SETQ Menu (create MENU
						 ITEMS ← MenuItems
						 TITLE ← "PropList Versions"
						 WHENSELECTEDFN ← (FUNCTION 
						   NC.CardPartsMenusWhenSelectedFn)))
			  SelectionNum)                      (* Seems like the only way to communicate to the 
							     whenselectedfn is through menuprops.)
		  (PUTMENUPROP Menu (QUOTE VERSIONS)
				 Versions)
		  (PUTMENUPROP Menu (QUOTE INSPECTORFN)
				 (FUNCTION NC.CardPropListVersionInspector])

(NC.CardSubstanceVersionInspector
  [LAMBDA (Card SubstanceInfo)                               (* rht: "26-Mar-86 12:26")

          (* * Fill in a SUBSTANCEDATA record and bring up an inspector on it.)



          (* * rht 12/8/85: Modified to reflect new card and notefile object formats.)



          (* * rht 3/22/86: Fixed to handle substance version nums. Now calls NC.ApplyFn and handles Hash card types.
	  Also changed the way text, graph, and sketch cards are handled.)


    (LET ((NoteFile (fetch (Card NoteFile) of Card))
	  Stream Type WindowTitle Sketch SketchObjDatum Length SubstanceVersionNum ListMenu 
	  TempStream StartLoc)                               (* Position file at main card data.
							     Hopefully no need to check validity of what we're 
							     reading.)
         (SETFILEPTR (SETQ Stream (fetch (NoteFile Stream) of NoteFile))
		       (CAR SubstanceInfo))
         (NC.ReadCardPartHeader Card NC.ItemIdentifier)
         [NC.SetType Card (SETQ Type (CAR (NC.RobustReadAtom Stream]
         (NC.RobustReadRegion Stream (GETEOFPTR Stream))
         (SETQ Length (NC.ReadPtr Stream 3))
         (SETQ SubstanceVersionNum (NC.ReadPtr Stream 1))
         (SETQ WindowTitle (CONCAT Type ": " (NC.ShaveTitleString (
								   NC.FetchTitleFromScavengerInfo
									  Card))
				       " | Date: "
				       (CADR SubstanceInfo)))
                                                             (* Unfortunately, can only inspect system-defined 
							     substances now.)
         (COND
	   ((NC.IsSubTypeOfP Type (QUOTE Text))          (* This is so that user edits a copy of the text and 
							     can't affect original.)
	     (COPYBYTES Stream (SETQ TempStream (OPENSTREAM (QUOTE {NODIRCORE})
								  (QUOTE BOTH)
								  (QUOTE NEW)))
			  (SETQ StartLoc (GETFILEPTR Stream))
			  (PLUS StartLoc Length))
	     (OPENTEXTSTREAM (COPYTEXTSTREAM (OPENTEXTSTREAM TempStream)
						 T)
			       (CREATEW (PROGN (NC.PrintMsg NIL T 
							   "Choose region for Text card display.")
						   (GETREGION))
					  WindowTitle)))
	   ((NC.IsSubTypeOfP Type (QUOTE Graph))
	     (SHOWGRAPH (NC.MakeExternalGraphCopy (NC.ApplyFn GetFn Card Length Stream 
								  SubstanceVersionNum))
			  (CREATEW (PROGN (NC.PrintMsg NIL T 
							  "Choose region for Graph card display.")
					      (GETREGION))
				     WindowTitle)
			  NIL NIL NIL T))
	   ((NC.IsSubTypeOfP Type (QUOTE Sketch))
	     (SETQ Sketch (NC.ApplyFn GetFn Card Length Stream SubstanceVersionNum))
	     (SKETCHW.CREATE (NC.ExternalizeLinkIconsInSketch Sketch)
			       (NC.FetchRegionViewed Card)
			       (PROGN (NC.PrintMsg NIL T "Choose region for Sketch card display.")
					(GETREGION))
			       WindowTitle
			       (NC.FetchScale Card)))
	   ((NC.IsSubTypeOfP Type (QUOTE List))
	     (SETQ ListMenu (create MENU
					ITEMS ← (NC.ApplyFn GetFn Card Length Stream 
							    SubstanceVersionNum)
					TITLE ← WindowTitle))
	     (ADDMENU ListMenu NIL (GETBOXPOSITION (fetch (MENU IMAGEWIDTH) of ListMenu)
						       (fetch (MENU IMAGEHEIGHT) of ListMenu)
						       NIL NIL NIL 
						       "Choose region for List card display.")))
	   ((NC.IsSubTypeOfP Type (QUOTE Hash))
	     (WINDOWPROP (INSPECT (NC.ApplyFn GetFn Card Length Stream SubstanceVersionNum))
			   (QUOTE TITLE)
			   WindowTitle))
	   (T (NC.PrintMsg NIL T 
	  "Sorry, can only inspect card types inheriting from Text, Graph, Sketch, List or Hash."])

(NC.CardLinksVersionInspector
  [LAMBDA (Card LinksInfo)                                   (* rht: " 8-Dec-85 16:55")

          (* * Fill in a LINKSDATA record and bring up an inspector on it.)



          (* * rht 12/8/85: Modified to reflect new card and notefile object formats.)


    (LET ((NoteFile (fetch (Card NoteFile) of Card))
	  Stream)                                            (* Position file at links lists.
							     Hopefully no need to check validity of what we're 
							     reading.)
         (SETFILEPTR (SETQ Stream (fetch (NoteFile Stream) of NoteFile))
		       (CAR LinksInfo))
         (NC.ReadCardPartHeader Card NC.LinksIdentifier)
         (INSPECT (create LINKSDATA
			      CARD ← Card
			      VERSIONDATE ← (CADR LinksInfo)
			      TOLINKS ← (CAR (NC.RobustReadLinks Stream NoteFile))
			      FROMLINKS ← (CAR (NC.RobustReadLinks Stream NoteFile))
			      GLOBALLINKS ← (CAR (NC.RobustReadLinks Stream NoteFile)))
		    (QUOTE LINKSDATA))
         (NC.PrintMsg NIL T "Inspect individual links as datatype Link."])

(NC.CardPropListVersionInspector
  [LAMBDA (Card PropListInfo)                                (* rht: " 8-Dec-85 16:59")

          (* * Fill in a PROPLISTDATA record and bring up an inspector on it.)



          (* * rht 12/8/85: Modified to reflect new card and notefile object formats.)


    (LET ((NoteFile (fetch (Card NoteFile) of Card))
	  Stream IdentifierAndVersionNum)                    (* Position file at prop list.
							     Hopefully no need to check validity of what we're 
							     reading.)
         (SETFILEPTR (SETQ Stream (fetch (NoteFile Stream) of NoteFile))
		       (CAR PropListInfo))
         (NC.ReadCardPartHeader Card NC.PropsIdentifier)
         (INSPECT (create PROPLISTDATA
			      CARD ← Card
			      VERSIONDATE ← (CADR PropListInfo)
			      PROPLIST ← (CAR (NC.RobustReadList Stream)))
		    (QUOTE PROPLISTDATA])

(NC.CheckForBadLinksAndTitlesAndPropLists
  [LAMBDA (NoteFile MessageWin BadNewsList)                  (* kirk: "23-Jan-86 21:35")

          (* * For any cards with bad links, set links to NIL if user agrees. This will only really destroy global links, 
	  since Tolinks and Fromlinks will get rebuilt by link scavenger later. Look around for bad titles and see if user 
	  wants to set them all to "Untitled" Untitled. Then check for cards with bad prop lists and reset to NIL if user 
	  wants. Set a windowprop on the MessageWin to the cards with bad links, if they got reset. Then the 2nd phase of the
	  scavenger can rebuild those cards' global links.)



          (* * rht 12/8/85: Modified to reflect new card and notefile object formats.)



          (* * kirk 23Jan86 Changed to use NC.AskYesOrNo)


    (LET (ActiveCardsWithBadNews CardsWithBadLinks CardsWithBadTitles CardsWithBadPropLists)
                                                             (* Collect active cards on the bad news list.)
         (SETQ ActiveCardsWithBadNews (for BadNews in BadNewsList bind Card
					   when (EQ (NC.FetchStatus (SETQ Card (CAR BadNews)
									    ))
							(QUOTE ACTIVE))
					   collect Card))
                                                             (* Collect active cards that still have bad links.)
         (SETQ CardsWithBadLinks (for Card in ActiveCardsWithBadNews
				      unless (SASSOC (fetch (Card LinksLoc) of Card)
							 (NC.FetchScavengerLinksInfo Card))
				      collect Card))       (* Collect active cards that still have bad titles.)
         (SETQ CardsWithBadTitles (for Card in ActiveCardsWithBadNews
				       unless (SASSOC (fetch (Card TitleLoc) of Card)
							  (NC.FetchScavengerTitleInfo Card))
				       collect Card))      (* Collect active cards that still have bad prop 
							     lists.)
         (SETQ CardsWithBadPropLists (for Card in ActiveCardsWithBadNews
					  unless (SASSOC (fetch (Card PropListLoc)
								of Card)
							     (NC.FetchScavengerPropListInfo Card))
					  collect Card))
         (if (OR CardsWithBadLinks CardsWithBadTitles CardsWithBadPropLists)
	     then                                          (* Print out the bad news.)
		    (if CardsWithBadLinks
			then (NC.PrintMsg MessageWin NIL "Cards: " CardsWithBadLinks 
				     " still have bad links.  Links rebuilder will rebuild them."
					      (CHARACTER 13)))
		    (if CardsWithBadTitles
			then (NC.PrintMsg MessageWin NIL "Cards: " CardsWithBadTitles 
				       " still have bad titles.  They will be set to 'Untitled'."
					      (CHARACTER 13)))
		    (if CardsWithBadPropLists
			then (NC.PrintMsg MessageWin NIL "Cards: " CardsWithBadPropLists 
					  " still have bad prop lists.  They will be set to NIL."
					      (CHARACTER 13)))
                                                             (* If it's okay with user, then reset links, titles 
							     and prop lists for those cards.)
		    (if (NC.AskYesOrNo "Is this okay?" NIL (QUOTE Yes)
					   NIL MessageWin (NC.AttachPromptWindow MessageWin)
					   NIL NIL)
			then (WINDOWPROP MessageWin (QUOTE CARDSWITHLINKSRESET)
					     (if CardsWithBadLinks
						 then (NC.PrintMsg MessageWin NIL 
								       "Resetting links ...")
							(for Card in CardsWithBadLinks
							   do (NC.SetToLinks Card NIL)
								(NC.SetFromLinks Card NIL)
								(NC.SetGlobalLinks Card NIL)
								(NC.PutLinks Card))
							(NC.PrintMsg MessageWin NIL "Done.")
							CardsWithBadLinks))
			       (if CardsWithBadTitles
				   then (NC.PrintMsg MessageWin NIL "Resetting titles ...")
					  (for Card in CardsWithBadTitles
					     do (NC.SetTitle Card "Untitled")
						  (NC.PutTitle Card)
						  (NC.SetTitle Card NIL))
					  (NC.PrintMsg MessageWin NIL "Done."))
			       (if CardsWithBadPropLists
				   then (NC.PrintMsg MessageWin NIL "Resetting prop lists ...")
					  (for Card in CardsWithBadPropLists
					     do (NC.SetPropList Card NIL)
						  (NC.PutPropList Card))
					  (NC.PrintMsg MessageWin NIL "Done."))
		      else (QUOTE ABORT])

(NC.UndeletableCardP
  [LAMBDA (Card)                                             (* rht: " 2-Mar-86 15:09")

          (* * Returns non-nil if this card is either a top level card or the link labels card.)



          (* * rht 3/2/86: Changed to use all special cards not just top level boxes.)


    (for SpecialCard in (NC.FetchSpecialCards (fetch (Card NoteFile) of Card))
       thereis (NC.SameCardP Card SpecialCard])
)
(* * changes to NCHASHCARD)

(DEFINEQ

(NC.RegistryCardMakeFn
  [LAMBDA (Card Title NoDisplayFlg)                          (* rht: "26-Feb-86 11:09")

          (* * Make a Registry substance.)


    (NC.ApplySupersFn MakeFn Card Title NoDisplayFlg (LIST NC.DefaultRegistryCardHashArraySize])

(NC.RegisterCardByName
  [LAMBDA (RegistryCard Name Card)                           (* rht: "26-Feb-86 15:38")

          (* * Stuff the item/val pair Name/Card into RegistryCard's hash array. Note that RegistryCard should be active when
	  this is called.)


    (PUTHASH (MKATOM Name)
	       (fetch (Card UID) of Card)
	       (NC.FetchSubstance RegistryCard))
    (NC.MarkCardDirty RegistryCard])

(NC.LookupCardByName
  [LAMBDA (RegistryCard Name)                                (* fgh: " 2-May-86 22:25")

          (* * Look up in RegistryCard's hash array the card hash'ed by key Name. Note that RegistryCard must be active when 
	  this is called.)



          (* * fgh 5/2/86 Now handles case where no match is found in registry table!)


    (LET [(UIDFound (GETHASH (MKATOM Name)
			       (NC.FetchSubstance RegistryCard]
         (if UIDFound
	     then (NC.CardFromUID UIDFound (fetch (Card NoteFile) of RegistryCard])
)
(* * changes to NCSEARCHCARD)

(DEFINEQ

(NC.MakeSearchCard
  [LAMBDA (Card Title NoDisplayFlg)                          (* rht: "25-Mar-87 17:11")

          (* Search for cards with specified characteristics and create a list card containing pointers to these cards.
	  For now search is limited to cards whose title contains a specified string.)



          (* * rht 11/8/84: Fixed some confusion between ListCardID and ID variables.)



          (* * fgh 11/17/85 Updated to handle multiple notefiles and crad objects.)



          (* * rht 4/11/86: changed to call NC.ApplySuper.)



          (* * rht 10/21/86: Now deletes card if no search string specified.)



          (* * rg 3/16/87 NC.DeleteNoteCards -> NC.DeleteNoteCard)


    (LET ((NoteFile (fetch (Card NoteFile) of Card))
	  SearchString HitCards WindowOrCard Window)
         (SPAWN.MOUSE)
         (SETQ WindowOrCard (NC.ApplySupersFn MakeFn Card (OR Title "SearchCard")
						NoDisplayFlg))
         (NC.ActivateCard Card)
         (SETQ Window (AND (WINDOWP WindowOrCard)
			       WindowOrCard))
         (SETQ SearchString (NC.AskUser "Please enter the search string: " NIL NIL T Window))
         (if (OR (EQUAL SearchString "")
		     (NOT SearchString))
	     then (NC.DeleteNoteCard Card NIL T)
		    NIL
	   else [NC.SetTitle Card (SETQ Title (OR Title (CONCAT "Cards with %"" 
									  SearchString "%" in title"]
		  (AND Window (WINDOWPROP Window (QUOTE TITLE)
					      Title))
		  (RESETLST (RESETSAVE (CURSOR WAITINGCURSOR))
			      (NC.PrintMsg Window T "Searching for cards ...")
			      (SETQ HitCards (NC.TitleSearch NoteFile SearchString))
			      (TEDIT.INSERT (NC.FetchSubstance Card)
					      (CONCAT " List compiled on: " (DATE)
							(CHARACTER 13)
							(CHARACTER 13))
					      1)
			      (for HitCard in HitCards unless (EQ HitCard Card)
				 do (NC.InsertLinkBeforeMarker Card HitCard 
								   NC.ListContentsLinkLabel NIL NIL))
			      (NC.PrintMsg Window NIL "Done!" (CHARACTER 13)))
		  (BLOCK 250)
		  (NC.ClearMsg Window T)
		  WindowOrCard])
)
(* * changes to NCDOCUMENTCARD)

(DEFINEQ

(NC.MakeDocument
  [LAMBDA (Card Title NoDisplayFlg CardIdentifier)           (* rht: " 4-Jun-87 12:14")

          (* * Called from a filebox's title bar. Makes a document by smashing all the descendant cards's text together.
	  Ask user if wants numbered section headings and titles. The former are made from FileBox titles, the latter from 
	  notecard titles. Delete embedded links at the end if the user desires.)



          (* * rht 10/22/84: Hacked to be callable from Programmer's interface.)



          (* * rht 11/17/84: Checks for cancel when choosing rootID and also when setting parameters.)



          (* * rht 8/25/85: Now dumps sketch and graph cards as well as text cards.)



          (* * rht 9/16/85: Now handles cr's around titles using para leading.)



          (* * fgh 11/178/85 Updated to handle Card and NoteFile objects.)



          (* * kirk 27Jun86 Moved NC.RetrieveTitle call so does not break when user Cancels)



          (* * rht 7/31/86: Now checks for card types having ExportSubstanceFn prop.)



          (* * kirk 8/22/86 Fix of free use of NoteFile var)



          (* * rht 10/15/86: Integrated markM's changes and fixed box numbering.)



          (* * rht 11/17/86: Now calls NC.ApplySupersFn rather than NC.MakeNoteCard.)



          (* * pmi 12/5/86: Modified message to NC.SelectNoteCards to mention SHIFT-selection.)



          (* * pmi 12/12/86: Removed obsolete ReturnLinksFlg argument in call to NC.SelectNoteCards.)



          (* * rg 3/16/87 NC.DeleteNoteCards -> NC.DeleteNoteCard)



          (* * rg 3/18/87 added NC.CardSelectionOperation wrapper. Still needs ProtectedCardOperation wrapper!)



          (* * rg 4/2/87 changed NC.CardSelectionOperation to NCP.WithLockedCards)



          (* * rht 4/17/87: No longer bugs user for confirm of delete when cancel'ing.)



          (* * rht 6/4/87: Now stashes on doc card a prop list of destination notefiles of cross-file links encountered 
	  during creation of contents.)


    (NCP.WithLockedCards (PROG (RootCard RootTitle DocWindow DocCard DocWindowOrCard DocStream 
					   HeadingsFromFileboxes TitlesFromNoteCards BuildBackLinks 
					   CopyEmbeddedLinks ExpandEmbeddedLinks InspectWin 
					   RootSubstanceType)
			         (OR NoDisplayFlg (SPAWN.MOUSE))
			         (SETQ DocWindowOrCard (NC.ApplySupersFn MakeFn Card "Document" 
									   NoDisplayFlg))
			         (if NoDisplayFlg
				     then (SETQ DocWindow NIL)
					    (SETQ DocCard DocWindowOrCard)
				   else (SETQ DocWindow DocWindowOrCard)
					  (SETQ DocCard (NC.CoerceToCard DocWindow)))
                                                             (* NC.MakeNoteCard either returned an Card or a window
							     depending on NoDisplayFlg.)
			         (SETQ RootCard (OR (NC.CoerceToCard CardIdentifier)
							(NC.SelectNoteCards T NIL 
									     NC.SelectingCardMenu 
									      DocWindow 
		  "Please shift-select the Note Card or File Box the document should start from.")))
			         (if (NOT RootCard)
				     then (NC.DeleteNoteCard Card NIL T)
					    (RETURN NIL))
			         (SETQ RootTitle (NC.RetrieveTitle RootCard))
			         (NC.SetTitle DocCard (CONCAT "Document from %"" RootTitle "%""))
			         (AND DocWindow (WINDOWPROP DocWindow (QUOTE TITLE)
								(NC.RetrieveTitle DocCard)))
			         (SETQ DocStream (NC.FetchSubstance DocCard))

          (* * Get MakeDocument parameters from user via inspector window.)


			         (if (NOT NoDisplayFlg)
				     then (SETQ InspectWin (NC.BuildMakeDocInspector DocWindow))
					    (TOTOPW InspectWin)
					    (for while (OPENWP InspectWin) do (BLOCK)))
			         (if (EQ (GETPROP (QUOTE NC.MakeDocParameters)
							(QUOTE --DONE--))
					     (QUOTE QUIT))
				     then (PUTPROP (QUOTE NC.MakeDocParameters)
						       (QUOTE --DONE--)
						       (QUOTE --CANCEL--))
					    (NC.DeleteNoteCard Card NIL T)
					    (RETURN NIL))
			         (SETQ HeadingsFromFileboxes (GETPROP (QUOTE 
									     NC.MakeDocParameters)
									  (QUOTE 
									    HeadingsFromFileboxes)))
			         (SETQ TitlesFromNoteCards (GETPROP (QUOTE NC.MakeDocParameters)
									(QUOTE TitlesFromNoteCards))
				   )
			         (SETQ BuildBackLinks (GETPROP (QUOTE NC.MakeDocParameters)
								   (QUOTE BuildBackLinks)))
			         (SETQ CopyEmbeddedLinks (GETPROP (QUOTE NC.MakeDocParameters)
								      (QUOTE CopyEmbeddedLinks)))
			         (SETQ ExpandEmbeddedLinks (GETPROP (QUOTE NC.MakeDocParameters)
									(QUOTE ExpandEmbeddedLinks))
				   )

          (* * Call recursive routine to dump filebox.)


			         (RESETLST (RESETSAVE (CURSOR WAITINGCURSOR))
					     (NC.PrintMsg DocWindow NIL 
						     "Collecting text from descendant cards ... ")

          (* * Clean up the SeenBefore markers placed on the cards and boxes just copied.)


					     [RESETSAVE NIL
							  (QUOTE (PROGN
								     (for Card
									in (NC.FetchUserDataProp
									       DocCard
									       (QUOTE SeenCards))
									do (NC.SetUserDataProp
									       Card
									       (QUOTE SeenBefore)
									       NIL))
								     (NC.SetUserDataProp
								       DocCard
								       (QUOTE SeenCards)
								       NIL]
                                                             (* Clean up the CrossFileLinkModePropList hung off the
							     Doccard.)
					     [RESETSAVE NIL (QUOTE (PROGN (NC.SetUserDataProp
										  DocCard
										  (QUOTE 
									CrossFileLinkModePropList)
										  NIL]

          (* * Unbelievably kludgy hack to get around Intermezzo TEdit bug. Just insert and delete a CR.)


					     (TEDIT.INSERT DocStream NC.CRString 1)
					     (TEDIT.DELETE DocStream 1 1)
					     (NC.SetUserDataProp DocCard (QUOTE 
									CrossFileLinkModePropList)
								   (LIST (fetch (Card NoteFile)
									      of DocCard)
									   NIL))
					     (NC.DumpCardToDoc RootCard DocCard DocStream 0 0 
								 HeadingsFromFileboxes 
								 TitlesFromNoteCards BuildBackLinks 
								 CopyEmbeddedLinks 
								 ExpandEmbeddedLinks)
					     (NC.PrintMsg DocWindow NIL "Done!"))
			         (COND
				   ((NOT NoDisplayFlg)
				     (BLOCK 250)
				     (NC.ClearMsg DocWindow T)))
			         (RETURN DocWindowOrCard])

(NC.MakeDocInspectorSelectionFn
  [LAMBDA (Property ValueFlg InspectWin)                     (* pmi: "25-Mar-87 15:05")

          (* * Called when user buttons in the make document inspector menu on the Property parameter.
	  Put up a menu of choices for new values for this parameter.)



          (* * rht 11/17/84: Now can select --CANCEL--. Notice strange way of checking for --DONE-- versus --CANCEL--.
	  This is because the Inspector package doesn't send the property name in Property arg if ValueFlg is on.
	  That bug has been reported.)



          (* * rht 10/11/85: Fixed to have a more correct interface to NC.AskLinkLabel when need to Select.)



          (* * rht 10/22/85: Now uses ChangedFlg to prevent NIL from showing up as value in inspector.)



          (* * rht 8/8/86: Changed call from NCP.GetLinkLabels to NC.RetrieveLinkLabels. Also now allows selection of value 
	  as well as property.)



          (* * pmi 3/25/87: Added NC.MenuFont to all menus)


    (DECLARE (GLOBALVARS NC.MenuFont NC.MakeDocParameters))
    (if (FMEMB Property (QUOTE (--DONE-- --CANCEL--)))
	then (DETACHWINDOW InspectWin)
	       (CLOSEW InspectWin)
	       (if ValueFlg
		   then (PUTPROP (QUOTE NC.MakeDocParameters)
				     (QUOTE --DONE--)
				     (QUOTE QUIT)))
	       NIL
      else (LET ((OldVal (GETPROP (QUOTE NC.MakeDocParameters)
				      Property))
		   [Answer (MENU (create MENU
					     ITEMS ← (CDR (FASSOC Property NC.MakeDocParameters))
					     TITLE ← "Choose New Value"
					     MENUFONT ← NC.MenuFont
					     CENTERFLG ← T
					     ITEMHEIGHT ← (IPLUS (FONTPROP NC.MenuFont
									       (QUOTE HEIGHT))
								   1]
		   Links ChangedFlg)
	          [SETQ ChangedFlg (if (EQ Answer (QUOTE Select))
					 then (LET ((CardWin (MAINWINDOW InspectWin)))
						     (SETQ Links
						       (NC.AskLinkLabel
							 CardWin T T NIL NIL NIL
							 (COND
							   ((LISTP OldVal))
							   ((EQ OldVal (QUOTE ALL))
							     (NC.RetrieveLinkLabels
							       (fetch (Card NoteFile)
								  of (NC.CoerceToCard CardWin))
							       T))
							   (T NIL))
							 T)))
						(if Links
						    then (SETQ Answer (if (CAR Links)
									    else (QUOTE NONE)))
							   (NOT (EQUAL Answer OldVal)))
				       else (AND Answer (NOT (EQUAL Answer OldVal]
	          (if ChangedFlg
		      then (PUTPROP (QUOTE NC.MakeDocParameters)
					Property Answer)
			     (INSPECTW.REDISPLAY InspectWin Property))
	          (INSPECTW.SELECTITEM InspectWin)
	      NIL])
)
(* * changes to NCHACKS)

(DEFINEQ

(NCHACKS.MakeLinkIconsInvisibleInTextCard
  [LAMBDA (Card Invisibility)                                (* rht: "18-Jul-86 21:54")

          (* * Make any link icons appearing in Card invisible or visible according to whether Invisibility is ON or OFF.)


    (if (NCP.TextBasedP Card)
	then (LET ((WasActiveFlg (NCP.CardCachedP Card))
		     TextStream)
		    (if (NOT WasActiveFlg)
			then (NCP.CacheCards Card))
		    (SETQ TextStream (NCP.CardSubstance Card))
		    (for LinkPair in (CAR (NCP.ApplyCardTypeFn CollectLinksFn Card NIL T T))
		       do (NCHACKS.MakeTEditCharInvisible TextStream (CDR LinkPair)
							      Invisibility))
		    (if (NOT WasActiveFlg)
			then (NCP.UncacheCards Card])

(NCHACKS.MakeLinkIconForLinkInvisible
  [LAMBDA (Link Invisibility)                                (* rht: "18-Jul-86 21:54")

          (* * Make any link icons appearing in Card invisible or visible according to whether Invisibility is ON or OFF.)


    (LET ((Card (NCP.LinkSource Link)))
         (if (NCP.TextBasedP Card)
	     then (LET ((WasActiveFlg (NCP.CardCachedP Card))
			  TextStream)
		         (if (NOT WasActiveFlg)
			     then (NCP.CacheCards Card))
		         (SETQ TextStream (NCP.CardSubstance Card))
		         (for LinkPair in (CAR (NCP.ApplyCardTypeFn CollectLinksFn Card NIL NIL 
									  T))
			    when (NC.SameLinkP Link (CAR LinkPair)) do (
								   NCHACKS.MakeTEditCharInvisible
										 TextStream
										 (CDR LinkPair)
										 Invisibility))
		         (if (NOT WasActiveFlg)
			     then (NCP.UncacheCards Card])
)
(* * changes to NOTECARDS)

(DEFINEQ

(NC.PostGreet
  [LAMBDA NIL                                                (* Randy.Gobbel " 2-Sep-87 14:03")

          (* * called when loading NOTECARDS and after each greet (for NOTECARDS sysout users) Note this means you cannot put
	  anything in here that should not be called twice!)



          (* * kirk 10Jul86 added load of NCPOSTRELEASEPATCHES)



          (* * kirk 10Aug86 set quietflg in call on NC.CardTypeLoader)



          (* * fgh 8/27/86 Changed call to NC.AddCardTypeStub to NC.CardTypeStubLoader to go along with changes to 
	  AddCardTypeStub)



          (* * rg 10/29/86 Added calls to NC.FixFileDates after all LOAD calls)



          (* * rg 12/11/86 Changed LOADFROM of source to LOADVARS of coms)



          (* * RG 3/20/87 moved load of POSTRELEASEPATCHES after load of default card types)



          (* * rg 4/24/87 added load of LISPUSERS packages using NC.LoadFileFromDirectories ; also moved call to 
	  START-TEDIT-KILLER here)



          (* * rg 7/10/87 zapped lotsa cruft about file loading, in conjunction with complete rework of all that stuff)



          (* * rg 9/2/87 added (NC.FixFileDates NC.LoadedFiles))


    (DECLARE (GLOBALVARS NC.CardTypes NC.CoreFiles NC.LoadedFiles NOTECARDTYPES NOTECARDTYPESTUBS 
			     NOTECARDSLIBRARYFILES NOTECARDSLISPUSERSFILES NCINITIALGLOBALPARAMS))
    [LET (FullFileName TypeName Type File)
         (NC.FixFileDates NC.LoadedFiles)
         (for TypeName in NOTECARDTYPES unless (AND (SETQ Type (GETHASH TypeName 
										    NC.CardTypes))
							    (NOT (fetch (NoteCardType StubFlg)
								      of Type)))
	    do (NC.CardTypeLoader TypeName NIL T))

          (* * in case new patches have been made since the sysout was made or the last greet)


         (COND
	   ((SETQ FullFileName (NC.FindFile (QUOTE POSTRELEASEPATCHES)))
	     (NC.LoadFileFromDirectories FullFileName)))
         (for TypeName in NOTECARDTYPESTUBS unless (OR (NC.CardTypeRecord TypeName)
							       (MEMB TypeName NOTECARDTYPES)
							       (GETHASH TypeName NC.CardTypes))
	    do (NC.CardTypeStubLoader TypeName))

          (* * Load the library packages requested by the user's NOTECARDSLIBRARYFILES parameters)


         (for File in NOTECARDSLIBRARYFILES unless (GETPROP File (QUOTE FILEDATES))
	    do (COND
		   ((SETQ FullFileName (NC.FindFile File))
		     (NC.LoadFileFromDirectories FullFileName))
		   (T (PRINT (CONCAT "NoteCards: Can't find library file: " File "."]
    (for File in NOTECARDSLISPUSERSFILES do (NC.LoadFileFromDirectories File (QUOTE 
									     LISPUSERSDIRECTORIES)))
    (if (GETD (QUOTE START-TEDIT-KILLER))
	then (START-TEDIT-KILLER))
    (NCP.NoteCardsParameters NCINITIALGLOBALPARAMS])
)
(DECLARE: DONTEVAL@LOAD DOEVAL@COMPILE DONTCOPY COMPILERVARS 

(ADDTOVAR NLAMA )

(ADDTOVAR NLAML )

(ADDTOVAR LAMA NCP.LinkType)
)
(PUTPROPS RGPATCH063 COPYRIGHT ("Xerox Corporation" 1987))
(DECLARE: DONTCOPY
  (FILEMAP (NIL (32211 137248 (NC.EditNoteCard 32221 . 35366) (NC.InstallTitleBarMiddleMenu 35368 . 
35971) (NC.ShowLinks 35973 . 39645) (NC.CardP 39647 . 39846) (NC.FetchStatus 39848 . 40073) (
NC.FetchNewCardFlg 40075 . 40523) (NC.FetchTitle 40525 . 40905) (NC.FetchType 40907 . 41294) (
NC.LinksCachedP 41296 . 41680) (NC.ActiveCardP 41682 . 42173) (NC.SetFromLinks 42175 . 42575) (
NC.SetLinksDirtyFlg 42577 . 43006) (NC.FetchFromLinks 43008 . 43398) (NC.SetLinksDate 43400 . 43852) (
NC.SetToLinks 43854 . 44253) (NC.SetGlobalLinks 44255 . 44666) (NC.CardNeedsFilingP 44668 . 46047) (
NC.TopLevelCardP 46049 . 46384) (NC.SetPropList 46386 . 46785) (NC.SetPropListDirtyFlg 46787 . 47207) 
(NC.FetchPropListDate 47209 . 47774) (NC.SetPropListDate 47776 . 48233) (NC.FetchPropList 48235 . 
48626) (NC.SetRegion 48628 . 49018) (NC.FetchSavedRegion 49020 . 49419) (NC.FetchRegion 49421 . 49804)
 (NC.FetchDefaultWidth 49806 . 50090) (NC.FetchDefaultHeight 50092 . 50375) (NC.FetchItemDate 50377 . 
50929) (NC.SetItemDate 50931 . 51375) (NC.SetType 51377 . 51660) (NC.FetchLinksDate 51662 . 52217) (
NC.FetchToLinks 52219 . 52607) (NC.FetchGlobalLinks 52609 . 52902) (NC.SetTitleDate 52904 . 53356) (
NC.SetTitle 53358 . 53750) (NC.ReadOnlyCardP 53752 . 54045) (NC.SetUserDataProp 54047 . 54473) (
NC.SetSubstance 54475 . 54903) (NC.MarkCardDirty 54905 . 55514) (NC.SetSubstanceDirtyFlg 55516 . 55938
) (NC.ActivateCard 55940 . 56231) (NC.FetchSubstance 56233 . 56621) (NC.MakeNoteCard 56623 . 59954) (
NC.SetNewCardFlg 59956 . 60413) (NC.DeactivateCard 60415 . 61730) (NC.SetTitleDirtyFlg 61732 . 62146) 
(NC.QuitCard 62148 . 68129) (NC.CardDirtyP 68131 . 68578) (NC.FetchSubstanceDirtyFlg 68580 . 68990) (
NC.FetchTitleDirtyFlg 68992 . 69391) (NC.FetchPropListDirtyFlg 69393 . 69807) (NC.FetchLinksDirtyFlg 
69809 . 70215) (NC.SetSavedRegion 70217 . 70764) (NC.FetchUserDataProp 70766 . 71077) (NC.CardSaveFn 
71079 . 78014) (NC.FetchBeingDeletedFlg 78016 . 78429) (NC.FetchTitleDate 78431 . 78986) (
NC.AssignTitle 78988 . 83718) (NC.CheckFiling 83720 . 85825) (NC.ObtainEditPermission 85827 . 87648) (
NC.RetrieveTypeAndTitle 87650 . 88799) (NC.FetchLinkDisplayMode 88801 . 89103) (
NC.DeleteNoteCardInternal 89105 . 95459) (NC.SetBeingDeletedFlg 95461 . 95885) (NC.ClosePropListEditor
 95887 . 99346) (NC.FetchLinkIconAttachedBitMap 99348 . 100917) (NC.FetchLinkAnchorModesSupported 
100919 . 101178) (NC.DeleteNoteCard 101180 . 103429) (NC.FetchRegionViewed 103431 . 103811) (
NC.FetchSlotNum 103813 . 104327) (NC.SetUserDataPropList 104329 . 104577) (NC.AddParents 104579 . 
107436) (NC.SeverExternalLinks 107438 . 113738) (NC.DeleteNoteCards 113740 . 120057) (
NC.QuitWithoutSaving 120059 . 126664) (NC.UnfileNoteCard 126666 . 128921) (NC.CollectReferences 128923
 . 130255) (NC.EditProperties 130257 . 132019) (NC.OpenPropListEditor 132021 . 136482) (
NC.CardOrCardHolderFromUID 136484 . 137246)) (137280 209154 (NC.TraverseLink 137290 . 138934) (
NC.DeleteBadLink 138936 . 140157) (NC.SameLinkP 140159 . 140458) (NC.ValidLinkP 140460 . 141194) (
NC.DeleteLink 141196 . 144496) (NC.DeleteFromLink 144498 . 145668) (NC.DelFromLink 145670 . 147596) (
NC.FileInOrphanBox 147598 . 149642) (NC.HookToOrphanCard 149644 . 151500) (NC.MakeFilingLink 151502 . 
154009) (NC.MakeLink 154011 . 161517) (NC.UpdateLinkImages 161519 . 162656) (NC.UncacheLinks 162658 . 
162892) (NC.MakeFilingLinks 162894 . 166335) (NC.AddToLink 166337 . 167606) (NC.AddFromLink 167608 . 
168779) (NC.DelToLink 168781 . 170492) (NC.DelReferencesToCard 170494 . 173928) (
NC.DelReferencesToCardFromGlobalList 173930 . 175805) (NC.DeleteToLink 175807 . 177003) (
NC.ChangeLinkDisplayMode 177005 . 182816) (NC.FetchLinkIconForLink 182818 . 183406) (NC.RelabelLink 
183408 . 189219) (NC.ChangeCardTitleFromLinkIcon 189221 . 191901) (NC.LinkIconWhenDeletedFn 191903 . 
196699) (NC.CheckForOrphanDelete 196701 . 198287) (NC.InsertLinkBeforeMarker 198289 . 203244) (
NC.AddGlobalLinksToCard 203246 . 205469) (NC.AddLinkToCard 205471 . 206913) (NC.AddLinksToCard 206915
 . 209152)) (209188 220637 (NCP.OpenCard 209198 . 209951) (NCP.DisplayCard 209953 . 210946) (
NCP.CardTypeLinkDisplayMode 210948 . 211443) (NCP.CardTypeSuper 211445 . 211907) (
NCP.RemoveSpecialCard 211909 . 212288) (NCP.NoteFileFromCard 212290 . 212538) (NCP.CardNoteFile 212540
 . 212784) (NCP.LocalGlobalLink 212786 . 216862) (NCP.GlobalGlobalLink 216864 . 218566) (NCP.LinkType 
218568 . 220635)) (220678 231061 (NC.CrossFileLinkEditFn 220688 . 221704) (NC.GetCrossFileLinkDestCard
 221706 . 226160) (NC.CreateCrossFileLinkCard 226162 . 227485) (NC.AskCrossFileLinkMode 227487 . 
228477) (NC.CheckCrossFileLinkType 228479 . 229879) (NC.ComputeCrossFileLinkMode 229881 . 231059)) (
231097 234607 (NC.GraphCardLeftButtonFn 231107 . 232424) (NC.RelayoutGraphCard 232426 . 234605)) (
234642 243602 (NC.InstallTextTitleBarMiddleMenu 234652 . 235484) (NC.MakeTEditCard 235486 . 237963) (
NC.BringUpTEditCard 237965 . 241074) (NC.TEditMenuFn 241076 . 242143) (NC.GetTextSubstance 242145 . 
243600)) (243639 247809 (NC.MakeSketchCard 243649 . 245253) (NC.BringUpSketchCard 245255 . 247807)) (
247850 251361 (NCIDEASKETCH.MakeIdeaSketchCard 247860 . 249129) (NCIDEASKETCH.BringUpIdeaSketchCard 
249131 . 251359)) (251397 285451 (NC.InstallTitleBarLeftMenu 251407 . 252035) (NC.AskLinkLabel 252037
 . 257001) (NC.SelectNoteCards 257003 . 274768) (NC.AttachNoteFileName 274770 . 278781) (
NC.CardImageObjP 278783 . 278968) (NC.CopyStructure 278970 . 281525) (NC.CloseStructure 281527 . 
283414) (NC.DeleteStructure 283416 . 285449)) (285489 292039 (NC.AddFileBoxCard 285499 . 286480) (
NC.MakeFileBox 286482 . 289026) (NC.FileBoxCollectChildren 289028 . 292037)) (292077 370053 (
NC.AddBrowserCard 292087 . 294947) (NC.MakeBrowserCard 294949 . 303696) (NC.BringUpBrowserCard 303698
 . 309205) (NC.UpdateBrowserCard 309207 . 321783) (NC.RelayoutBrowserCard 321785 . 328721) (
NC.ConnectNodesInBrowser 328723 . 335911) (NC.UnconnectNodesInBrowser 335913 . 338420) (
NC.ExpandBrowserNode 338422 . 347979) (NC.AskBrowserSpecs 347981 . 352539) (NC.ChangeBrowserSpecs 
352541 . 354127) (NC.BrowserCreateCard 354129 . 355828) (NC.BrowserAddNode 355830 . 359270) (
NC.DelBrowserContentsLink 359272 . 361241) (NC.MakeBrowserOverviewWin 361243 . 363640) (
NC.AskBrowserOverviewSpecs 363642 . 365783) (NC.BrowserCardQuitFn 365785 . 366343) (
NC.GetBrowserNodeID 366345 . 367302) (NC.GetBrowserHashArray 367304 . 368842) (
NC.RemoveBrowserNodeHashArrayEntry 368844 . 369407) (NC.SetBrowserRoots 369409 . 370051)) (370093 
381347 (NC.AddLinkIndexCard 370103 . 370807) (NC.MakeLinkIndex 370809 . 372878) (NC.ComputeLinkIndex 
372880 . 375604) (NC.RecomputeLinkIndex 375606 . 377163) (NC.AskLinkIndexSpecs 377165 . 379831) (
NC.ChangeLinkIndexSpecs 379833 . 381345)) (381383 394753 (NC.MakeCardTypesList 381393 . 383152) (
NC.AddCardType 383154 . 385793) (NC.IsSubTypeOfP 385795 . 386251) (NC.ModifyCardType 386253 . 387871) 
(NC.RecomputeCardType 387873 . 389048) (NC.SubTypesOfCardType 389050 . 389615) (
NC.InheritFieldsFromSuperType 389617 . 391928) (NC.AutoLoadCardType 391930 . 394751)) (394788 518660 (
NC.UIDSetPropList 394798 . 394981) (NC.UIDPutProp 394983 . 395309) (NC.UIDGetProp 395311 . 395497) (
NC.UIDGetPropList 395499 . 395720) (NC.ReadLink 395722 . 397493) (NC.OpenNoteFile 397495 . 415569) (
NC.StoreNoteFileInHashArray 415571 . 416775) (NC.FindNextCardPart 416777 . 418929) (
NC.ForceDatabaseClose 418931 . 421514) (NC.RemoveNoteFileFromHashArray 421516 . 422038) (
NC.CreateNoteFile 422040 . 429886) (NC.PutNoteFileHeader 429888 . 432056) (NC.CopyCardPartInPlaceToEOF
 432058 . 433207) (NC.GetLinks 433209 . 435568) (NC.ReadCardPartHeader 435570 . 437239) (
NC.PutFromLinks 437241 . 439542) (NC.WriteCardPartHeader 439544 . 440320) (NC.WriteLink 440322 . 
441597) (NC.PutPropList 441599 . 445044) (NC.GetPropList 445046 . 447338) (NC.GetType 447340 . 449512)
 (NC.PutLinks 449514 . 453120) (NC.GetTitle 453122 . 455786) (NC.PutMainCardData 455788 . 460774) (
NC.GetNoteCard 460776 . 461473) (NC.GetMainCardData 461475 . 464535) (NC.SetStatus 464537 . 464831) (
NC.InstallCardInNoteFile 464833 . 465503) (NC.LockListOfCards 465505 . 469554) (
NC.CardCheckOpInProgress 469556 . 471834) (NC.PutRegion 471836 . 473011) (NC.PutTitle 473013 . 476331)
 (NC.CloseNoteFile 476333 . 488952) (NC.CleanupCardObjects 488954 . 489552) (NC.CloseListOfActiveCards
 489554 . 490936) (NC.PutNoteCard 490938 . 491398) (NC.SetMainLoc 491400 . 491701) (NC.SetLinksLoc 
491703 . 492008) (NC.SetTitleLoc 492010 . 492312) (NC.SetPropListLoc 492314 . 492628) (NC.CopyCards 
492630 . 504714) (NC.PutNoteCardToStream 504716 . 505763) (NC.GetNoteCardFromStream 505765 . 506647) (
NC.MakeHashKeyFromCard 506649 . 506890) (NC.UpdateIndexLocIfNeeded 506892 . 508327) (
NC.FixUpLinksInCardCopy 508329 . 514798) (NC.OperationInProgress 514800 . 515452) (NC.GetNewCard 
515454 . 516348) (NC.InstallCriticalUIDsInNoteFile 516350 . 518658)) (518698 542699 (
NCLocalDevice.GetNoteFileHeader 518708 . 520542) (NCLocalDevice.OpenNoteFile 520544 . 524387) (
NCLocalDevice.PutNoteFileHeader 524389 . 526637) (NCLocalDevice.NewCardUID 526639 . 528459) (
NCLocalDevice.GetCardInfo 528461 . 529712) (NCLocalDevice.PutCardPart 529714 . 533727) (
NCLocalDevice.GetCardPart 533729 . 534446) (NCLocalDevice.GetHashArray 534448 . 537050) (
NCLocalDevice.PutHashArray 537052 . 539500) (NCLocalDevice.PutIndexEntry 539502 . 540543) (
NCLocalDevice.PutFromLinks 540545 . 541973) (NCLocalDevice.ReadIndexEntry 541975 . 542697)) (542744 
554973 (NC.ConvertNoteFileVersion2To3 542754 . 547853) (NC.ConvertVersion2LinkIcon 547855 . 549589) (
NC.ConvertLinkFormat 549591 . 551656) (NC.ReadVersion2MainCardData 551658 . 554971)) (555007 566117 (
NC.CompactNoteFileToTarget 555017 . 559933) (NC.GetCardPartLength 559935 . 560370) (
NC.SortIndexEntries 560372 . 561879) (NC.UpdateCardLoc 561881 . 562522) (NC.CopySortedCardPart 562524
 . 563775) (NC.CopySortedCardPartInPlace 563777 . 566115)) (566153 567847 (NC.CoerceToNoteFileStream 
566163 . 566655) (NC.CoerceToInterestedWindow 566657 . 567845)) (567883 601307 (NC.AskLinkLabel 567893
 . 572857) (NC.SelectNoteCards 572859 . 590624) (NC.AttachNoteFileName 590626 . 594637) (
NC.CardImageObjP 594639 . 594824) (NC.CopyStructure 594826 . 597381) (NC.CloseStructure 597383 . 
599270) (NC.DeleteStructure 599272 . 601305)) (601340 624280 (NC.RobustGetSubstance 601350 . 602040) (
NC.WorthlessCardP 602042 . 603128) (NC.CheckIndexLocs 603130 . 604927) (NC.BuildTitlesInspectorMenu 
604929 . 607125) (NC.BuildSubstancesInspectorMenu 607127 . 609364) (NC.BuildLinksInspectorMenu 609366
 . 611426) (NC.BuildPropListsInspectorMenu 611428 . 613383) (NC.CardSubstanceVersionInspector 613385
 . 617190) (NC.CardLinksVersionInspector 617192 . 618353) (NC.CardPropListVersionInspector 618355 . 
619298) (NC.CheckForBadLinksAndTitlesAndPropLists 619300 . 623807) (NC.UndeletableCardP 623809 . 
624278)) (624315 625624 (NC.RegistryCardMakeFn 624325 . 624594) (NC.RegisterCardByName 624596 . 625036
) (NC.LookupCardByName 625038 . 625622)) (625661 627924 (NC.MakeSearchCard 625671 . 627922)) (627963 
637623 (NC.MakeDocument 627973 . 634823) (NC.MakeDocInspectorSelectionFn 634825 . 637621)) (637655 
639435 (NCHACKS.MakeLinkIconsInvisibleInTextCard 637665 . 638459) (
NCHACKS.MakeLinkIconForLinkInvisible 638461 . 639433)) (639469 642465 (NC.PostGreet 639479 . 642463)))
))
STOP