/* makename.c
 *
 * Set up filename for output file.
 *  Used by both ms2smus and smus2ms
 *  Note: should strip all but last component of path
 *   when making new name.... /intro.song as source makes /intro.smus dest.
 */

#include "smus.h"
#include "music.h"

#define  MAX_DIR_LEN  64 
#define  MAX_SUFFIX_LEN 7     /* maximum # of chars in suffix */
                              /* longest suffix = ".sound" */

extern char *strncat();
extern char *strncpy();

static char NewName[MAX_DIR_LEN+MS_NAME_MAX+MAX_SUFFIX_LEN];

/*
 *  Make an input filename by removing all chars after
 *   the last period, and replacing them with the given suffix
 */
char *
MakeInName(InName,Suffix)
   char  *InName;
   char  *Suffix;
{
   int   PrefixLen;                    /* length of name before ".song" */
   int   InNameLen;                    /* length of filename */

      /* find length of input filename */
   InNameLen = strlen(InName)-1;
   if (InNameLen > MS_NAME_MAX)
      InNameLen = MS_NAME_MAX;

      /* Remove suffix from input filename */
   PrefixLen = InNameLen;
   while ((InName[PrefixLen] != '.') && (PrefixLen > 0))   /* find "." */
      PrefixLen--;
      /* set up name of file to be created */
   if (PrefixLen == 0)                 /* if no "." in input filename */
      PrefixLen = InNameLen+1;         /* then use entire filname */

   (VOID) strncpy(NewName,InName,PrefixLen);  /* copy up to "." */
   (VOID) strncat(NewName,Suffix,MAX_SUFFIX_LEN);
   return(NewName);
} /* MakeInName */

static char OutName[MAX_DIR_LEN+MS_NAME_MAX+MAX_SUFFIX_LEN];

/*
 * Strip the suffix and prefix off the input filename
 *  and replace it with a new suffix and prefix.
 */
char *
MakeName(InName,Dir,Suffix)
   char  *InName;
   char  *Dir;
   char  *Suffix;
{
   int   PrefixSt;
   char  *Name;

   Name =  MakeInName(InName,Suffix);   /* replace suffix first */

   PrefixSt = strlen(Name) - 1;
   while ((Name[PrefixSt] != '/') &&   /* and look for path chars */
          (Name[PrefixSt] != ':') &&
          (PrefixSt > 0))
      PrefixSt --;

      /* bump name pointer past pathname stuff, also reduces length */
   if ((InName[PrefixSt] == '/') || (InName[PrefixSt] == ':'))
      Name += PrefixSt + 1;

   if ((Dir != NULL) && (strlen(Dir) > 0))
   {
      (VOID) strncpy(OutName,Dir,strlen(Dir));
      (VOID) strncat(OutName,"/",1);
   }
   else
      (VOID) strncpy(OutName,":",1);

   (VOID) strncat(OutName,Name,strlen(Name));  /* copy up to "." */

   return(OutName);
} /* MakeName */


char  mshed[] = { " Mstudio " };
         /*        012345678       */

/*
 *  Check to see if SongPtr points to the start
 *   of a valid Music Studio file
 */
BOOL
IsMSFile(SongPtr)
   char  *SongPtr;
{
   int   i;

   mshed[0] = 0xCE;
   mshed[8] = 0xCE;
   for (i = 0; i < 9; i++)
      if (*SongPtr++ != mshed[i])
         return(FALSE);
   return(TRUE);
}

