/* XSum.c - sums up all bytes in a compressed or uncompressed file 
 *
 * This is a typical read-and-process xpk application. Try it out... XSum a
 * file, then compress it and XSum it again. The result should be the same.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libraries/xpk.h>

struct Library *XpkBase, *OpenLibrary( char *libName, ULONG version );

char errbuf[XPKERRMSGSIZE+1], *outbuf;
long outlen, outbuflen;

void end( char *text )
{
	if( outbuf )  FreeMem(outbuf,outbuflen);
	if( text )    Write(Output(), text, strlen(text));
	if( XpkBase ) CloseLibrary( XpkBase );
	exit(text ? 10 : 0);
}

void main(int argc, char *argv[])
{
	UBYTE *ptr, *last;
	ULONG sum=0;

	if(!(XpkBase=OpenLibrary( XPKNAME,0)))
		end("Cannot open "XPKNAME"\n");
	
	if( argc!=2 )
		end("Usage: XChecksum filename\n");
	
	if(XpkUnpackTags(
		XPK_InName,      argv[1],   /* The file name to be read              */
		XPK_GetError,    errbuf,    /* A pointer to the error message buffer */
		XPK_GetOutBuf,   &outbuf,   /* Sets a pointer to the output buffer   */
		XPK_GetOutLen,   &outlen,   /* Sets the number of bytes written      */
		XPK_GetOutBufLen,&outbuflen,/* Sets the length of the output buffer  */
		XPK_PassThru,    TRUE,      /* Will pass through uncompressed data   */
		TAG_DONE
	 ))
		end(strcat(errbuf,"\n"));

	ptr = (UBYTE*)outbuf;
	last= ptr +   outlen;
	while( ptr<last )
		sum+=*ptr++;
	printf("%d\n",sum);

	end(NULL);
}
