/* SampleList.c */
/*****************************************************************************/
/*                                                                           */
/*    Out Of Phase:  Digital Music Synthesis on General Purpose Computers    */
/*    Copyright (C) 1994  Thomas R. Lawrence                                 */
/*                                                                           */
/*    This program is free software; you can redistribute it and/or modify   */
/*    it under the terms of the GNU General Public License as published by   */
/*    the Free Software Foundation; either version 2 of the License, or      */
/*    (at your option) any later version.                                    */
/*                                                                           */
/*    This program is distributed in the hope that it will be useful,        */
/*    but WITHOUT ANY WARRANTY; without even the implied warranty of         */
/*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          */
/*    GNU General Public License for more details.                           */
/*                                                                           */
/*    You should have received a copy of the GNU General Public License      */
/*    along with this program; if not, write to the Free Software            */
/*    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.              */
/*                                                                           */
/*    Thomas R. Lawrence can be reached at tomlaw@world.std.com.             */
/*                                                                           */
/*****************************************************************************/

#include "MiscInfo.h"
#include "Audit.h"
#include "Debug.h"
#include "Definitions.h"

#include "SampleList.h"
#include "Memory.h"
#include "StringList.h"
#include "Array.h"
#include "SampleObject.h"
#include "Alert.h"
#include "DataMunging.h"
#include "PcodeSystem.h"
#include "BufferedFileInput.h"
#include "BufferedFileOutput.h"
#include "Files.h"
#include "Scrap.h"
#include "InstrList.h"


struct SampleListRec
	{
		StringListRec*					List;
		struct CodeCenterRec*		CodeCenter;
		struct MainWindowRec*		MainWindow;
		ArrayRec*								SampleArray;
		MyBoolean								SampleListChanged;
	};


#define MAGICSCRAPSTRING ("\xff\x00\x1f\xfe SampleObjectScrap")


SampleListRec*			NewSampleList(struct MainWindowRec* MainWindow,
											struct CodeCenterRec* CodeCenter, WinType* ScreenID,
											OrdType XLoc, OrdType YLoc, OrdType Width, OrdType Height)
	{
		SampleListRec*		SampList;

		SampList = (SampleListRec*)AllocPtrCanFail(sizeof(SampleListRec),"SampleListRec");
		if (SampList == NIL)
			{
			 FailurePoint1:
				return NIL;
			}
		SampList->List = NewStringList(ScreenID,XLoc,YLoc,Width,Height,
			GetScreenFont(),9,StringListDontAllowMultipleSelection,"Samples");
		if (SampList->List == NIL)
			{
			 FailurePoint2:
				ReleasePtr((char*)SampList);
				goto FailurePoint1;
			}
		SampList->SampleArray = NewArray();
		if (SampList->SampleArray == NIL)
			{
			 FailurePoint3:
				DisposeStringList(SampList->List);
				goto FailurePoint2;
			}
		SampList->CodeCenter = CodeCenter;
		SampList->MainWindow = MainWindow;
		SampList->SampleListChanged = False;
		return SampList;
	}


/* delete the sample list and all of the samples it contains */
void								DisposeSampleList(SampleListRec* SampList)
	{
		long							Scan;
		long							Limit;

		CheckPtrExistence(SampList);
		Limit = ArrayGetLength(SampList->SampleArray);
		for (Scan = 0; Scan < Limit; Scan += 1)
			{
				SampleObjectRec*	SampleTemp;

				SampleTemp = (SampleObjectRec*)ArrayGetElement(SampList->SampleArray,Scan);
				DisposeSampleObject(SampleTemp);
			}
		DisposeArray(SampList->SampleArray);
		DisposeStringList(SampList->List);
		ReleasePtr((char*)SampList);
	}


/* change the location of the sample list in the window */
void								SetSampleListLocation(SampleListRec* SampList,
											OrdType XLoc, OrdType YLoc, OrdType Width, OrdType Height)
	{
		CheckPtrExistence(SampList);
		SetStringListLoc(SampList->List,XLoc,YLoc,Width,Height);
	}


/* redraw the list */
void								SampleListRedraw(SampleListRec* SampList)
	{
		CheckPtrExistence(SampList);
		RedrawStringList(SampList->List);
	}


/* see if the specified coordinates falls inside the sample list rectangle */
MyBoolean						SampleListHitTest(SampleListRec* SampList,
											OrdType XLoc, OrdType YLoc)
	{
		CheckPtrExistence(SampList);
		return StringListHitTest(SampList->List,XLoc,YLoc);
	}


/* handle a mouse down event for the sample list */
void								SampleListDoMouseDown(SampleListRec* SampList, OrdType XLoc,
											OrdType YLoc, ModifierFlags Modifiers)
	{
		CheckPtrExistence(SampList);
		if (StringListMouseDown(SampList->List,XLoc,YLoc,Modifiers))
			{
				/* if it returns true, then it was a double click */
				SampleListOpenSelection(SampList);
			}
	}


/* called when the window becomes active */
void								SampleListBecomeActive(SampleListRec* SampList)
	{
		CheckPtrExistence(SampList);
		EnableStringList(SampList->List);
	}


/* called when the window becomes inactive */
void								SampleListBecomeInactive(SampleListRec* SampList)
	{
		CheckPtrExistence(SampList);
		DisableStringList(SampList->List);
	}


/* called when a selection is made in another list, so that this list */
/* is deselected */
void								SampleListDeselect(SampleListRec* SampList)
	{
		CheckPtrExistence(SampList);
		DeselectAllStringListElements(SampList->List);
	}


/* check to see if there is a selection in this list */
MyBoolean						SampleListIsThereSelection(SampleListRec* SampList)
	{
		CheckPtrExistence(SampList);
		return (GetStringListHowManySelectedItems(SampList->List) > 0);
	}


/* check to see if any of the samples contained in this list need to be saved */
MyBoolean						DoesSampleListNeedToBeSaved(SampleListRec* SampList)
	{
		long							Scan;
		long							Limit;
		MyBoolean					Flag;

		CheckPtrExistence(SampList);
		Flag = SampList->SampleListChanged;
		Limit = ArrayGetLength(SampList->SampleArray);
		for (Scan = 0; (Scan < Limit) && !Flag; Scan += 1)
			{
				SampleObjectRec*	SampleTemp;

				SampleTemp = (SampleObjectRec*)ArrayGetElement(SampList->SampleArray,Scan);
				if (HasSampleObjectBeenModified(SampleTemp))
					{
						Flag = True;
					}
			}
		return Flag;
	}


/* open an edit window for the selected sample */
void								SampleListOpenSelection(SampleListRec* SampList)
	{
		ArrayRec*					ListOfSelections;

		CheckPtrExistence(SampList);
		ListOfSelections = GetListOfSelectedItems(SampList->List);
		if (ListOfSelections != NIL)
			{
				long							Scan;
				long							Limit;

				Limit = ArrayGetLength(ListOfSelections);
				for (Scan = 0; Scan < Limit; Scan += 1)
					{
						SampleObjectRec*		SampleTemp;

						SampleTemp = (SampleObjectRec*)ArrayGetElement(ListOfSelections,Scan);
						SampleObjectOpenWindow(SampleTemp);
					}
				DisposeArray(ListOfSelections);
			}
	}


/* create a new sample and open a window for it */
void								SampleListNewSample(SampleListRec* SampList)
	{
		SampleObjectRec*	Sample;

		CheckPtrExistence(SampList);
		/* create the object */
		Sample = NewSampleObject(SampList->CodeCenter,SampList->MainWindow,SampList);
		if (Sample == NIL)
			{
			 FailurePoint1:
				AlertHalt("There is not enough memory available to create a new sample.",NIL);
				return;
			}
		/* add it to the string list */
		if (!InsertStringListElement(SampList->List,NIL,NIL,Sample,True))
			{
			 FailurePoint2:
				DisposeSampleObject(Sample);
				goto FailurePoint1;
			}
		MainWindowDeselectAllOtherStringLists(SampList->MainWindow,SampList);
		SelectStringListElement(SampList->List,Sample);
		MakeStringListSelectionVisible(SampList->List);
		/* add it to the array */
		if (!ArrayAppendElement(SampList->SampleArray,Sample))
			{
			 FailurePoint3:
				RemoveStringListElement(SampList->List,Sample,True);
				goto FailurePoint2;
			}
		/* update our internal flags */
		SampList->SampleListChanged = True;
		/* change the name in the list */
		SampleListSampleNameChanged(SampList,Sample);
		/* show the window */
		SampleObjectOpenWindow(Sample);
	}


/* delete the selected sample */
void								SampleListDeleteSelection(SampleListRec* SampList)
	{
		ArrayRec*					ListOfSelections;

		CheckPtrExistence(SampList);
		ListOfSelections = GetListOfSelectedItems(SampList->List);
		if (ListOfSelections != NIL)
			{
				long								Scan;
				long								Limit;

				Limit = ArrayGetLength(ListOfSelections);
				for (Scan = 0; Scan < Limit; Scan += 1)
					{
						SampleObjectRec*	OneToZap;

						OneToZap = (SampleObjectRec*)ArrayGetElement(ListOfSelections,Scan);
						SampleListDeleteSample(SampList,OneToZap);
					}
				DisposeArray(ListOfSelections);
			}
	}


/* delete the explicitly specified sample */
void								SampleListDeleteSample(SampleListRec* SampList,
											struct SampleObjectRec* TheSample)
	{
		long								Scan;
		long								Limit;

		CheckPtrExistence(SampList);
		MainWindowClearInstrObjects(SampList->MainWindow);
		Limit = ArrayGetLength(SampList->SampleArray);
		for (Scan = 0; Scan < Limit; Scan += 1)
			{
				SampleObjectRec*		SampleTemp;

				SampleTemp = (SampleObjectRec*)ArrayGetElement(SampList->SampleArray,Scan);

				if (TheSample == SampleTemp)
					{
						FileSpec*					BackupFileWhere;
						FileType*					BackupFile;
						MyBoolean					Success = False;

						BackupFileWhere = NewTempFileSpec(CODE4BYTES('?','?','?','?'),
							CODE4BYTES('?','?','?','?'));
						if (BackupFileWhere != NIL)
							{
								if (OpenFile(BackupFileWhere,&BackupFile,eReadAndWrite))
									{
										BufferedOutputRec*	Output;

										Output = NewBufferedOutput(BackupFile);
										if (Output != NIL)
											{
												if (WriteBufferedOutput(Output,sizeof(MAGICSCRAPSTRING),
													MAGICSCRAPSTRING))
													{
														if (SampleObjectWriteOutData(TheSample,Output)
															== eFileLoadNoError)
															{
																Success = True;
															}
													}
												if (!EndBufferedOutput(Output))
													{
														Success = False;
													}
											}
										 else
											{
												CloseFile(BackupFile);
											}
									}
								 else
									{
										DeleteFile(BackupFileWhere);
										DisposeFileSpec(BackupFileWhere);
									}
							}
						if (Success)
							{
								MainWindowNewDeleteUndoInfo(SampList->MainWindow,BackupFileWhere,
									BackupFile);
								DisposeSampleObject(SampleTemp);
								RemoveStringListElement(SampList->List,SampleTemp,True);
								ArrayDeleteElement(SampList->SampleArray,Scan);
								SampList->SampleListChanged = True;
							}
						 else
							{
								YesNoCancelType		Decision;

								Decision = AskYesNoCancel("Unable to save undo information for object.  "
									"Delete object anyway?",NIL,"Delete","Cancel",NIL/*nothirdbutton*/);
								if (Decision == eYes)
									{
										DisposeSampleObject(SampleTemp);
										RemoveStringListElement(SampList->List,SampleTemp,True);
										ArrayDeleteElement(SampList->SampleArray,Scan);
										SampList->SampleListChanged = True;
									}
							}
						return;
					}
			}
		EXECUTE(PRERR(AllowResume,"SampleListDeleteSample:  couldn't find object"));
	}


/* the name of a sample has changed, so the name in the scrolling */
/* list must also be changed */
void								SampleListSampleNameChanged(SampleListRec* SampList,
											struct SampleObjectRec* TheSample)
	{
		char*							SampleName;

		CheckPtrExistence(SampList);
		CheckPtrExistence(TheSample);
		ERROR(ArrayFindElement(SampList->SampleArray,TheSample) < 0,
			PRERR(ForceAbort,"SampleListSampleNameChanged:  unknown sample"));
		SampleName = SampleObjectGetNameCopy(TheSample);
		if (SampleName != NIL)
			{
				char*							SampleNameNullTerminated;

				SampleNameNullTerminated = BlockToStringCopy(SampleName);
				if (SampleNameNullTerminated != NIL)
					{
						ChangeStringListElementName(SampList->List,
							SampleNameNullTerminated,TheSample);
						ReleasePtr(SampleNameNullTerminated);
					}
				ReleasePtr(SampleName);
			}
	}


/* look for a specified sample.  returns NIL if not found.  the name is NOT null */
/* terminated */
SampleObjectRec*		SampleListLookupNamedSample(SampleListRec* SampList, char* Name)
	{
		long							Scan;
		long							Limit;

		CheckPtrExistence(SampList);
		CheckPtrExistence(Name);
		Limit = ArrayGetLength(SampList->SampleArray);
		for (Scan = 0; Scan < Limit; Scan += 1)
			{
				SampleObjectRec*		Sample;
				char*								NameCopy;

				Sample = (SampleObjectRec*)ArrayGetElement(SampList->SampleArray,Scan);
				NameCopy = SampleObjectGetNameCopy(Sample);
				if (NameCopy != NIL)
					{
						if (PtrSize(Name) == PtrSize(NameCopy))
							{
								if (MemEqu(Name,NameCopy,PtrSize(Name)))
									{
										ReleasePtr(NameCopy);
										return Sample;
									}
							}
						ReleasePtr(NameCopy);
					}
			}
		return NIL;
	}


SampleErrors				SampleListGetSampleLeftFixed(SampleListRec* SampList,
											char* Name, largefixedsigned** DataOut)
	{
		SampleObjectRec*		Sample;

		CheckPtrExistence(SampList);
		ERROR(DataOut == NIL,PRERR(ForceAbort,
			"SampleListGetSampleLeftFixed:  data out is NIL"));
		Sample = SampleListLookupNamedSample(SampList,Name);
		if (Sample == NIL)
			{
				return eEvalSampleUndefined;
			}
		if (eSampleStereo != SampleObjectGetNumChannels(Sample))
			{
				return eEvalSampleWrongChannel;
			}
		*DataOut = SampleObjectGetLeftFixed(Sample);
		if (*DataOut == NIL)
			{
				return eEvalSampleNotEnoughMemoryToCopy;
			}
		return eEvalSampleNoError;
	}


SampleErrors				SampleListGetSampleRightFixed(SampleListRec* SampList,
											char* Name, largefixedsigned** DataOut)
	{
		SampleObjectRec*		Sample;

		CheckPtrExistence(SampList);
		ERROR(DataOut == NIL,PRERR(ForceAbort,
			"SampleListGetSampleRightFixed:  data out is NIL"));
		Sample = SampleListLookupNamedSample(SampList,Name);
		if (Sample == NIL)
			{
				return eEvalSampleUndefined;
			}
		if (eSampleStereo != SampleObjectGetNumChannels(Sample))
			{
				return eEvalSampleWrongChannel;
			}
		*DataOut = SampleObjectGetRightFixed(Sample);
		if (*DataOut == NIL)
			{
				return eEvalSampleNotEnoughMemoryToCopy;
			}
		return eEvalSampleNoError;
	}


SampleErrors				SampleListGetSampleMonoFixed(SampleListRec* SampList,
											char* Name, largefixedsigned** DataOut)
	{
		SampleObjectRec*		Sample;

		CheckPtrExistence(SampList);
		ERROR(DataOut == NIL,PRERR(ForceAbort,
			"SampleListGetSampleMonoFixed:  data out is NIL"));
		Sample = SampleListLookupNamedSample(SampList,Name);
		if (Sample == NIL)
			{
				return eEvalSampleUndefined;
			}
		if (eSampleMono != SampleObjectGetNumChannels(Sample))
			{
				return eEvalSampleWrongChannel;
			}
		*DataOut = SampleObjectGetMonoFixed(Sample);
		if (*DataOut == NIL)
			{
				return eEvalSampleNotEnoughMemoryToCopy;
			}
		return eEvalSampleNoError;
	}


/* use the provided data to open a new sample with the specified attributes. */
/* this is used when opening an algorithmic sample as a data sample. */
/* RawData MUST be valid. */
SampleObjectRec*		SampleListCopyRawSampleAndOpen(SampleListRec* SampList,
											char* RawData, NumBitsType NumBits, NumChannelsType NumChannels,
											long Origin, long LoopStart1, long LoopStart2, long LoopStart3,
											long LoopEnd1, long LoopEnd2, long LoopEnd3, long SamplingRate,
											double NaturalFrequency)
	{
		SampleObjectRec*	Sample;

		CheckPtrExistence(SampList);
		CheckPtrExistence(RawData);
		/* create the object */
		Sample = NewSampleObjectInitialized(SampList->CodeCenter,SampList->MainWindow,
			SampList,RawData,NumBits,NumChannels,Origin,LoopStart1,LoopStart2,LoopStart3,
			LoopEnd1,LoopEnd2,LoopEnd3,SamplingRate,NaturalFrequency);
		if (Sample == NIL)
			{
			 FailurePoint1:
				AlertHalt("There is not enough memory available to create a new sample.",NIL);
				return NIL;
			}
		/* add it to the string list */
		if (!InsertStringListElement(SampList->List,NIL,NIL,Sample,True))
			{
			 FailurePoint2:
				DisposeSampleObject(Sample);
				goto FailurePoint1;
			}
		MainWindowDeselectAllOtherStringLists(SampList->MainWindow,SampList);
		SelectStringListElement(SampList->List,Sample);
		MakeStringListSelectionVisible(SampList->List);
		/* add it to the array */
		if (!ArrayAppendElement(SampList->SampleArray,Sample))
			{
			 FailurePoint3:
				RemoveStringListElement(SampList->List,Sample,True);
				goto FailurePoint2;
			}
		/* update our internal flags */
		SampList->SampleListChanged = True;
		/* change the name in the list */
		SampleListSampleNameChanged(SampList,Sample);
		/* show the window */
		SampleObjectOpenWindow(Sample);
		return Sample;
	}


/* the document's name has changed, so the windows have to be updated */
void								SampleListGlobalNameChange(SampleListRec* SampleList,
											char* NewFilename)
	{
		long							Scan;
		long							Limit;

		CheckPtrExistence(SampleList);
		Limit = ArrayGetLength(SampleList->SampleArray);
		for (Scan = 0; Scan < Limit; Scan += 1)
			{
				SampleObjectRec*		Sample;

				Sample = (SampleObjectRec*)ArrayGetElement(SampleList->SampleArray,Scan);
				SampleObjectGlobalNameChange(Sample,NewFilename);
			}
	}


/*   4-bytes little endian number of sample objects (positive 2s complement) */
/*   n-bytes of data for the sampe objects */


/* read sample objects from a file.  returns True if fully successful. */
FileLoadingErrors		SampleListReadData(SampleListRec* SampleList,
											struct BufferedInputRec* Input)
	{
		signed long				NumSampleObjects;
		long							Scan;

		CheckPtrExistence(SampleList);
		CheckPtrExistence(Input);

		/*   4-bytes little endian number of sample objects */
		if (!ReadBufferedSignedLongLittleEndian(Input,&NumSampleObjects))
			{
				return eFileLoadDiskError;
			}
		if (NumSampleObjects < 0)
			{
				return eFileLoadBadFormat;
			}

		/* load the objects */
		for (Scan = 0; Scan < NumSampleObjects; Scan += 1)
			{
				SampleObjectRec*	Sample EXECUTE(= (SampleObjectRec*)0x81818181);
				FileLoadingErrors	Error;

				/* read the sample object from the file */
				Error = SampleObjectNewFromFile(&Sample,Input,SampleList->CodeCenter,
					SampleList->MainWindow,SampleList);
				if (Error != eFileLoadNoError)
					{
					 FailurePoint1:
						return Error;
					}
				CheckPtrExistence(Sample);
				/* add it to the string list */
				if (!InsertStringListElement(SampleList->List,NIL,NIL,Sample,True))
					{
					 FailurePoint2:
						DisposeSampleObject(Sample);
						Error = eFileLoadOutOfMemory;
						goto FailurePoint1;
					}
				/* add it to the array */
				if (!ArrayAppendElement(SampleList->SampleArray,Sample))
					{
					 FailurePoint3:
						RemoveStringListElement(SampleList->List,Sample,True);
						goto FailurePoint2;
					}
				/* change the name in the list */
				SampleListSampleNameChanged(SampleList,Sample);
			}

		return eFileLoadNoError;
	}


/* write sample objects to a file.  returns True if fully successful. */
FileLoadingErrors		SampleListWriteData(SampleListRec* SampleList,
											struct BufferedOutputRec* Output)
	{
		signed long				NumSampleObjects;
		long							Scan;

		CheckPtrExistence(SampleList);
		CheckPtrExistence(Output);

		/*   4-bytes little endian number of sample objects (positive 2s complement) */
		NumSampleObjects = ArrayGetLength(SampleList->SampleArray);
		if (!WriteBufferedSignedLongLittleEndian(Output,NumSampleObjects))
			{
				return eFileLoadDiskError;
			}

		/* write out the samples */
		for (Scan = 0; Scan < NumSampleObjects; Scan += 1)
			{
				SampleObjectRec*		Sample;
				FileLoadingErrors		Error;

				/* get the sample */
				Sample = (SampleObjectRec*)ArrayGetElement(SampleList->SampleArray,Scan);
				/* write it out */
				Error = SampleObjectWriteOutData(Sample,Output);
				/* handle mishaps */
				if (Error != eFileLoadNoError)
					{
						return Error;
					}
			}

		return eFileLoadNoError;
	}


/* after a file has been saved, this is called to mark all objects as not modified. */
void								SampleListMarkAllObjectsSaved(SampleListRec* SampleList)
	{
		long							Scan;
		long							Limit;

		CheckPtrExistence(SampleList);
		Limit = ArrayGetLength(SampleList->SampleArray);
		for (Scan = 0; Scan < Limit; Scan += 1)
			{
				SampleObjectRec*		Sample;

				Sample = (SampleObjectRec*)ArrayGetElement(SampleList->SampleArray,Scan);
				SampleObjectMarkAsSaved(Sample);
			}
		SampleList->SampleListChanged = False;
	}


/* copy the selected object in the list to the clipboard.  return False if failed. */
MyBoolean						SampleListCopyObject(SampleListRec* SampleList)
	{
		ArrayRec*							ListOfSelections;
		MyBoolean							TotalSuccessFlag = False;

		CheckPtrExistence(SampleList);
		ListOfSelections = GetListOfSelectedItems(SampleList->List);
		if (ListOfSelections != NIL)
			{
				if (ArrayGetLength(ListOfSelections) >= 1)
					{
						SampleObjectRec*		SampleTemp;
						FileSpec*						TempFileLocation;

						SampleTemp = (SampleObjectRec*)ArrayGetElement(ListOfSelections,0);
						/* open the temporary file */
						TempFileLocation = NewTempFileSpec(CODE4BYTES('\?','\?','\?','\?'),
							CODE4BYTES('\?','\?','\?','\?'));
						if (TempFileLocation != NIL)
							{
								FileType*							FileDescriptor;

								if (OpenFile(TempFileLocation,&FileDescriptor,eReadAndWrite))
									{
										BufferedOutputRec*		BufferedFile;

										BufferedFile = NewBufferedOutput(FileDescriptor);
										if (BufferedFile != NIL)
											{
												MyBoolean							WriteSucceeded = False;

												if (WriteBufferedOutput(BufferedFile,sizeof(MAGICSCRAPSTRING),
													MAGICSCRAPSTRING))
													{
														if (SampleObjectWriteOutData(SampleTemp,BufferedFile)
															== eFileLoadNoError)
															{
																WriteSucceeded = True;
															}
													}
												if (EndBufferedOutput(BufferedFile) && WriteSucceeded)
													{
														char*							Buffer;
														long							NumberOfBytes;

														NumberOfBytes = GetFileLength(FileDescriptor);
														Buffer = AllocPtrCanFail(NumberOfBytes,
															"SampleListCopyObject:  scrap buffer");
														if (Buffer != NIL)
															{
																if (SetFilePosition(FileDescriptor,0))
																	{
																		if (0 == ReadFromFile(FileDescriptor,
																			Buffer,NumberOfBytes))
																			{
																				if (SetScrapToThis(Buffer))
																					{
																						TotalSuccessFlag = True;
																					}
																			}
																	}
																ReleasePtr(Buffer);
															}
													}
											}
										CloseFile(FileDescriptor);
									}
								DeleteFile(TempFileLocation);
								DisposeFileSpec(TempFileLocation);
							}
					}
				DisposeArray(ListOfSelections);
			}
		return TotalSuccessFlag;
	}


/* try to paste the clipboard in as a sample object.  returns False if it failed */
/* or the clipboard did not contain a sample object. */
MyBoolean						SampleListPasteObject(SampleListRec* SampleList)
	{
		MyBoolean					TotalSuccessFlag = False;
		char*							Scrap;

		CheckPtrExistence(SampleList);
		Scrap = GetCopyOfScrap();
		if (Scrap != NIL)
			{
				FileSpec*					TempFileLocation;

				TempFileLocation = NewTempFileSpec(CODE4BYTES('\?','\?','\?','\?'),
					CODE4BYTES('\?','\?','\?','\?'));
				if (TempFileLocation != NIL)
					{
						FileType*							FileDescriptor;

						if (OpenFile(TempFileLocation,&FileDescriptor,eReadAndWrite))
							{
								BufferedOutputRec*		BufferedFile;

								BufferedFile = NewBufferedOutput(FileDescriptor);
								if (BufferedFile != NIL)
									{
										MyBoolean							WriteSucceeded = False;

										if (WriteBufferedOutput(BufferedFile,PtrSize(Scrap),Scrap))
											{
												WriteSucceeded = True;
											}
										if (EndBufferedOutput(BufferedFile) && WriteSucceeded)
											{
												TotalSuccessFlag = SampleListPasteFromFile(SampleList,
													FileDescriptor);
											}
									}
								CloseFile(FileDescriptor);
							}
						DeleteFile(TempFileLocation);
						DisposeFileSpec(TempFileLocation);
					}
				ReleasePtr(Scrap);
			}
		return TotalSuccessFlag;
	}


/* paste a sample object in from the file */
MyBoolean						SampleListPasteFromFile(SampleListRec* SampleList,
											struct FileType* File)
	{
		MyBoolean					TotalSuccessFlag = False;

		CheckPtrExistence(SampleList);
		if (SetFilePosition(File,0))
			{
				BufferedInputRec*	InputFile;

				InputFile = NewBufferedInput(File);
				if (InputFile != NIL)
					{
						char							HeaderTest[sizeof(MAGICSCRAPSTRING)];

						if (ReadBufferedInput(InputFile,sizeof(MAGICSCRAPSTRING),HeaderTest))
							{
								if (MemEqu(MAGICSCRAPSTRING,HeaderTest,sizeof(MAGICSCRAPSTRING)))
									{
										SampleObjectRec*			SampleTemp EXECUTE(= (SampleObjectRec*)0x81818181);

										if (eFileLoadNoError == SampleObjectNewFromFile(&SampleTemp,InputFile,
											SampleList->CodeCenter,SampleList->MainWindow,SampleList))
											{
												CheckPtrExistence(SampleTemp);
												/* add it to the scrolling object list */
												if (!InsertStringListElement(SampleList->List,NIL,NIL,SampleTemp,True))
													{
													 FailurePoint:
														DisposeSampleObject(SampleTemp);
													}
												 else
													{
														MainWindowDeselectAllOtherStringLists(SampleList->MainWindow,SampleList);
														SelectStringListElement(SampleList->List,SampleTemp);
														MakeStringListSelectionVisible(SampleList->List);
														/* add it to the array */
														if (!ArrayAppendElement(SampleList->SampleArray,SampleTemp))
															{
																RemoveStringListElement(SampleList->List,SampleTemp,True);
																goto FailurePoint;
															}
														 else
															{
																/* change the name in the list */
																SampleListSampleNameChanged(SampleList,SampleTemp);
																TotalSuccessFlag = True;
																SampleList->SampleListChanged = True;
															}
													}
											}
									}
							}
						EndBufferedInput(InputFile);
					}
			}
		return TotalSuccessFlag;
	}


/* find out how many samples there are in this list */
long								SampleListHowMany(SampleListRec* SampleList)
	{
		CheckPtrExistence(SampleList);
		return ArrayGetLength(SampleList->SampleArray);
	}


/* get an indexed sample from the list */
struct SampleObjectRec*	SampleListGetIndexedSample(SampleListRec* SampleList, long Index)
	{
		SampleObjectRec*	Sample;

		CheckPtrExistence(SampleList);
		ERROR((Index < 0) || (Index >= SampleListHowMany(SampleList)),PRERR(ForceAbort,
			"SampleListGetIndexedSample:  index out of range"));
		Sample = (SampleObjectRec*)ArrayGetElement(SampleList->SampleArray,Index);
		CheckPtrExistence(Sample);
		return Sample;
	}
