/*
   <p>Add an extension to a filename that does not have one.</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 <stdio.h>
#include "environ.h"

#ifdef OS9
#include <strings.h>
#define SEP '/'
#endif

#ifdef MSDOS
#include <string.h>
#define index strchr
#define rindex strrchr
#define SEP '\\'
#endif

#ifdef LINUX
#include <string.h>
#define SEP '/'
#endif

#ifndef NULL
#define    NULL    (char*)(0)
#endif

/*
   Complete a filename by adding a default extension if needed.
   
   If <u>name</u> doesn't have an extension, append a '.' followed
   by <u>ext</u>, putting the result in <u>fullname</u>, which must
   be large enough to contain the completed name plus the string
   terminator. A pointer to <u>fullname</u> is returned.
*/
char *strmfe(char *fullname, char *name, char *ext)
{
    char*    ptr;
    char*    savptr;

    /*
        Validate inputs
    */

    if (name == NULL)
        name = "";

    if (ext == NULL)    
    	ext = "";
    	
    /*
        Copy name to output.
    */
    strcpy(fullname,name);

    /*
        Find the last SEP in the name. If none, point
        to the start of name. Skip leading '.'s, but if
        this reaches the end of the string, backtrack on
        the '.' skipping.
    */
    if (ptr = rindex(name, SEP))
        ptr++;
    else
        ptr = name;
    savptr = ptr;
    while (*ptr == '.')
        ptr++;
    if (!(*ptr))
        ptr = savptr;

    /*
        Examine the remaining portion of the name, which
        should be effectively a local name. If it has
        no extension (recognised by the presense of '.')
        append the default extension and return a pointer
        to the result.
    */
    if (index(ptr,'.') == 0)
    {
        strcat(fullname,".");
        strcat(fullname,ext);
    }
    return fullname;
}
