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

#include "pcap.h"

int main( int argc, char *argv[] )
{
    int i, n;
    unsigned long nbw;
    unsigned char buffer[1024];
    FILE *f_in, *f_out;

    if( argc < 4 )
    {
        printf( "usage: mergeivs <ivs file 1> <ivs file 2> .. <output file>\n" );
        return( 1 );
    }

    printf( "Creating %s\n", argv[argc - 1] );

    if( ( f_out = fopen( argv[argc - 1], "wb+" ) ) == NULL )
    {
        perror( "fopen failed" );
        return( 1 );
    }

    nbw = 0;

    for( i = 1; i < argc - 1; i++ )
    {
        printf( "Opening %s\n", argv[i] );

        if( ( f_in = fopen( argv[i], "rb" ) ) == NULL )
        {
            perror( "fopen failed" );
            return( 1 );
        }

        if( fread( buffer, 1, 4, f_in ) != 4 )
        {
            perror( "fread file header failed" );
            return( 1 );
        }

        if( memcmp( buffer, IVSONLY_MAGIC, 4 ) != 0 )
        {
            printf( "%s is not an .ivs file\n", argv[i] );
            return( 1 );
        }

        if( i == 1 )
            fwrite( buffer, 1, 4, f_out );

        while( ( n = fread( buffer, 1, 1024, f_in ) ) > 0 )
        {
            nbw += n;
            fwrite( buffer, 1, n, f_out );
            printf( "%ld bytes written\r", nbw );
        }

        fclose( f_in );

        printf( "\n" );
    }

    fclose( f_out );

    return( 0 );
}
