/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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 Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdio.h>
#include <netinet/in.h>

char usage[] = "\nusage: pcap_big2lil <input file>\n";

struct pcap_file_header {
    unsigned int magic;
    unsigned short version_major;
    unsigned short version_minor;
    int thiszone;
    unsigned int sigfigs;
    unsigned int snaplen;
    unsigned int linktype;
};

struct pcap_pkthdr {
    struct timeval ts;
    unsigned int caplen;
    unsigned int len;
};


int main( int argc, char *argv[] ) {

        FILE *f_in;
        long f_pos;

        struct pcap_file_header hdr;
        struct pcap_pkthdr pkt;
        
        if ( argc < 2 ) {
                printf( usage );
                return 1;
        }
        
        if( ( f_in = fopen( argv[1], "r+" ) ) == NULL ) {
                printf( "Error opening input file %s\n", argv[1] );
                return 1;
        }
        
        fread( &hdr, sizeof( struct pcap_file_header ), 1, f_in );
        rewind( f_in );
        
        hdr.magic = ( ntohl( hdr.magic ) );
        hdr.version_major = ( ntohs( hdr.version_major ) );
        hdr.version_minor = ( ntohs( hdr.version_minor ) );
        hdr.thiszone = ( ntohl( hdr.thiszone ) );
        hdr.sigfigs = ( ntohl( hdr.sigfigs ) );
        hdr.snaplen = ( ntohl( hdr.snaplen ) );
        hdr.linktype = ( ntohl( hdr.linktype ) );

        fwrite( &hdr, sizeof( struct pcap_file_header ), 1, f_in );

        while ( 1 ) {

                f_pos = ftell( f_in );
                
                if ( ! fread( &pkt, sizeof( struct pcap_pkthdr ), 1, f_in ) )
			break;
                fseek( f_in, f_pos, SEEK_SET );

                pkt.ts.tv_sec = ( ntohl( pkt.ts.tv_sec ) );
                pkt.ts.tv_usec = ( ntohl( pkt.ts.tv_usec ) );
                pkt.caplen = ( ntohl( pkt.caplen ) );
                pkt.len = ( ntohl( pkt.len ) );

                fwrite( &pkt, sizeof( struct pcap_pkthdr ), 1, f_in);
                fseek( f_in, pkt.caplen, SEEK_CUR );
        }
        
        fclose(f_in);
	return 0;
}
