/* test fwrite behaviour
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "catalogue.h"

int main(int argc, char **argv )
{
    char buffer[512], errmsg[256];
    int i, count;
    FILE *f;

    if ( argc < 3 ) {
	printf("Usage: test [init|mount|test] volpath [key] [flag1] [flag2]\n" );
	return 1;
    }

    if ( strcmp ( argv[1], "init" ) == 0 ) {
	i = cds_initialize ( argv[2], 20000, 1000000000, errmsg );
	printf("status: %d '%s'\n", i, errmsg );
	if ( i&1 == 0 ) printf ( "failure: %s\n", errmsg );
    } else if ( strcmp ( argv[1], "mount" ) == 0 ) {
	volptr vol;
	vol = cds_mount ( argv[2], 0, (char **) 0, errmsg );
	if ( !vol ) printf ( "failure: %s\n", errmsg );

	else {
	    if ( argc > 3 ) {
		struct cds_header header;
		objptr obj;
		int status;

		obj = cds_open_entry ( vol, argv[3],
		   (argc > 4) ? atoi(argv[4]) : 0, &header, errmsg );
		if ( obj ) {
		    int written, status;
		    printf("Access sucess, obj_number: %d\n", header.number);

		    if ( header.state == 1 ) {	/* new file */
			status = cds_write ( obj, 
			    "check this out\n\n", 16 );
		 	printf ( "status of write: %d\n",status );
		    } else {			/* old file */
			char buffer[100];
			status = cds_read ( obj, buffer, 100, &written );
			printf("status of read: %d, %d '%s'\n", status,
				written, (status&1) ? buffer : "" );
			
		    }

		    status = cds_close_entry ( obj, (argc > 5) ?
			atoi(argv[5]) : 0, &header, errmsg );
		    printf ( "status of close: %d %s\n", status, errmsg );
		} else {
		    printf ( "access failure: %s\n", errmsg );
		}
	    }
	    i = cds_dismount ( vol, 0 );
	    printf("dismount status: %d\n", i );
	}
    } else if ( strcmp ( argv[1], "test" ) == 0 && argc > 3 ) {
	volptr vol;
	vol = cds_mount ( argv[2], 0, (char **) 0, errmsg );
	if ( !vol ) printf ( "failure: %s\n", errmsg );

	else {
	    int LIB$INIT_TIMER(), LIB$SHOW_TIMER();
	    f = fopen ( argv[3], "r" );
	    if ( f ) {
		struct cds_header header;
		objptr obj;
		int status, count, duplicates;
		char buffer[4000], *nl;

		LIB$INIT_TIMER();
		duplicates = 0;
		strcpy ( buffer, "txt:" );
		for ( count=0; 
			fgets(&buffer[4], sizeof(buffer)-4, f); count++) {
		    nl = strchr ( buffer, '\n' );
		    if ( nl ) *nl = '\0';
		    obj = cds_open_entry ( vol, buffer, 1, &header, errmsg );
		    if ( obj ) {
			if ( header.state == 1 ) {
			    if ( argc > 4 ) status = cds_write ( obj, "dummy\n", 6 );
			} else duplicates++;
			cds_close_entry ( obj, 0, &header,  errmsg );
		    } else {
			printf("entry open failure: '%s' '%s'\n",
			     buffer, errmsg );
		    }
		}
		LIB$SHOW_TIMER();
		fclose ( f );
		printf("Keys opened: %d, duplicaets: %d\n", count, duplicates);
	    } else {
		printf ( "Open failure on key list file (%s)\n", argv[3] );
	    }
	    i = cds_dismount ( vol, 0 );
	    printf("dismount status: %d\n", i );
	}
    } else {
	printf("Usage: test [init|mount|test] volpath [key] [flag1] [flag2]\n" );
	return 1;
    }
    return 1;
}
