/*rectify.c - compute the absolute value of a GnuroScan averaged EEG data file.
  Copyright (c) 1996 Matthew Belmonte

  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 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.

  If you find this program useful, please send mail to Matthew Belmonte.
  <mkb4@Cornell.edu>.  If you base a publication on data processed by this
  program, please notify Matthew Belmonte and include the following citation
  in your publication:

	Matthew Belmonte, `A Software System for Analysis of
	Steady-State Evoked Potentials', Association for Computing
	Machinery SIGBIO Newsletter 17:1:9-14 (April 1997).
*/

#include <stdio.h>
#include <errno.h>
#include "intel.h"
#include "gnuro.h"

void main(argc, argv)
int argc;
char **argv;
  {
  register int i, channel;
  int num_samples, num_channels;
  FILE *fp, *out;
  printf("Copyright (c) 1996 Matthew Belmonte <mkb4@Cornell.edu>.  Please cite.\n");
  if(argc != 3)
    {
    fprintf(stderr, "usage: %s <input.avg> <output.avg>\n", *argv);
    exit(1);
    }
  if((fp = fopen(argv[1],
#ifdef MSDOS
    "rb"
#else
    "r"
#endif
    )) == NULL)
    {
    perror(argv[1]);
    exit(errno);
    }
  if((out = fopen(argv[2],
#ifdef MSDOS
    "wb"
#else
    "w"
#endif
    )) == NULL)
    {
    perror(argv[2]);
    fclose(fp);
    exit(errno);
    }
/*copy the beginning of the file header*/
  for(i = 0; i != S_pnts_offset; i++)
    putc(getc(fp), out);
/*get # of samples and # of channels from file header*/
  num_samples = getc(fp);
  putc(num_samples, out);
  i = getc(fp);
  putc(i, out);
  num_samples |= i<<8;
  num_channels = getc(fp);
  putc(num_channels, out);
  i = getc(fp);
  putc(i, out);
  num_channels |= i<<8;
/*copy the rest of the headers*/
  for(i = S_nchans_offset+2; i != packed_sizeof_SETUP+num_channels*packed_sizeof_ELECTLOC; i++)
    putc(getc(fp), out);
  for(channel = 0; channel != num_channels; channel++)
    {
  /*5-byte sweep header*/
    for(i = 0; i != 5; i++)
      putc(getc(fp), out);
  /*vector of floats*/
    for(i = 0; i != num_samples; i++)
      {
      putc(getc(fp), out);
      putc(getc(fp), out);
      putc(getc(fp), out);
    /*mask out the sign bit*/
      putc(getc(fp)&0x7f, out);
      }
    }
/*copy variance data, if it exists*/
  while((i = getc(fp)) != EOF)
    putc(i, out);
  fclose(out);
  fclose(fp);
  exit(0);
  }
