#include "mlib.h"
#include "mdebug.h"
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>

ALLOCATED char* extname(char* name)
{
    char* p;
    
    for(p = name + strlen(name); p != name; p--) {
        if(*p == '.') {
            return STRDUP(p+1);
        }
    }

    return STRDUP("");
}

ALLOCATED char* noextname(char* name)
{
    char* max;
    char* p;
    
    max = name + strlen(name);
    for(p = name; p < max; p++) {
        if(*p == '.') {
            char* result = (char*)MALLOC(p - name + 1);
            memcpy(result, name, p - name);
            result[p - name] = 0;
            return result;
        }
    }

    return STRDUP(name);
}


ALLOCATED char* parentname(char* path)
{
    char* p;
    
    if(strcmp(path, "/") == 0) return STRDUP("/");

    for(p=path + strlen(path)-2; p != path-1; p--) {
        if(*p == '/') {
            char* result = (char*)MALLOC(p-path + 2);
            memcpy(result, path, p-path);
            result[p-path] = '/';
            result[p-path+1] = 0;
            
            return result;
        }
    }

    return STRDUP("/");
}

ALLOCATED char* mygetcwd()
{
    int l;
    char* result;
    
    l = 50;
    result = (char*)MALLOC(l);
    
    while(!getcwd(result, l)) {
         l += 50;
         result = (char*)REALLOC(result, l);
    }

    return result;
}

char* mygetpwuid(struct stat* statbuf)
{
    struct passwd* ud;
    
    ud = getpwuid(statbuf->st_uid);
        
    if(ud)
        return ud->pw_name;
    else
        return NULL;
}

char* mygetgrgid(struct stat* statbuf)
{
    struct group* gd;

    gd = getgrgid(statbuf->st_gid);
    if(gd)
        return gd->gr_name;
    else
        return NULL;
}

