/* FSUtilities.c */
/*
 * Copyright (C) 1985-1992  New York University
 * Copyright (C) 1994 George Washington University
 * 
 * This file is part of the GWAdaEd system, an extension of the Ada/Ed-C
 * system.  See the Ada/Ed README file for warranty (none) and distribution
 * info and also the GNU General Public License for more details.
 */


/* Routines to traverse files in folder listing */

#include "FSUtilities.h"
#include "AdaFileTypes.h"


/****
 *	CountFilesInFolder()
 *
 *	Given an FSSpec for a folder, this routine will count
 *	how many files and folders are stored in the parent
 *	folder.
 *
 *	Returns 0 on errors.
 *
 ****/

long	CountItemsInFolder(FSSpec folder)
{
	CInfoPBRec	pb;				/* local pb */
	HFileInfo	*fpb = (HFileInfo *)&pb;	/* to pointers */
	DirInfo	*dpb = (DirInfo *) &pb;
	long		dirID;
	long		count, idx;
	OSErr		err;
	Str255		name;

	fpb->ioFDirIndex = 0;		// this HAS to be 0!
	fpb->ioDirID   = folder.parID;
	fpb->ioVRefNum = folder.vRefNum;
	fpb->ioNamePtr = folder.name;
	err = PBGetCatInfo(&pb, false);
	dirID = fpb->ioDirID;		/* save to set on each loop */

	count = 0;
	fpb->ioNamePtr = name;
	for (idx = 1; err == noErr; idx++) {
		fpb->ioDirID = dirID;	/* must set on each loop */
		fpb->ioFDirIndex = idx;
		err = PBGetCatInfo(&pb, false);

		//if ((err == noErr) && !(fpb->ioFlAttrib & 16))
		if (err == noErr)
			count++;
	}

	return count;
}

/****
 *	GetItemInFolder()
 *
 *	Given a folder and an index to a file into the folder,
 *	return an FSSpec for the file/folder in the folder.
 *
 ****/

void	GetItemInFolder(long index, FSSpec folder, FSSpec *file)
{	// set file.name to a valid empty Pascal String if error
	CInfoPBRec	pb;
	HFileInfo	*fpb = (HFileInfo *)&pb;	/* to pointers */
	DirInfo		*dpb = (DirInfo *) &pb;
	OSErr		err;
	Str255		name;

	fpb->ioFDirIndex = 0;		// this HAS to be 0!
	fpb->ioDirID   = folder.parID;
	fpb->ioVRefNum = folder.vRefNum;
	fpb->ioNamePtr = folder.name;
	err = PBGetCatInfo(&pb, false);

	fpb->ioNamePtr = name;
	fpb->ioFDirIndex = index;
	err = PBGetCatInfo(&pb, false);
	if (err == noErr) {
		err = FSMakeFSSpec(fpb->ioVRefNum, fpb->ioFlParID,
			fpb->ioNamePtr, file);
	}

	if (err != noErr)
		file->name[0] = 0;
}

/****
 *	ItemIsFolder
 *
 *	Given an FSSpec, this routine returns true if the
 *	FSSpec is for a folder; false otherwise.
 *
 ****/

Boolean	ItemIsFolder(FSSpec file)
{
	CInfoPBRec	pb;
	HFileInfo	*fpb = (HFileInfo *)&pb;	/* to pointers */
	OSErr		err;

	fpb->ioFDirIndex = 0;		// this HAS to be 0!
	fpb->ioDirID   = file.parID;
	fpb->ioVRefNum = file.vRefNum;
	fpb->ioNamePtr = file.name;
	err = PBGetCatInfo(&pb, false);
	if ((err == noErr) && !(fpb->ioFlAttrib & 16))
		return false;
	else
		return true;
}
