// This may look like C code, but it is really -*- C++ -*-
//
// $Id: utils.cc,v 1.1.1.1 1999-11-26 16:37:12 ansari Exp $
//

#include "machdefs.h"
#include "utils.h"
#include "pexceptions.h"
#include <string.h>

// MemCpy marche meme en cas de recouvrement.
void* MemCpy(void* dest, const void* source, size_t n)
{
  int i;   // THINK C ne veut pas du int i dans chaque for...
  if (dest < source)
    for (i=0; i<n; i++)
      ((char*)dest)[i] = ((char*)source)[i];
  else 
    for (i=n-1; i>=0; i--)
      ((char*)dest)[i] = ((char*)source)[i];
  
  return dest;
}

// Dans parmst.cc
//int PrtLevel = 0;
//int DebugLevel = 0;

char const* PeidaWorkPath()
{
  char const* envWP = getenv("PEIDAWORKPATH");
  if (envWP) return envWP;
  #ifdef __mac__
  return "WORK";
  #endif
  return ".";
}

#ifndef __mac__
void buildPath(char* dst, const char* dir, const char* file)
{
  strcpy(dst, dir);
  char *p = dst; while (*p) p++; p--;
  if (*dir && *p != '/') strcat(dst, "/");
  strcat(dst, file);
}

void buildPath(string& dst, const string& dir, const string& file)
{
  dst = dir;
  if (dir != "" && dir[dir.length()-1] != '/') dst += "/";
  dst += file;
}

#else
void buildPath(char* dst, const char* dir, const char* file)
{
  if (*dir) {
    strcpy(dst, ":");
    strcat(dst, dir);
    char *p = dst; while (*p) p++; p--;
    strcat(dst, ":");
    strcat(dst, file);
  } else
    strcpy(dst, file);
}

void buildPath(string& dst, const string& dir, const string& file)
{
  if (dir != "") {
    dst = ":" + dir + ":" + file;
  } else
    dst = file;
}

#endif


void changeSuffix(char* file, const char* suffix)
{
  char *p = file;
  while (*p) p++;
  while (*p != '.' && p > file) p--;
  if (*p != '.') 
    strcat(file, suffix);
  else
    strcpy(p,suffix);
}

void changeSuffix(string& file, const string& suffix)
{
  size_t pos = file.rfind('.');
  //  if (pos != NPOS) file.remove(pos);
  if (pos != NPOS) file = file.substr(0,pos);
  file += suffix;
}

string itos(int i)
{
  char s[20];
  sprintf(s, "%d", i);
  return s;
}

string ftos(double f)
{
  char s[20];
  sprintf(s, "%g", f);
  return s;
}


