#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>
#include <malloc.h>
#include "proctitleutils.h"

/* Globals */
static char **Argv = ((void *)0);
static int maxlength = 0;
static int start = 0;

void init_set_proc_title(int argc, char *argv[], char *envp[], const char *name)
{
  int i;
  extern char **environ;
  char **p;
  char *ptr;

  // Get the maximum length
  for(i = 0; argv[i] != NULL; i++)
    maxlength += strlen(argv[i]) + 1;
  for(i = 0; envp[i] != NULL; i++)
    maxlength += strlen(envp[i]) + 1;
  
  if((p = (char **) malloc((i + 1) * sizeof(char *))) != NULL ) {
    environ = p;

    for(i = 0; envp[i] != NULL; i++) {
      if((environ[i] = malloc(strlen(envp[i]) + 1)) != NULL)
         strcpy(environ[i], envp[i]);
    }
    
    environ[i] = NULL;
  }

  Argv = argv;
    
  // Clear the title (from the start of argv to the start of envp)
  // All command line arguments should have been taken care of by now...
  for(ptr=Argv[0]; ptr<envp[0]; ptr++)
    *ptr='\0';
    
  set_proc_title("%s : ", name);
  start=strlen(name)+3;    // 3 = " : "
  maxlength-=start+1;
}

void set_proc_title(char *fmt,...)
{
  va_list msg;
  static char statbuf[512];
  char *p = Argv[0];

  // Clear old Argv[0]
  for(p+=start;*p; p++)
    *p='\0';
   
  va_start(msg,fmt);
  memset(statbuf, 0, sizeof(statbuf));
  vsnprintf(statbuf, sizeof(statbuf), fmt, msg);
  va_end(msg);

  snprintf(Argv[0]+start, maxlength, "%s", statbuf);
  
  Argv[1] = ((void *)0) ;
}


