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

const char *SPIT_history[] =
{
"------------------------------------------------------------------",
"                                                                  ",
"                            Ztee v1.02                            ",
"                                                                  ",
"                    by FrANK G. Barchard, EAC                     ",
"                                                                  ",
"                   Main program - Mar 16, 2004                    ",
"                                                                  ",
"------------------------------------------------------------------",
"                                                                  ",
" Version Date   SE History:                                       ",
" ------- ----   -- --------                                       ",
" 1.00    050308 FB tee work alike for fifa                        ",
" 1.01    050316 FB title, no eof in file, fixed linecount         ",
" 1.02    050403 FB time goes to log file as well                  ",
"                                                                  ",
"------------------------------------------------------------------",
"\0"
};


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

#if defined(_MSC_VER)
#include "windows.h"        // SetConsoleTitle
#endif
#include "spit.h"
#include "stdgimex.h"
#include "ranger.h"
#include <stdio.h>

const char TextVersion[]="1.02 (Samba) 2007.12.4";
#define TOOL_VERSION 102
#define TOOL_NAME "ztee"

char OPTreturn[SPITMAXLINE];
int OPTappend;

/*
;
; ABSTRACT
;
; ztee - redirect stdin (pipe) to a file as well as stdout
;
; SUMMARY
;
; ztee -options [files]
;
;     @file          response file, containing a list of options and files
;     =file          specify a output file ie source=dest
;     -b0            disable banner
;     -v0            no console output
;     -v1            less output (no title or console output)
;     -v2            normal output (default)
;     -v             more output (aka -v3) - shows ztee on title bar
;     -v4            more output - shows line count
;     -w0            dont output file
;     -w             write output file (default)
;     -a0            create file instead of appending to existing new file (default)
;     -a             append to existing file instead of creating a new file
;     -r             recurse subdirectories to find files
;     -r%ENV%        traverse environment variable ENV to find files
;     -time          show execution time
;     -return<expr>  return expression (default errorcount)
;                    variables available:
;                      errorcount
;                      TOOL_VERSION
;                      SPIT_VERSION
;
; DESCRIPTION
;
; Ztee takes stdin and sends it to a file, stdout and/or the title bar
;
; RETURNS
;
; error count by default (0 for no errors)
; -return value if specified
;
; SEE ALSO
;
; huff, Spit
;
; SAMPLE OUTPUT
;
; >mk pc | ztee build.txt -time
;
; ztee.cpp
; linking ztee
; chunktoavi.cpp
; linking chunktoavi
; vid2div.cpp
; linking vid2div
; sony2dvd.cpp
; linking sony2dvd
; dvdmap.cpp
; linking dvdmap
; PerlApp 6.0.0 build 117102
; Copyright (C) 1998-2004 ActiveState Corp.  All rights reserved.
; ActiveState is a division of Sophos Plc.
; Commercial license for frank barchard <FBarchard@ea.com>
;
; Created 'du.exe'
; PerlApp 6.0.0 build 117102
; Copyright (C) 1998-2004 ActiveState Corp.  All rights reserved.
; ActiveState is a division of Sophos Plc.
; Commercial license for frank barchard <FBarchard@ea.com>
;
; Created 'cdu.exe'
; PerlApp 6.0.0 build 117102
; Copyright (C) 1998-2004 ActiveState Corp.  All rights reserved.
; ActiveState is a division of Sophos Plc.
; Commercial license for frank barchard <FBarchard@ea.com>
;
; Created 'paddvd.exe'
;  TIME ztee 34844.00 ms (34.84 seconds)
;
;
; END ABSTRACT
;
*/

/****************************************************************/
/*  SPIT Routines                                               */
/****************************************************************/

void SPIT_reset(void)
{
    OPTkeepopts = 1;
    OPTtime = 0;
    OPTappend = 0;
    strcpy(OPTreturn,"");

    return;
}

char *optionhelp[]=
{
    "    @file          response file, containing a list of options and files\n",
    "    =file          specify a output file ie source=dest\n",
    "    -b0            disable banner\n",
    "    -v0            no console output\n"
    "    -v1            less output (no title or console output)\n"
    "    -v2            normal output (default)\n"
    "    -v             more output (aka -v3) - shows ztee on title bar\n"
    "    -v4            more output - shows line count\n",
    "    -w0            dont output file\n",
    "    -w             write output file (default)\n",
    "    -a0            create file instead of appending to existing new file (default)\n",
    "    -a             append to existing file instead of creating a new file\n",
    "    -r             recurse subdirectories to find files\n"
    "    -r%ENV%        traverse environment variable ENV to find files\n",
    "    -time          show execution time\n",
    "    -return<expr>  return expression (default errorcount)\n"
    "                   variables available:\n"
    "                     errorcount\n"
    "                     linecount\n"
    "                     TOOL_VERSION\n"
    "                     SPIT_VERSION\n",
    "\n",
    0,
};

void SPIT_usage(const char *prgname, const char *envname, const char *urlname, int utype)
{
    char **hlp;

    if (((OPTverbose>=2 && utype==2) || OPTverbose>=4))
        printf("zTee v%s by FrANK G. Barchard\n",TextVersion);


    if (utype)
        printf("USAGE: %s -options [files]\n", prgname);

    switch (utype)
    {
        case 0:
        case 1:
            break;

        case 2:
            puts("    -time time execution         -return value");
            puts("    -v verbose                   -w write file");
            puts("    -a append");
            puts("     @ response file              = output file");
          printf("type '%s -h' for more help\n", prgname);
          printf("type '%s -help' for web page (%s)\n", prgname, urlname);
            break;

        case 3:
            puts("");
          printf("VERSION: %s v%s, Spit v%.2f\n",SPIT_MACHINE,TextVersion,(float)SPIT_VERSION/100.0f);
            puts("SUMMARY: Redirect stdin (pipe) to a file as well as stdout");
          printf("         SPIT environment variable is %s\n",envname);
            puts("");

            hlp = optionhelp;
            while (*hlp)
            {
                printf("%s",*hlp);
                ++hlp;
            }
            break;

         case 4:
            puts("");
            {
                hlp = optionhelp;
                while (*hlp)
                {
                    if (SPIT_strstr(*hlp,envname))
                        printf("%s",*hlp);
                    ++hlp;
                }
                puts("");
            }
            break;

        default:
            break;
    }
}

char *SPIT_opt(const char* optptr)
{
    char *d=NULL;
    switch (tolower(*optptr))
    {
        case 'a':
            d = SPIT_getopt( &OPTappend,optptr+1, "append to output file", 0, 1);
            break;

        case 'r':
            if (!strnicmp(optptr,"return",6))
            {
                d = SPIT_getfield( OPTreturn,optptr+6,1,0);
            }
            break;

        default:
            break;
    }
    return(d);
}

static void ZTEE_settitle(char *title)
{
#if defined(_MSC_VER)
    if (OPTverbose)
        SetConsoleTitle(title);
#endif
}

int main(int argc, char* argv[] /*, char **envp */ )
{
    int more;
    int i;
    int isopt;
    int errorcount=0;
    int linecount=0;

#if 0
    if (envp)
    {
        for (int i=0; envp[i]; ++i)
            printf("got env %s\n",envp[i]);
    }
#endif

    SPIT_init(SPIT_reset, SPIT_usage, SPIT_opt, SPIT_history);

    EXPR *expr = EXPR_open();

    do
    {
        more = SPIT_parse(argc, argv, TOOL_NAME, TOOL_VERSION);

        if (!SPIThelpgiven)
        {
            double totaltime = SPIT_gettime();

            // Open all output files

            FILE **outhandles = (FILE **) galloc(SPITargnum*sizeof(FILE *));

            for (i=0; i<SPITargnum; ++i)
            {
                outhandles[i] = (FILE *) 0;
                isopt = 0;
                if (SPITsargv[i][0]=='-' || SPITsargv[i][0]=='+' || (SPITsargv[i][0]==OPTdot && SPITsargv[i][1]!='.' && SPITsargv[i][1]!='/' && SPITsargv[i][1]!='\\'))
                {
                    isopt = Zop(SPITsargv[i]+1)?1:0;
                }
                else if (SPITsargv[i][0]=='=')
                {
                    isopt = Zop(SPITsargv[i])?1:0;
                }

                if (!isopt)
                {
                    if (OPTwrite)
                    {
                        if (OPTappend)
                            outhandles[i] = fopen(SPITdargv[i],"a");
                        else
                            outhandles[i] = fopen(SPITdargv[i],"w");
                        if (!outhandles[i])
                        {
                            if (OPTverbose>=1)
                                printf("ERROR ZTEE could not open logfile %s\n",SPITdargv[i]);
                            ++errorcount;
                        }
                    }
                }
            }

            // Main loop

            FILE *inhandle = stdin;
            FILE *outhandle = stdout;

            int lastc=0;

            const int MAXTITLE=256;
            char titlebuf[MAXTITLE+1]="ztee - ";
            int TITLESTARTINDEX = 7;
            if (OPTverbose<=2)
                TITLESTARTINDEX = 0;
            int titleindex=TITLESTARTINDEX;
            while (!feof(inhandle))
            {
                int c = fgetc(inhandle);
                if (c==EOF)
                    break;
                if (OPTverbose>=2)
                    fputc(c, outhandle);
                if ((c==10 || c==13) && c!=lastc)
                {
                    if (lastc==10 || lastc==13)
                        lastc = 0;
                    else
                    {
                        ++linecount;
                        titlebuf[titleindex] = 0;
                        if (OPTverbose>=2 && titleindex>TITLESTARTINDEX)
                            ZTEE_settitle(titlebuf);
                        titleindex = TITLESTARTINDEX;
                    }
                }
                else
                {
                    if (titleindex<MAXTITLE)
                    {
                        if (c>' ' || titleindex>TITLESTARTINDEX)    // skip leading tab/space
                        {
                            int tc=c;
                            if (tc=='\t') tc = ' ';
                            titlebuf[titleindex] = (char)tc;
                            ++titleindex;
                        }
                    }

                    lastc = c;
                }

                if (OPTwrite)
                {
                    for (i=0; i<SPITargnum; ++i)
                    {
                        if (outhandles[i])
                            fputc(c, outhandles[i]);
                    }
                }
            }

            // Timing goes to files

            totaltime = SPIT_gettime()-totaltime;
            if (OPTtime)
            {
                if (totaltime>=3600000.0)
                    printf("TIME " TOOL_NAME " %.2f ms (%.2f seconds) (%.2f minutes) (%.2f hours)\n",totaltime,totaltime/1000.0,totaltime/60000.0,totaltime/3600000.0);
                else if (totaltime>=60000.0)
                    printf("TIME " TOOL_NAME " %.2f ms (%.2f seconds) (%.2f minutes)\n",totaltime,totaltime/1000.0,totaltime/60000.0);
                else if (totaltime>=1000.0)
                    printf("TIME " TOOL_NAME " %.2f ms (%.2f seconds)\n",totaltime,totaltime/1000.0);
                else
                    printf("TIME " TOOL_NAME " %.2f ms\n",totaltime);

                if (OPTwrite)
                {
                    for (i=0; i<SPITargnum; ++i)
                    {
                        if (outhandles[i])
                        {
                            if (totaltime>=3600000.0)
                                fprintf(outhandles[i],"TIME " TOOL_NAME " %.2f ms (%.2f seconds) (%.2f minutes) (%.2f hours)\n",totaltime,totaltime/1000.0,totaltime/60000.0,totaltime/3600000.0);
                            else if (totaltime>=60000.0)
                                fprintf(outhandles[i],"TIME " TOOL_NAME " %.2f ms (%.2f seconds) (%.2f minutes)\n",totaltime,totaltime/1000.0,totaltime/60000.0);
                            else if (totaltime>=1000.0)
                                fprintf(outhandles[i],"TIME " TOOL_NAME " %.2f ms (%.2f seconds)\n",totaltime,totaltime/1000.0);
                            else
                                fprintf(outhandles[i],"TIME " TOOL_NAME " %.2f ms\n",totaltime);

                        }
                    }
                }
            }

            // Close files

            if (OPTwrite)
            {
                for (i=0; i<SPITargnum; ++i)
                {
                    if (outhandles[i])
                        fclose(outhandles[i]);
                }
            }
            gfree((void *)outhandles);
        }
    } while (more>0);


    static int olderrorlevel=0;
    {
        char *forcedriver;
        forcedriver = getenv("ERRORLEVEL");
        if (forcedriver)
            olderrorlevel = atoi(forcedriver);
        else
            olderrorlevel = 0;
    }

    int lasterr = GetLastError();

    EXPR_set(expr,"linecount",   linecount);

    int returncode = errorcount;
    if (OPTreturn[0])
    {
        RANGER *r = RANGER_open(expr,OPTreturn,0.0,1000000.0);  // min/max mostly ignored

        EXPR_set(expr,"errorcount",   errorcount);
        EXPR_set(expr,"linecount",   linecount);
        EXPR_set(expr,"TOOL_VERSION", TOOL_VERSION);
        EXPR_set(expr,"SPIT_VERSION", SPIT_VERSION);
        EXPR_set(expr,"ERRORLEVEL", olderrorlevel);
        EXPR_set(expr,"lasterror", lasterr);

        returncode = (int) RANGER_closest(r, (double) returncode, RANGER_ROUND_CLOSEST);

        RANGER_close(r);
    }
    EXPR_close(expr);

    if (OPTverbose>=4)
        printf(TOOL_NAME " %d lines\n",linecount);

    SPIT_restore();

    if (galloccount)
    {
        if (OPTverbose>=2)
        {
            printf(TOOL_NAME " - WARNING MEMORY NOT FREED TO SYSTEM %d\n",galloccount);
            returncode = galloccount;
        }
    }

    return returncode;
}

