/* env.pmc
 *  Copyright: 2001-2003 The Perl Foundation.  All Rights Reserved.
 *  CVS Info
 *     $Id: env.pmc,v 1.8 2003/08/25 09:46:23 leo Exp $
 *  Overview:
 *     These are the vtable functions for the Env base class, which
 *     accesses the system environment
 *  Data Structure and Algorithms:
 *  History:
 *  Notes:
 *  References:
 */

#include "parrot/parrot.h"

pmclass Env extends default {

    STRING* get_string_keyed(PMC* key) {
	char *keyname = string_to_cstring(interpreter,
		VTABLE_get_string(interpreter, key));
	int free_it;
	STRING *retval;
	char *val = NULL;

	if (keyname) {
	    val = Parrot_getenv(keyname, &free_it);
	    string_cstring_free(keyname);
	    if (val) {
		retval = string_from_cstring(interpreter, val, 0);
	    } else {
		retval = string_from_cstring(interpreter, "", 0);
	    }
	} else {
	    retval = string_from_cstring(interpreter, "", 0);
	}
	if (free_it) mem_sys_free(val);
        return retval;
    }

    void set_string_keyed(PMC* key, STRING* value) {
	char *keyname = string_to_cstring(interpreter,
		VTABLE_get_string(interpreter, key));
	char *env_val = string_to_cstring(interpreter, value);
	if (keyname && env_val) {
	    Parrot_setenv(keyname, env_val);
	}
	if (keyname) {
	    string_cstring_free(keyname);
	}
	if (env_val) {
	    string_cstring_free(env_val);
	}
    }

    INTVAL exists_keyed(PMC* key) {
      char *keyname = string_to_cstring(interpreter,
	      VTABLE_get_string(interpreter, key));
      int free_it;

      if (keyname) {
        char *val = Parrot_getenv(keyname, &free_it);
        string_cstring_free(keyname);
	if (val) {
	  if (free_it) mem_sys_free(val);
	  return 1;
	}
      }

      return 0;
    }

    void delete_keyed(PMC* key) {
      char *keyname = string_to_cstring(interpreter,
	      VTABLE_get_string(interpreter, key));

      if (keyname) {
        char *val = getenv(keyname);
	if (val) {
	  Parrot_unsetenv(keyname);
	}
        string_cstring_free(keyname);
      }
    }
}

