/*
 * c-examples/any/example.c - an example of how to call C ASN.1-BER
 *             encoders and decoders generated by snacc
 *
 * AUTHOR: Mike Sample
 * DATE:   Mar 92
 *
 * $Header: /baseline/SNACC/c-examples/any/example.c,v 1.7 2003/12/17 19:05:03 gronej Exp $
 * $Log: example.c,v $
 * Revision 1.7  2003/12/17 19:05:03  gronej
 * SNACC baseline merged with PER v1_7 tag
 *
 * Revision 1.6.2.1  2003/11/05 14:58:53  gronej
 * working PER code merged with esnacc_1_6
 *
 * Revision 1.6  2003/01/15 17:45:23  mcphersc
 * *** empty log message ***
 *
 * Revision 1.5  2003/01/15 17:41:47  mcphersc
 * *** empty log message ***
 *
 * Revision 1.4  2002/10/24 15:18:40  mcphersc
 * took out win32 fwrite
 *
 * Revision 1.3  2002/10/24 14:48:28  mcphersc
 * Changed test routine to use GenBufs
 *
 * Revision 1.2  2002/10/23 12:42:56  mcphersc
 * Added "C" files instead of C++ files
 *
 * Revision 1.3.1.1  1997/08/20 23:14:52  povey
 *
 *
 * Revision 1.6  1997/02/16 20:26:15  rj
 * check-in of a few cosmetic changes
 *
 * Revision 1.5  1995/07/24  20:40:19  rj
 * any-test.[hc] becomes any.[hc] due to to snacc's new file name generation scheme.
 *
 * changed `_' to `-' in file names.
 *
 * Revision 1.4  1995/02/18  15:17:35  rj
 * cosmetic changes
 *
 * Revision 1.3  1994/08/31  23:45:45  rj
 * more portable .h file inclusion.
 *
 * Revision 1.2  1994/08/31  08:59:31  rj
 * first check-in. for a list of changes to the snacc-1.1 distribution please refer to the ChangeLog.
 *
 */

#include "asn-incl.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

#include "any.h"

extern 	unsigned short stdIndentG = 4;


main PARAMS ((argc, argv),
    int argc _AND_
    char *argv[])
{
    int fd;
    SBuf  *buf;
	ExpBuf *ebuf;
    SBuf  *encBuf;
	GenBuf *genBuf = 0;
    char *encData;
    AsnLen encodedLen;
    AsnLen decodedLen;
    int     val;
    AnyTestType att;
    int      size;
	int		 err = 0;
	int		  useExpBuf = 0, currArg;
    char    *origData;
    struct stat sbuf;
    jmp_buf env;

    if ((argc < 2) || (argc > 3))
    {
        fprintf (stderr, "Usage: %s <-E> <BER data file name>\n", argv[0]);
        fprintf (stderr, "   Decodes the given PersonnelRecord BER data file\n");
        fprintf (stderr, "   and re-encodes it to stdout\n");
        fprintf (stderr, "  -E use ExpBuf memory buffers (Optional)\n");
        exit (1);
    }

    for (currArg = 1; (currArg < argc); )
    {
		if ((argv[currArg][0] == '-'))
		{
			switch (argv[currArg][1])
			{
				case 'E':
					useExpBuf = 1;
					currArg++;
					break;
				default:
					currArg++;
					break;
			}
		}
		else
		{
#ifdef WIN32
			    fd = open (argv[currArg], O_RDONLY|O_BINARY, 0);
#else
			    fd = open (argv[currArg], O_RDONLY, 0);
#endif
				if (fd < 0)
				{
					perror ("main: fopen");
					exit (1);
				}

				if (fstat (fd, &sbuf) < 0)
				{
					perror ("main: fstat");
					exit (1);
				}
				currArg++;
		}
	}

    size = sbuf.st_size;
    origData = (char*)malloc (size);
    if ((err = read (fd, origData, size)) != size)
    {
        perror ("main: read");
        exit (1);
    }

    close (fd);

	if (useExpBuf)
	{
		ebuf = ExpBufAllocBuf();
		ExpBufInstallDataInBuf (ebuf, origData, size);
		ExpBuftoGenBuf (ebuf, &genBuf);
	}
	else
	{
		/*
		* puts the given data 'origData' of 'size' bytes
		* into an SBuf and sets the SBuf up for reading
		* origData from the beginning
		*/
		buf = (SBuf *)malloc(sizeof (SBuf));
		SBufInstallData (buf, origData, size);
		SBuftoGenBuf (buf, &genBuf);
	}
    /*
     * the first argument (512) is the number of bytes to
     * initially allocate for the decoder to allocate from.
     * The second argument (512) is the size in bytes to
     * enlarge the nibble memory by when it fills up
     */
    InitNibbleMem (512, 512);


    /*
     * initialize the hash table for the
     * the ANY type mappings.
     * This only needs to be done once per execution
     * (before any encoding or decoding is done)
     */
    InitAnyANY_TEST();

    decodedLen = 0;
    if ((val = setjmp (env)) == 0)
    {
        BDecAnyTestType (genBuf, &att, &decodedLen, env);
    }
    else
    {
        fprintf (stderr, "ERROR - Decode routines returned %d\n",val);
        exit (1);
    }

    fprintf (stderr, "decodedValue AnyTestType ::= ");
    PrintAnyTestType (stderr, &att, 0);
    fprintf (stderr, "\n\n");
	Asn1Free(genBuf);

	if (useExpBuf)
	{
		ebuf = ExpBufAllocBufAndData();
	    ExpBufResetInWriteRvsMode (ebuf);
		ExpBuftoGenBuf (ebuf, &genBuf);
	}
	else
	{
		/*
		 * setup a new buffer set up for writing.
		 * make sure size is big enough to hold the encoded
		 * value (may be larger than decoded value if encoding
		 * with indef lengths - so add 512 slush bytes)
		 */
		encData = (char*) malloc (size + 512);
		encBuf = (SBuf *)malloc(sizeof (SBuf));

		SBufInit (encBuf, encData, size + 512);
		SBufResetInWriteRvsMode (encBuf);
		SBuftoGenBuf (encBuf, &genBuf);

	}


    encodedLen =  BEncAnyTestType (genBuf, &att);
    if ((encodedLen <= 0) || BufWriteError (genBuf))
    {
        fprintf (stderr, "ERROR - buffer to hold the encoded value was too small\n");
        exit (1);
    }

    /*
     * free all of the decoded value since
     * it has been encoded into the buffer.
     * This is much more efficient than freeing
     * each compontent of the value individually
     */
    ResetNibbleMem();
    /*
     * write encoded value from encBuf
     * to stdout
     */

    fwrite (SBufDataPtr (genBuf->spare), SBufDataLen (genBuf->spare), 1, stdout);
    return 0;
}
