/*
 * LowCase v1.1 ©1998 Duncan Strand.
 *
 * Renames the given file so that it is all lower case.
 *
 * Problems?
 *
 *   None known.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <exec/types.h>
#include <utility/utility.h>

#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/utility.h>


void about(void);
void closeprog(void);

struct Library *UtilityBase=NULL;

void about()
{
    puts("$VER: LowCase v1.1. ©1998 Duncan Strand.\nlowercase <filename>");
}

void closeprog(void)
{
    CloseLibrary(UtilityBase);
    return;
}

int main(int argc, char *argv[])
{
    BOOL ok;

    char oldname[108];
    char newname[108]="newname";

    atexit(closeprog);

    register int wild, i, rval=0;//, len;

    if (!(UtilityBase = OpenLibrary("utility.library", 37)))
    {
        puts("Error: Need version 37+ of utility.library.");
        return 20;
    }

    // Did the user give no filename or a ?
    if(argc<2)
    {
        about();
        return 0;
    }

    if(!strncmp(argv[1],"?", 1) )
    {
        about();
        return 0;
        //exit(0);
    }

    int error = expand_args(argc, argv, &argc, &argv);
    if(error)
    {
        puts("Error parsing command line.");
        return 20;
    }

    for(wild=1; wild<argc; ++wild)
    {

        // Get file to rename
        strcpy(oldname,argv[wild]);

        // Lower the case
        for(i=0;i< strlen(oldname);i++)
            oldname[i]=ToLower(oldname[i]);


        strcpy(newname,oldname);
        // Rename the file:
        ok = Rename( oldname , newname );

        // Check if the file was successfully renamed
        if( !ok )
        {
            sprintf(newname, "Cannot rename \"%s\" because", oldname);
            PrintFault(IoErr(), newname);
            rval=10;
        }
    }
    return rval;

}
