/* This file is part of Lcrzo.
*/

/*-------------------------------------------------------------*/
int lcrzo_priv_globalvars_close(void)
{ lcrzo_priv_globalvars *ptr;

  /* check for double close */
#if defined LCRZODEF_SYSTEM_Unix
  if (lcrzo_priv_globalvars_ptr==NULL) return(LCRZO_ERR_OK);
#elif defined LCRZODEF_SYSTEM_Windows
  LPVOID p;
  p=TlsGetValue(lcrzo_priv_globaltlsindex);
  if (p==NULL) return(LCRZO_ERR_OK);
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif

  lcrzo_er(lcrzo_priv_globalvars_ptr_get(&ptr));

  lcrzo_er(lcrzo_priv_confvars_close(&(ptr->confvars)));

  lcrzo_er(lcrzo_priv_randomvars_close(&(ptr->randomvars)));
  
  lcrzo_er(lcrzo_priv_staticvars_close(&(ptr->staticvars)));

  /* free stored data */
  if (ptr->errmsglcrzo!=NULL)
  { lcrzo_er(lcrzo_string_free(ptr->errmsglcrzo));
  }
  if (ptr->errmsgsys!=NULL)
  { lcrzo_er(lcrzo_string_free(ptr->errmsgsys));
  }

  /* free global zone */
#if defined LCRZODEF_SYSTEM_Unix
  lcrzo_er(lcrzo_data_free((lcrzo_data)ptr));
#elif defined LCRZODEF_SYSTEM_Windows
  if (LocalFree(ptr)!=NULL)
    return(LCRZO_ERR_FULOCALFREE);
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif

  /* set close */
#if defined LCRZODEF_SYSTEM_Unix
  lcrzo_priv_globalvars_ptr=NULL;
#elif defined LCRZODEF_SYSTEM_Windows
  { BOOL err;
    err=TlsSetValue(lcrzo_priv_globaltlsindex, NULL);
    if (!err) return(LCRZO_ERR_FUTLSSETVALUE);
  }
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif

  return(LCRZO_ERR_OK);
}

