/******************************************************************************
*
* project name:    TI-68k Developer Utilities (formerly TIGCC Tools Suite)
* file name:       ttunarchive.c
* initial date:    29/01/2002
* authors:         thomas.nussbaumer@gmx.net
* description:     unpacks files generated by ttarchive
*
* -----------------------------------------------------------------------------
*
* based on code from Pasi 'Albert' Ojala, albert@cs.tut.fi
*
* heavily reduced to fit to the needs by thomas.nussbaumer@gmx.net
*
*
* NOTE: this tool is quite a hack done in 30 minutes by taking ttunebk.c as
*       base code ... don't expect "wonders" here ... ;-)
*
*
******************************************************************************/

/*
  This file is part of TI-68k Developer Utilities.

  This file is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  As a special exception, UNMODIFIED copies of ttunarchive may also be
  redistributed or sold without source code, for any purpose. (The Lesser
  General Public License restrictions do apply in other respects; for example,
  they cover modification of the program.) This exception notice must be
  removed on modified copies of this file.

  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
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

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

#include "unpack.c"

#include "tt.h"          // generic defines
#include "ttversion.h"   // TI-68k Developer Utilities version info
#include "revtools.h"
#include "ttunpack.h"    // errorcodes definition
#include "packhead.h"    // compressed header definition
#include "ttarchive.h"   // ttarchive definitions

#ifdef FILE_REVISION
#undef FILE_REVISION
#endif
#define FILE_REVISION "1.3"


//=============================================================================
// outputs usage information of this tool
//=============================================================================
void PrintUsage() {
    fprintf(USAGE_OUT, "Usage: ttunarchive <infile> [<entry_number> <outfile>]\n\n"\
                       "       extracts one entry of an TTArchive into a file\n"\
                       "       (entry_number starts with 0). If no entry number\n"\
                       "       and outfile are given, ttunarchive lists only\n"\
                       "       the contents of the TTArchive\n\n");
}



//=============================================================================
// our main reason why we are here ...
//=============================================================================
int main(int argc, char* argv[]) {
    unsigned char* src;
    FILE*          fp;
    char*          infilename  = NULL;
    char*          outfilename = NULL;
    char*          entrynumber = NULL;
    long           insize;
    short          nr_entries;
    short          i;
    short          extract_idx = 0; // 1.40: default initialization, hope it is correct.
    unsigned short origsize;
    short          show_content = 0;

    PRINT_ID("TTUnArchive");

    for (i=1;i<argc;i++) {
        if (!infilename)       infilename  = argv[i];
        else if (!entrynumber) entrynumber = argv[i];
        else if (!outfilename) outfilename = argv[i];
        else {
            PrintUsage();
            return 1;
        }
    }

    if (infilename && !entrynumber && !outfilename) {
        show_content = 1;
    }
    else if (!infilename || !entrynumber || !outfilename) {
        PrintUsage();
        return 1;
    }

    //-------------------------------------------
    // convert entrynumber string into short
    //-------------------------------------------
    if (!show_content) {
        extract_idx = atoi(entrynumber);
        if (extract_idx < 0) {
            fprintf(stderr, "ERROR: negative entry numbers are not valid (%s)\n", entrynumber);
            return 1;
        }
    }
    if (!(fp = fopen(infilename, "rb"))) {
        fprintf(stderr, "ERROR: cannot open input file %s\n", infilename);
        return 1;
    }

    fseek(fp,0,SEEK_END);
    insize = ftell(fp);
    rewind(fp);

    // treatment of PC header ...
    insize -= 88;
    fseek(fp,86,SEEK_SET);


    if (!(src = (unsigned char*)malloc(insize))) {
        fprintf(stderr, "ERROR: cannot allocate buffer\n");
        fclose(fp);
        return 1;
    }

    if ((long)fread(src, 1, insize, fp) != insize) {
        fprintf(stderr, "ERROR: cannot read %ld bytes from %s\n",insize,infilename);
        fclose(fp);
        free(src);
        return 1;
    }

    fclose(fp);

    if (!IsTTArchive(src+2)) {
        fprintf(stderr, "ERROR: %s is not a valid archive\n",infilename);
        free(src);
        return 1;
    }

    nr_entries = GetNrEntries(src+2);

    if (show_content) {
        printf("Archive: %s\n",infilename);
        printf("Entries: %d\n",nr_entries);

        for (i=0;i<nr_entries;i++) {
            TTAEntry*      entry = GetEntryInfo(src+2,i);
            unsigned char* data  = GetEntryStart(src+2,entry);
            PackedHeader*  ch    = (PackedHeader*)data;
            unsigned short size  = GetEntrySize(entry);

            if (ch->magic1 != MAGIC_CHAR1 || ch->magic2 != MAGIC_CHAR2) {
                origsize = size;
            }
            else {
                origsize = ch->origsize_lo | (ch->origsize_hi << 8);
            }
            printf("Entry[%02d]: archive_size=%05u orig_size=%05u\n",i,size,origsize);
        }
        free(src);
        return 0;
    }

    if (nr_entries <= extract_idx) {
        fprintf(stderr, "ERROR: entry number (%d) too large (nr_entries=%d)\n",extract_idx,nr_entries);
        free(src);
        return 1;
    }


    if (!(fp = fopen(outfilename, "wb"))) {
        fprintf(stderr, "ERROR: cannot open output file %s\n", outfilename);
        return 1;
    }

    {
        TTAEntry*      entry = GetEntryInfo(src+2,extract_idx);
        unsigned char* data  = GetEntryStart(src+2,entry);
        PackedHeader*  ch    = (PackedHeader*)data;
        unsigned char* dest;
        int            result;


        if (ch->magic1 != MAGIC_CHAR1 || ch->magic2 != MAGIC_CHAR2) {
            // handle uncompressed entry
            printf("processing uncompressed entry %d ...\n",extract_idx);
            origsize = GetEntrySize(entry);

            if (fwrite(data,1,origsize,fp) != origsize) {
                fprintf(stderr,"ERROR: cannot write uncompressed entry to file\n");
                free(src);
                fclose(fp);
                return 1;
            }
        }
        else {
            // handle a compressed entry
            printf("processing compressed entry %d ...\n",extract_idx);
            origsize = ch->origsize_lo | (ch->origsize_hi << 8);
            if (!(dest = (unsigned char*)malloc(origsize))) {
                fprintf(stderr,"ERROR: cannot allocate %d bytes for output buffer\n",origsize);
                free(src);
                fclose(fp);
                return 1;
            }

            result=UnPack(data,dest);
            if (result) {
                fprintf(stderr,"ERROR: cannot decompress (code %03d)\n",result);
                free(src);
                free(dest);
                fclose(fp);
                return 1;
            }

            if (fwrite(dest,1,origsize,fp) != origsize) {
                fprintf(stderr,"ERROR: cannot decompress (code %03d)\n",result);
                free(src);
                free(dest);
                fclose(fp);
                return 1;
            }
            free(dest);
        }
    }

    printf("%d bytes written to %s\n",origsize,outfilename);

    free(src);
    fclose(fp);
    return 0;
}

//#############################################################################
//###################### NO MORE FAKES BEYOND THIS LINE #######################
//#############################################################################
//
//=============================================================================
// Revision History
//=============================================================================
//
// Revision 1.3  2009/01/25           Lionel Debroux
// Changes by Romain Liévin and/or me for 64-bit compatibility.
// Adapt to new version display (revtools.h).
//
// Revision 1.2  2002/02/07 09:49:38  tnussb
// all local includes changed, because header files are now located in pctools folder
//
// Revision 1.1  2002/02/07 09:12:12  tnussb
// initial version
//
//
//
