/*************************************************************************
  Remove header from VSSP32/64 raw data
  How to compile
   $ gcc -o vssp_rm_header vssp_rm_header.c
  How to use
   $ cat vssp_data.dat | ./vssp_rm_header > vssp_data.bin 2> vssp_data.log
   here, vssp_data.dat is VSSP32/64 raw data
         vssp_data.bin is VSSP32/64 raw data without header
         vssp_data.log is log file which includes the header data
*************************************************************************/

#include <stdio.h>
#include <stdlib.h>

// definition of header in VSSP32/64 data
struct vssp32_header {
    //----------
    unsigned int sync1;
    //----------
    unsigned int sod:17;
    unsigned int ch:1;
    unsigned int sfreq:4;
    unsigned int ad:2;
    unsigned int sync2:8;
    //----------
    unsigned int doy:9;
    unsigned int year:6;
    unsigned int ef:1;
    unsigned int aux_sz:8;
    unsigned int sver:4;
    unsigned int ver:4;
    //----------
    unsigned int aux[5];
    //----------
};

// data buffer size for 32MHz sampling, 2bit, 4ch is 32000000 Bytes (increase N as needed)
#define N 32000000
char buff[N];

int main()
{
    struct vssp32_header hdr;
    
    unsigned int ui_data_sz;
    unsigned int sfreq_khz[] = {40, 100, 200, 500, 
                                1000, 2000, 4000, 8000, 
                                16000, 32000, 64000, 128000, 
                                256000, 512000, 1024000, 2048000};
    unsigned int ad_bit[] = {1, 2, 4, 8}; 
    unsigned int ch_num[] = {1, 4}; 
        
    fprintf(stderr, "Sync1     Sync2 AD SFREQ CH   SOD VER SVER AUX  EF YEAR DOY DATA_SZ\n");

    while(1)
    {
        // read header from stdin
        fread(&hdr, 1, sizeof(hdr), stdin);
        
        // calculate data size in Byte
        ui_data_sz = (unsigned int)(sfreq_khz[hdr.sfreq] * 1000 * ad_bit[hdr.ad] * ch_num[hdr.ch] / 8);

        // output header to stderr
        fprintf(stderr, "0x%08x 0x%02x  %d    %02d  %d %05d  %02d   %02d %03d [%d] 20%02d %03d %d\n",
                hdr.sync1, 
                hdr.sync2, hdr.ad, hdr.sfreq, hdr.ch, hdr.sod, 
                hdr.ver, hdr.sver, hdr.aux_sz, hdr.ef, hdr.year, hdr.doy,
                ui_data_sz);

        // error check
        if (hdr.sync1 != 0xffffffff)
        {
            fprintf(stderr, "Invalid sync patter is deteted : 0x%08x\n", hdr.sync1);
            return 1;
        }

        // read data from stdin
        fread(buff, ui_data_sz, sizeof(char), stdin);

        // terminate if end-of-file is detected
        if (feof(stdin)) break;

        // write data (without header) to stdout
        fwrite(buff, ui_data_sz, sizeof(char), stdout);
    }

    return 0;

}