/* 
   Copyright 1994-2003 Free Software Foundation, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library 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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 
   USA

   You may contact the author at:

   mailto::camille@bluegrass.net

   or by snail mail at:

   David Lindauer
   850 Washburn Ave Apt 99
   Louisville, KY 40222
*/
#include <windows.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#undef errno
#include <wchar.h>
#include <locale.h>
#include "libp.h"


static int __rtlTlsIndex ;
static struct __rtl_data *rd;

void __threadinit(void)
{
    __rtlTlsIndex = TlsAlloc();
}
void __threadrundown(void)
{
    TlsFree(__rtlTlsIndex);
}
struct __rtl_data *__threadTlsAlloc(int cs)
{
    HLOCAL data = LocalAlloc(LPTR,sizeof(struct __rtl_data));
    struct __rtl_data *rv ;
    if (!data) {
        printf(stderr,"out of memory");
        abort();
    }
    rv = LocalLock(data);
    rv->handle = (void *)data;
    TlsSetValue(__rtlTlsIndex,(void *)rv);
    if (cs)
        __ll_enter_critical();
    rv->link = rd ;
    rd = rv ;
    if (cs)
        __ll_exit_critical();
    return rv;
}
void __threadTlsFree(int cs)
{
    struct __rtl_data *rv = TlsGetValue(__rtlTlsIndex) , **list = &rd;
    if (rv) {
        HLOCAL handle = rv->handle;
        if (cs)
            __ll_enter_critical();
        while (*list) {
            if (*list == rv) {
                *list = (*list)->link;
                break;
            }
            list = &(*list)->link;
        }
        if (cs)
            __ll_exit_critical();
        LocalUnlock(handle);
        LocalFree(handle);
    }
    TlsSetValue(__rtlTlsIndex,0);
}
void __threadTlsFreeAll(void)
{
    while (rd) {
        struct __rtl_data *next = rd->link;
        HLOCAL handle = rd->handle;
        LocalUnlock(handle);
        LocalFree(handle);
        rd = next;
    }
}
struct __rtl_data *__getRtlData(void)
{
    struct __rtl_data *rv = (struct __rtl_data *)TlsGetValue(__rtlTlsIndex);
    if (!rv)
        rv = __threadTlsAlloc(TRUE);
    return rv;
}

