// (c) 1990-2007 Electronic Arts Inc.

const char *SPIT_history[] =
{
"------------------------------------------------------------------",
"                                                                  ",
"                          ZRename v1.06                           ",
"                                                                  ",
"                     by FrANK G. Barchard, EAC                    ",
"                                                                  ",
"                    Main program - Sep 19, 2001                   ",
"                                                                  ",
"------------------------------------------------------------------",
"                                                                  ",
" Version Date   SE History:                                       ",
" ------- ------ -- --------                                       ",
"    1.00 940408 FB zrename for hash renaming to pc filenames      ",
"    1.01 940413 FB show intermediate name                         ",
"    1.02 940520 FB -v2 shows just name per line                   ",
"    1.03 981117 FB improved error messages                        ",
"    1.04 990215 FB try intermediate rename                        ",
"    1.05 000919 FB -hash0 default disables hashing                ",
"    1.06 010919 FB -hash0 dont free hash table if not allocated   ",
"                                                                  ",
"------------------------------------------------------------------",
"\0"
};

/****************************************************************/
/*  Spit Setup                                                  */
/****************************************************************/

const char TextVersion[]="1.06 (Samba) 2007.12.4";
#define TOOL_VERSION 106
#define TOOL_NAME "zrename"

#include "spit.h"
#include "hashidi.cpp"
#include "wildmatch.h"

int OPTmaxidlen;
int OPTmaxstrings;
int OPTtolower;


static const char * ZRENAME_filename(const char *s)
{
    const char *l=s;

    while (*s)
    {
        if (*s==(char)'\\' || *s==':' || *s=='/')
            l = s+1;
        ++s;
    }
    return(l);
}


#if 0
;
; ABSTRACT
;
; zrename - renames filenames using spit rules and hashing
;
; SUMMARY
;
; zrename -options <sourcestrings>
;   @file     response file, containing a list of options and strings
;   =file     specify a output file ie: source=dest
;   -l        specify length of id (default 4)
;   -n        specify max number of shapes (default 255)
;   -v0       no console output
;   -v1       prints source file name and errors
;   -v2       status line for each file (default)
;   -v3       additional information
;   -r        recurse subdirectories
;
; DESCRIPTION
;
; The program zrename converts int filename strings to smaller ids by removing
; unneeded characters.
;
; RETURNS
;
; Number of files renamed.
;
; SEE ALSO
;
; cel2shp
;
; SAMPLE OUTPUT
;
; > zrename testfile testfile2 testfile3
; zrename v1.00 (bunny) 940331 by Gerry Shaw, EAC
; testfile = tstf
; testfile2 = tst2
; testfile3 = tst3
;
; END ABSTRACT
;
#endif

void SPIT_reset(void)
{
    OPTmaxidlen = 0;
    OPTmaxstrings = 4096;   /* 4096 names otta do it! */
    OPTtolower = 0;
}

/* SPIT routines */

void SPIT_usage(const char *prgname, const char *envname, const char *urlname, int utype)
{
    printf("ZRename v%s by FrANK Barchard, EAC\n", TextVersion);
    if (utype)
        printf("USAGE: %s -options [oldfilenames]=[newnames]\n", prgname);

    switch (utype)
    {
        case 2:
              puts("    -l  length of hashed name    -n  number of unique files");
              puts("    -r  recurse subdirectories    &  response file");
              puts("    -math math expression         =  output file");
            printf("type '%s -h' for more help\n", prgname);
          printf("type '%s -help' for web page (%s)\n", prgname, urlname);
            exit(0);

        case 3:
              puts("");
            printf("VERSION: %s v%s, Spit v%.2f\n", SPIT_MACHINE, TextVersion, (float)SPIT_VERSION/100.0f);
              puts("SUMMARY: zrename renames files");
            printf("         SPIT environment variable is %s\n", envname);
              puts("");
              puts("    @file     response file, containing a list of options and files");
            printf("    =file     specify a output file ie %s source=dest\n", prgname);
              puts("    -l        specify length of id (default 256)");
              puts("    -tolower  lower case filenames");
              puts("    -math     enter math expression on # wildcards (ex. -math#[0]=#[0]*3)");
              puts("    -n        specify max number of shapes (default 255)");
              puts("    -v0       no console output");
              puts("    -v1       prints source file name and errors");
              puts("    -v2       status line for each file (default)");
              puts("    -v3       additional information");
              puts("    -r        recurse subdirectories");
            exit(0);

        default:
            break;
    }
}


char *SPIT_opt(const char *optptr)
{
    char *d=(char *)0;

    switch (*optptr | (char)' ')
    {
        case 'l':
            d = SPIT_getopt( &OPTmaxidlen,optptr+1, "Maximum ID length", 1, 256);
            break;

        case 'n':
            d = SPIT_getopt( &OPTmaxstrings,optptr+1, "Maximum strings", 1, 256);
            break;

        case 'm':
            if (!strnicmp(optptr, "math", 4))
            {
                char math[SPITMAXLINE];
                d = SPIT_getstropt( math,optptr+4, "math rule", "", SPITYES, SPITMAXLINE);
                WILD_addmathrule(math);
            }
            break;

        case 't':
            if (!strnicmp(optptr, "tolower", 7))
            {
                d = SPIT_getopt( &OPTtolower,optptr+7, "name to lower case", 0, 1);
            }
            break;

        default:;
    }
    return(d);
}

int main(int argc, char* argv[])
{
    int more;
    int i;
    int err;

    SPIT_init(SPIT_reset, SPIT_usage, SPIT_opt, SPIT_history);
    do
    {
        more = SPIT_parse(argc, argv, TOOL_NAME, TOOL_VERSION);

        if (OPTmaxidlen)
            HASHID_init(OPTmaxstrings, OPTmaxidlen, 0, 1);

        for (i=0; i<SPITargnum; ++i)
        {
            char newname[SPITMAXLINE];
            char *filename;

            strcpy(newname,SPITdargv[i]);
            if (OPTtolower)
                strlwr(newname);
            filename = (char *)ZRENAME_filename(newname);

            if (OPTmaxidlen)
                HASHID_apply(filename, filename);

            if (OPTverbose>=2)
            {
                if (OPTverbose>=3)
                    printf("%s <- %s <- %s\n", newname, SPITdargv[i], SPITsargv[i]);
                else
                    printf("%s, ", newname);
                SPIT_flush();
            }

            err = 0;
            if (OPTwrite)
            {
                err = rename(SPITsargv[i],newname);
                if (err)
                {
                    char tempnewname[SPITMAXLINE];
                    strcpy(tempnewname,newname);
                    strcat(tempnewname,".tmp");
                    err = rename(SPITsargv[i],tempnewname);
                    if (!err)
                    {
                        err = rename(tempnewname,newname);
                        if (err)
                        {
                            int t = err;
                            err = rename(tempnewname,SPITsargv[i]);
                            if (err)
                                printf("zrename - ERROR RENAMING '%s' to '%s'\n", tempnewname,SPITsargv[i]);
                            err = t;
                        }
                    }
                }
            }

            if (err)
            {
                if (OPTverbose>=2)
                {
                    if (OPTverbose>=3)
                        printf("zrename - ERROR RENAMING '%s' to '%s'\n", SPITsargv[i],newname);
                    else
                        printf("ERROR. ");
                    SPIT_flush();
                }
            }
        }
        if (OPTmaxidlen)
            HASHID_restore();
        WILD_deletemathrules();
    } while (more>0);

    return(i);
}

