/***
*rmtmp.c - remove temporary files created by tmpfile.
*
*       Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
*
*******************************************************************************/

#include <cruntime.h>
#include <stdio.h>
#include <file2.h>
#include <internal.h>
#include <mtdll.h>


#ifdef _MSC_VER

#pragma data_seg(".CRT$XPX")

#ifdef _WIN32

static _PVFV pterm = _rmtmp;

#else  /* _WIN32 */
#if defined (_M_MPPC) || defined (_M_M68K)

static _PVFV __prmtmp = _rmtmp;

#endif  /* defined (_M_MPPC) || defined (_M_M68K) */
#endif  /* _WIN32 */

#pragma data_seg()

#endif  /* _MSC_VER */

#ifdef _WIN32

/*
 * Definitions for _tmpoff, _tempoff and _old_pfxlen. These will cause this
 * module to be linked in whenever the termination code needs it.
 */
#ifndef CRTDLL
unsigned _tmpoff = 1;
#endif  /* CRTDLL */

unsigned _tempoff = 1;
unsigned _old_pfxlen = 0;


#else  /* _WIN32 */
#if defined (_M_MPPC) || defined (_M_M68K)

/*
 * Definitions for _tmpoff, _tempoff and _old_pfxlen. These will cause this
 * module to be linked in whenever the termination code needs it.
 */
unsigned int _tmpoff = 1;
unsigned int _tempoff = 1;
unsigned int _old_pfxlen = 0;

/*
 * Define _prmtmp, the function pointer used in the termination code.
 */
void (__cdecl * _prmtmp)(void) = _rmtmp;

#endif  /* defined (_M_MPPC) || defined (_M_M68K) */
#endif  /* _WIN32 */


/***
*int _rmtmp() - closes and removes temp files created by tmpfile
*
*Purpose:
*       closes and deletes all open files that were created by tmpfile.
*
*Entry:
*       None.
*
*Exit:
*       returns number of streams closed
*
*Exceptions:
*
*******************************************************************************/

int __cdecl _rmtmp (
        void
        )
{
        REG2 int count = 0;

#ifdef _WIN32

        REG1 int i;

        _mlock(_IOB_SCAN_LOCK);

        for ( i = 0 ; i < _nstream ; i++)

                if ( __piob[i] != NULL ) {

                        _lock_str2(i, __piob[i]);

                        if ( inuse( (FILE *)__piob[i] ) &&
                             (((FILE *)__piob[i])->_tmpfname != NULL) )
                        {
                                _fclose_lk( __piob[i] );
                                count++;
                        }

                        _unlock_str2(i, __piob[i]);
                }

        _munlock(_IOB_SCAN_LOCK);

#else  /* _WIN32 */
#if defined (_M_MPPC) || defined (_M_M68K)

        REG1 FILE *stream = _iob;

        for (; stream <= _lastiob; stream++) {

                if (inuse(stream) && (stream->_tmpfname != NULL) ) {
                        fclose(stream);
                        count++;
                }
        }

#endif  /* defined (_M_MPPC) || defined (_M_M68K) */
#endif  /* _WIN32 */

        return(count);
}
