#include <string.h>
#include <stdlib.h>
#include <dos.h>

#define MAX_NAME 17
#define MAX_STR 133
#define MAX_ENV 50

struct equiv {
             char *name;
             char *str;
             };

int nenv;
struct equiv envrec[MAX_ENV];

char *envptr()
{
   short pspseg,envseg,errseg;
   char *psp,*env,*err;
   pspseg = _psp;
   psp = (char *) (pspseg*65536);
   errseg = *((short *)(psp+0x14));
   err = (char *) (errseg*65536);
   envseg = *((short *)(err+0x2c));
   env = (char *) (envseg*65536);
   return env;
}

void envinit()
{
   char *env,*wrk;
   nenv = 0;
   env = envptr();
   while (*env!='\0') {
      wrk = envrec[nenv].name = malloc(MAX_NAME);
      while (*env!='=') {
         *wrk = *env;
         wrk++; env++;
      }
      env++;
      *wrk = '\0';
      wrk = envrec[nenv].str = malloc(MAX_STR);
      while (*env!='\0') {
         *wrk = *env;
         wrk++; env++;
      }
      env++;
      *wrk = '\0';
      nenv++;
   }
   return;
}

void envend()
{
   char *env,*wrk;
   int i;
   env = envptr();
   for (i=0;i<nenv;i++) {
      wrk = envrec[i].name;
      while (*wrk!='\0') {
         *env = *wrk;
         env++; wrk++;
      }
      *env = '=';
      env++;
      wrk = envrec[i].str;
      while (*wrk!='\0') {
         *env = *wrk;
         env++; wrk++;
      }
      *env = '\0';
      env++;
   }
   *env = '\0';
   return;
}

void envput(char *name,char *str)
{
   int i;
   for (i=0;i<nenv;i++) {
      if (strcmp(name,envrec[i].name)==0) {
         strcpy(envrec[i].str,str);
         return;
      }
   }
   envrec[nenv].name = malloc(MAX_NAME);
   strcpy(envrec[nenv].name,name);
   envrec[nenv].str = malloc(MAX_STR);
   strcpy(envrec[nenv].str,str);
   nenv++;
   return;
}

int envget(char *name,char *str)
{
   int i;
   for (i=0;i<nenv;i++) {
      if (strcmp(name,envrec[i].name)==0) {
         strcpy(str,envrec[i].str);
         return 1;
      }
   }
   return 0;
}
