#include <ncbi.h>
#include <gishlib.h>
#ifdef OS_UNIX
#include <fcntl.h>
#endif

/* SameFp -- TRUE if two file pointers describe the same I/O channel */

int LIBCALL
SameFp(fp1, fp2)
	FILE	*fp1, *fp2;
{
	if (fp1 == NULL || fp2 == NULL)
		return FALSE;
#ifdef OS_UNIX
	return SameFd(fileno(fp1), fileno(fp2));
#else
	return fp1 == fp2;
#endif
}

/* SameFd -- TRUE if two file descriptors describe the same I/O channel */
/*
Strategy:  obtain the flags associated with the two file descriptors;
test whether changing the flags for one descriptor produces a corresponding
change in the other descriptor.
*/
int LIBCALL
SameFd(fd1, fd2)
	int	fd1, fd2;
{
#if defined(OS_UNIX) && defined(O_NDELAY)
	int	flags1, flags1_new, flags2_new;

	if (fd1 == -1 || fd2 == -1)
		return FALSE;

	if (fd1 == fd2)
		return TRUE;
	if ((flags1 = fcntl(fd1, F_GETFL)) == -1)
		return FALSE;
	if (flags1 != fcntl(fd2, F_GETFL))
		return FALSE;

	/* Set new flags on fd1 */
	flags1_new = flags1^(O_NDELAY);
	fcntl(fd1, F_SETFL, flags1_new);

	/* Get flags for fd2 to see if they also changed */
	flags2_new = fcntl(fd2, F_GETFL);

	/* Restore previous flags on fd1 (and fd2 if they are the same) */
	fcntl(fd1, F_SETFL, flags1);

	return flags2_new == flags1_new;
#else
	if (fd1 == -1 || fd2 == -1)
		return FALSE;
	return fd1 == fd2;
#endif
}

