/***************************************************************************** 
  This function takes as input the name of an operating systems enviroment 
  variable (evar) and returns the value (val).

  Input: 
        evar[]   -Env. var. name. eg. HOME
        levar    -evar string length (NOT PHYSICAL LEN.)
        lval     -The physical len. of val[].
  Output:
        val[]    -String containing the value held in the evar[] eg. /home/joe
        flg      -Error flag.
  ERRORS:
        flg = -1 -Length of string provided is too small for env. value.
        flg = -2 -Variable (evar) has no value.

******************************************************************************/
#include <stdlib.h> 
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>

void envarc_( char evar[ ], int* levar, char val[ ],int* lval,int* flg,char errorstr[], int* lerr )
{
    char* value;
    int dperrno;
    DIR* dp;
   *flg = -99;
    evar[*levar]='\0';      /* NULL terminating FORTRAN string for C use*/
    memset(val,32,*lval);   /* BLANK (ASCI(32)) padding C string for FORTRAN use*/
    memset(errorstr,32,*lerr);
    value = getenv(evar);

    if(value){ 
        if(*lval < strlen(value)){
           *flg = -1;   /* val too short */
            return;
        }
        dp = opendir(value);
        dperrno = errno;
        if(dp == NULL){
            printf("dperrno = %d \n",dperrno);
            if(dperrno == 2){                                 /* No such file or directory */
                if(mkdir( value, S_IRUSR|S_IWUSR|S_IXUSR) != 0){
                    memcpy(errorstr,strerror(errno),strlen(strerror(errno)));
                   *flg = -4; 
                    return;
                }else{
                   *flg = 0;
                    memcpy(val,value,strlen(getenv(evar)));
                    return;
                } 
            }else{
                memcpy(errorstr,strerror(dperrno),strlen(strerror(dperrno)));
               *flg = -3;
                return;
            }
        }else{
            memcpy(val,value,strlen(getenv(evar)));
           *flg = 0;
            closedir(dp);
            return;
        }
    }else{
       *flg = -2;   /* val has no value */
        return;
    } 
}
