/*
   <p>Set the filename extension to that provided.</p>

   <kbd>
   <b>environ - C programming support functions</b><br>
   Copyright (C) 2005  Martin C Gregorie
   
   This program is free software; you can redistribute it and/or
   modify it under the terms of the Lesser GNU General Public License.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
  
   You should have received a copy of the Lesser GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
   </kbd>
  
   <p>Contact Martin Gregorie at <i>martin@gregorie.org</i></p>
*/

#include "environ.h"

#ifdef OS9
#include <strings.h>
#endif

#ifdef MSDOS
#include <string.h>
#endif

#ifdef LINUX
#include <string.h>
#include <stdlib.h>
#endif

/*
   Set the filename extension to that provided.
   If <u>name</u> is "." or ".." it is returned unchanged.
   If <u>name</u> has no extension a dot and <u>ext</u>
   are appended to it. If the file already has an extension
   it is replaced with <u>ext</u>.
   The revised name is in a hidden place;
   a pointer to it is returned. If <i>fixext()</i> is
   called repeatedly this space should be
   released as soon as possible by calling <i>free()</i>.

   The function returns the modified filename
   on success and null on failure.

*/
char* fixext(char *name, char *ext)
{
    char   *t;
    int    i;
    int    n;
    
    n = strlen(name);
    t = (char*)malloc(n+strlen(ext)+3);
    if (t == NULL)
        return (NULL);
        
    strcpy(t,name);
    for (i=n-1; i>=0; i--)
        if (t[i] == '.')
            break;

    if (strcmp(t,".") == 0 || strcmp(t,"..") == 0)
        return(t);
    if (i == 0)
        i = -1;           /* .xxxx treated as xxxx */
    if (i == -1)
        strcat(t,".");    /* no .ext found */
    else
        t[i+1] = 0;       /* remove extension */
    strcat(t,ext);        /* append new extension */
    return(t);
}            
