Add Debian source format file
[wdq2wav.git] / wdq2wav.cpp
index 0607f123e46d6fa0621065261bd82722dc4029b6..2ea87bf9ce0af8c94e7dc8b9e3e246f2196b3cd9 100644 (file)
@@ -8,8 +8,6 @@
 **
 **  Copyright (c) 2003 Kevin Rosenberg
 **
-**  $Id: wdq2wav.cpp,v 1.12 2003/01/21 12:59:56 kevin Exp $
-**
 **  This program is free software; you can redistribute it and/or modify
 **  it under the terms of the GNU General Public License (version 2) as
 **  published by the Free Software Foundation.
 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 ******************************************************************************/
 
+#include <stdlib.h>
 #include <wdq2wav.h>
 
-const char* g_szIdStr = "$Id: wdq2wav.cpp,v 1.12 2003/01/21 12:59:56 kevin Exp $";
-
 bool g_quiet = false;
 bool g_verbose = false;
 bool g_debug = false;
+bool g_dry_run = false;
+bool g_ignore_zero = false;
+bool g_dont_demean = false;
+
+
+#ifdef WIN32
+#define lseek _lseek
+#define close _close
+#define open _open
+#define read _read
+#define write _write
+#define O_BINARY _O_BINARY
+#define O_RDONLY _O_RDONLY
+#define O_WRONLY _O_WRONLY
+#define O_RDWR _O_RDRW
+#define O_TRUNC _O_TRUNC
+#define O_CREAT _O_CREAT
+const int g_fileMode = _S_IWRITE | _S_IREAD;
+struct fpos_t std::_Fpz = {0,0};
+#else
+const int g_fileMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
+// Define as NULL for non-Windows platforms
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+#endif
+
 
 void
 error_msg (const char *msg)
 {
-  std::cerr << msg << "\n";
+  std::cerr << msg << std::endl;
 }
 
 void
 info_msg (const char* msg)
 {
-  std::cout << msg << "\n";
+  std::cout << msg << std::endl;
 }
 
 void
@@ -53,8 +77,15 @@ info_msg_sans_newline (const char* msg)
 const char*
 fileBasename (const char* filename)
 {
-  const char* p = strrchr (filename, '/');
-  return (p ? p + 1 : filename);
+  const char* pslash = strrchr (filename, '/');
+  const char* pbackslash = strrchr (filename, '\\');
+  const char* p = filename;
+  if (pbackslash && (! pslash || pbackslash >= pslash))
+        p = pbackslash+1;
+  else if (pslash && (! pbackslash || pslash >= pbackslash))
+    p = pslash+1;
+
+  return p;
 }
 
 char *
@@ -83,12 +114,14 @@ usage (const char* progname)
 {
   std::cout << "usage: " << fileBasename (progname) << " [OPTIONS] <wdq-file> <channel-number> <wav-file>\n";
   std::cout << "OPTIONS\n";
-  std::cout << "  -p    Play channel through audio system\n";
-  std::cout << "  -q    Supress all messages\n";
-  std::cout << "  -v    Verbose mode\n";
-  std::cout << "  -d    Debug mode\n";
-  std::cout << "  -r    Print program version\n";
-  std::cout << "  -h    Print this help message\n";
+  std::cout << "  -p   Play channel through audio system\n";
+  std::cout << "  -q   Supress all messages\n";
+  std::cout << "  -z   Scale output without preserving zero point\n";
+  std::cout << "  -m   Do not demean the data (don't subtract the mean value from each sample)\n";
+  std::cout << "  -n   Dry run (do not create any output\n";
+  std::cout << "  -v   Verbose mode\n";
+  std::cout << "  -d   Debug mode\n";
+  std::cout << "  -h   Print this help message\n";
 }
 
 
@@ -99,15 +132,21 @@ main (int argc, char *argv[])
   bool play = false;
 
   const char* progname = argv[0];
-  
-  while ((c = getopt (argc, argv, "rqvdph")) != -1) {
+
+  while ((c = getopt (argc, argv, "rqvzmndph")) != -1) {
     switch (c) {
-    case 'r':
-        std::cout << "Version " << g_szIdStr << std::endl;
-        break;
     case 'q':
       g_quiet = true;
       break;
+    case 'm':
+      g_dont_demean = true;
+      break;
+    case 'n':
+      g_dry_run = true;
+      break;
+    case 'z':
+      g_ignore_zero = true;
+      break;
     case 'v':
       g_verbose = true;
       break;
@@ -126,6 +165,7 @@ main (int argc, char *argv[])
         return (1);
       }
     }
+
   argc -= optind;
   argv += optind;
   if (argc > 3) {
@@ -136,41 +176,42 @@ main (int argc, char *argv[])
 
   char wdq_fname[MAX_INPUT_STR];
   if (argc >= 1)
-      strncpy (wdq_fname, argv [0], MAX_INPUT_STR);
+    strncpy (wdq_fname, argv [0], MAX_INPUT_STR);
   else {
     std::cout << "Enter input WinDAQ filename: ";
-      std::cin.getline (wdq_fname, MAX_INPUT_STR);
-    }
+    std::cin.getline (wdq_fname, MAX_INPUT_STR);
+  }
 
-    char channel_buf [MAX_INPUT_STR];
-    if (argc >= 2)
-      strncpy (channel_buf, argv[1], MAX_INPUT_STR);
-    else {
-      std::cout << "Enter channel number: ";
-      std::cin.getline (channel_buf, MAX_INPUT_STR);
-    }
-    
-    char *channel_endptr;
-    int channel = static_cast<int>(strtol (channel_buf, &channel_endptr, 10));
-    if (*channel_endptr != 0) {
-      std::ostringstream os;
-      os << "Error: Channel " << channel_buf << " is not an integer";
-      error_msg (os.str().c_str());
+  char channel_buf [MAX_INPUT_STR];
+  if (argc >= 2)
+    strncpy (channel_buf, argv[1], MAX_INPUT_STR);
+  else {
+    std::cout << "Enter channel number: ";
+    std::cin.getline (channel_buf, MAX_INPUT_STR);
+  }
+  
+  char *channel_endptr;
+  int channel = static_cast<int>(strtol (channel_buf, &channel_endptr, 10));
+  if (*channel_endptr != 0) {
+    std::ostringstream os;
+    os << "Error: Channel " << channel_buf << " is not an integer";
+    error_msg (os.str().c_str());
       usage (progname);
       return (1);
-    }
-
-    char wav_fname[MAX_INPUT_STR];
+  }
+  
+  char wav_fname[MAX_INPUT_STR];
+  if (! g_dry_run) {
     if (argc >= 3)
       strncpy (wav_fname, argv[2], MAX_INPUT_STR);
     else {
       std::cout << "Enter output wav filename: ";
       std::cin.getline (wav_fname, MAX_INPUT_STR);
     }
-      
-    if (! wdq2wav (wdq_fname, channel, wav_fname, play))
+  }
+  if (! wdq2wav (wdq_fname, channel, wav_fname, play))
       return 1;
-    
+
     return 0;
 }
 
@@ -191,27 +232,39 @@ wdq2wav (const char* wdq_fname, const int channel, const char *wav_fname, bool p
     }
     return false;
   }
+
+  if (wdq.any_packed_channels()) {
+          std::ostringstream os;
+          os << "File contains 'packed' channels." << std::endl;
+          os << "Convert to 'Advanced CODAS headers' before processing with wdq2wav.";
+          error_msg (os.str().c_str());
+          return false;
+  }
+
   if (! g_quiet || g_verbose || g_debug) {
     std::ostringstream os1;
-    os1 << "File " << wdq_fname;
+    os1 << "File: " << wdq_fname;
     info_msg (os1.str().c_str());
+    std::ostringstream os;
+    os << "Format: " <<  (wdq.m_bLegacy_format ? "Legacy" : "Non-legacy");
+    info_msg(os.str().c_str());
     std::ostringstream os2;
     time_t time = wdq.m_time_acq_start;
     struct tm* tm = gmtime (&time);
-    os2 << "  Time File Creation: " << asctime(tm);
+    os2 << "Time File Creation: " << asctime(tm);
     info_msg_sans_newline (os2.str().c_str());
     std::ostringstream os3;
     time = wdq.m_time_acq_stop;
     tm = gmtime (&time);
-    os3 << "  Time File Written: " << asctime(tm);
+    os3 << "Time File Written:  " << asctime(tm);
     info_msg_sans_newline (os3.str().c_str());
     std::ostringstream os4;
-    os4 << "  Samples: " << wdq.m_nSamples <<
+    os4 << "Samples: " << wdq.m_nSamples <<
       ", Channels: " << wdq.m_nChannels <<
       ", Sample Rate: " << wdq.m_sample_rate;
     info_msg (os4.str().c_str());
   }
-  
+
   WindaqChannel wdq_channel (wdq, channel);
   if (! wdq_channel.m_valid) {
     error_msg ("Error reading data from channel");
@@ -220,16 +273,26 @@ wdq2wav (const char* wdq_fname, const int channel, const char *wav_fname, bool p
 
   if (! g_quiet || g_verbose || g_debug) {
     std::ostringstream os1;
-    os1 << "Channel " << channel;
+    os1 << "Channel " << channel << ", Units: " << wdq_channel.m_units
+        << ",  Minimum: " << wdq_channel.m_min_raw_data
+        << " (" << wdq_channel.raw2measured(wdq_channel.m_min_raw_data)
+        << "), Maximum: " << wdq_channel.m_max_raw_data
+        << " (" << wdq_channel.raw2measured(wdq_channel.m_max_raw_data) << ")";
     info_msg (os1.str().c_str());
-    std::ostringstream os2;
-    os2 << "  Units: " << wdq_channel.m_units.c_str();
-    info_msg (os2.str().c_str());
-    std::ostringstream os3;
-    os3 << "  Raw minimum: " << wdq_channel.m_min_raw_data <<
-      ", maximum: " << wdq_channel.m_max_raw_data;
-    info_msg (os3.str().c_str());
+
+    std::cout << "Mean: " << wdq_channel.raw2measured(wdq_channel.m_raw_mean) <<
+      " " << wdq_channel.m_units;
+  }
+
+  if (! g_dry_run && !g_dont_demean) {
+    std::cout << " (removing)\n";
+    int mean = nearest<int>(wdq_channel.m_raw_mean);
+    for (unsigned int i = 0; i < wdq.m_nSamples; i++)
+      wdq_channel.m_data[i] -= mean;
+  } else {
+    std::cout << " (not removing)\n";
   }
+
   if (g_debug) {
     std::ostringstream os4;
     os4 << "  Scaled minimum: " << wdq_channel.m_min_scaled_data <<
@@ -237,9 +300,12 @@ wdq2wav (const char* wdq_fname, const int channel, const char *wav_fname, bool p
     info_msg (os4.str().c_str());
     std::ostringstream os5;
     os5 << "  Slope " <<  wdq_channel.m_slope <<
-      ", Intercept " <<  wdq_channel.m_intercept;
+        ", Intercept " <<  wdq_channel.m_intercept;
     info_msg (os5.str().c_str());
   }
+  
+  if (g_dry_run)
+    return true;
 
   WavFile wav (wdq_channel, wav_fname);
 
@@ -255,13 +321,13 @@ wdq2wav (const char* wdq_fname, const int channel, const char *wav_fname, bool p
 
   if (play)
     wav.Play();
-  
+
   return true;
 }
 
 
 WindaqFile::WindaqFile (const char* fname)
-  : m_fd(0), m_nChannels(0), m_nSamples(0), m_sample_rate(0), m_valid(false),
+  : m_valid(false), m_fd(0), m_nChannels(0), m_nSamples(0), m_sample_rate(0),
     m_strFile (fname)
 {
 }
@@ -272,6 +338,16 @@ WindaqFile::~WindaqFile ()
     close (m_fd);
 }
 
+bool read_int1 (int fd, unsigned char& n)
+{
+  unsigned char tmp1;
+  if (read (fd, &tmp1, 1) != 1)
+    return false;
+
+  n = tmp1;
+  return true;
+}
+
 bool read_int2 (int fd, unsigned short int& n)
 {
   unsigned char tmp1;
@@ -281,7 +357,7 @@ bool read_int2 (int fd, unsigned short int& n)
   tmp2 = tmp1;
   if (read (fd, &tmp1, 1) != 1)
     return false;
-  
+
   n = tmp2 + (tmp1 * 256);
   return true;
 }
@@ -295,50 +371,109 @@ bool read_int4 (int fd, unsigned int& n)
   tmp4 = tmp2;
   if (! read_int2 (fd, tmp2))
     return false;
-  
+
   n = tmp4 + (tmp2 * 65536);
   return true;
 }
 
+bool read_float8 (int fd, double& f)
+{
+  unsigned char p[8];
+  if (read (fd, p, 8) != 8)
+    return false;
+
+#if WORDS_BIG_ENDIAN
+  unsigned char c;
+  c = p[0]; p[0] = p[7]; p[7] = c;
+  c = p[1]; p[1] = p[6]; p[6] = c;
+  c = p[2]; p[2] = p[5]; p[5] = c;
+  c = p[3]; p[3] = p[4]; p[4] = c;
+#endif
+
+  double *pd = reinterpret_cast<double*>(&p[0]);
+  f = *pd;
+
+  return true;
+}
+
 bool
 WindaqFile::ReadHeader ()
 {
-  unsigned short int tmp2;
-
   m_valid = false;
-  if ((m_fd = open (m_strFile.c_str(), O_RDONLY)) < 0) {
+  if ((m_fd = open (m_strFile.c_str(), O_RDONLY | O_BINARY)) < 0) {
     m_error = "Unable to open file";
     return false;
   }
 
   lseek (0, 0, SEEK_SET);
-  if (! read_int2 (m_fd, tmp2))
+  unsigned short int element1;
+  if (! read_int2 (m_fd, element1))
     return false;
 
-  m_nChannels = tmp2 & 0x1f;
-  m_sr_denom = (tmp2 & 0x7fff) >> 5;
-  m_sr_numer = (tmp2 & 0x8000) << 1;
-  
-  if (! read_int2 (m_fd, tmp2))
+  short unsigned int byte1 = (element1 & 0xFF00) >> 8;
+  short unsigned int byte2 = element1 & 0xFF;
+  if (byte1 == 0 || byte1 == 1) {
+          m_bLegacy_format = false;
+          m_sr_denom = m_sr_numer = 0;
+  } else {
+          m_sr_denom = (element1 & 0x7fff) >> 5;
+          m_sr_numer = (element1 & 0x8000) << 1;
+      m_bLegacy_format = true;
+  }
+  unsigned short int element2;
+  if (! read_int2 (m_fd, element2))
     return false;
 
-  m_sr_numer |= tmp2;
-  m_sample_rate = (double) m_sr_numer / (double) (m_sr_denom * m_nChannels);
+  if (m_bLegacy_format)
+          m_sr_numer |= element2;
 
-  if (! read_int2 (m_fd, tmp2))
+  unsigned char element3;
+  if (! read_int1 (m_fd, element3))
     return false;
+  m_channel_offset = element3;
+  if (g_debug)
+          std::cout << "Channel offset: " << m_channel_offset << std::endl;
 
-  m_channel_offset = tmp2 & 0xFF;
-  m_nBytes_channel_header = tmp2 >> 8;
-  
-  if (! read_int2 (m_fd, m_nHeader_bytes))
+  unsigned char element4;
+  if (! read_int1 (m_fd, element4))
     return false;
-  
-  if (! read_int4 (m_fd, m_nData_bytes))
+  m_nBytes_channel_header = element4;
+  if (g_debug)
+          std::cout << "Channel header bytes: " << m_nBytes_channel_header << std::endl;
+
+  unsigned short int element5;
+  if (! read_int2 (m_fd, element5))
     return false;
+  m_nHeader_bytes = element5;
+  if (g_debug)
+          std::cout << "Header bytes: " << m_nHeader_bytes << std::endl;
+
+  m_nMaxChannels = (m_nHeader_bytes - 112) / 36;
+  if (m_nMaxChannels >= 144)
+        m_nChannels = byte2 & 0xFF;
+  else
+    m_nChannels = byte2 & 0x1F;
+
+  unsigned int element6;
+  if (! read_int4 (m_fd, element6))
+    return false;
+  m_nData_bytes = element6;
+  if (g_debug)
+          std::cout << "Data bytes: " << m_nData_bytes << std::endl;
 
   m_nSamples = (m_nData_bytes / m_nChannels) / 2;
 
+  lseek (m_fd, 28, SEEK_SET);
+  double element13;
+  if (! read_float8 (m_fd, element13))
+          return false;
+  m_time_between_channel_samples = element13;
+
+  if (m_bLegacy_format)
+     m_sample_rate = (double) m_sr_numer / (double) (m_sr_denom * m_nChannels);
+  else
+     m_sample_rate = (double) 1 / m_time_between_channel_samples;
+
   lseek (m_fd, 36, SEEK_SET);
   if (! read_int4 (m_fd, m_time_acq_start))
     return false;
@@ -346,14 +481,31 @@ WindaqFile::ReadHeader ()
   if (! read_int4 (m_fd, m_time_acq_stop))
     return false;
 
+  lseek (m_fd, 100, SEEK_SET);
+  unsigned short int element27;
+  if (! read_int2 (m_fd, element27))
+          return false;
+
+  m_bHires = (element27 & 0x0001) ? true : false;
+  if (g_debug) {
+          std::cout << "High resolution: ";
+          if (m_bHires)
+                  std::cout << "Yes";
+          else
+                  std::cout << "No";
+
+          std::cout << std::endl;
+  }
+
   // Verify Windaq signature
   lseek (m_fd, m_nHeader_bytes - 2, SEEK_SET);
-  if (! read_int2 (m_fd, tmp2))
+  unsigned short int element35;
+  if (! read_int2 (m_fd, element35))
     return false;
 
-  if (tmp2 != 0x8001) {
+  if (element35 != 0x8001) {
     std::ostringstream os;
-    m_error = "File is not a valid WinDAQ file";
+        m_error = "Incorrect signagure: file is not a valid WinDAQ file";
     return false;
   }
 
@@ -361,7 +513,32 @@ WindaqFile::ReadHeader ()
   return true;
 }
 
-  
+bool
+WindaqFile::any_packed_channels ()
+{
+        for (int iChannel = 0; iChannel < m_nChannels; iChannel++)
+                if (is_channel_packed (iChannel))
+                        return true;
+
+        return false;
+}
+
+bool
+WindaqFile::is_channel_packed (const int channel)
+{
+  long iStart = m_channel_offset + channel * m_nBytes_channel_header;
+
+  lseek (m_fd, iStart + 31, SEEK_SET);
+  unsigned char iReadings_per_data_point;
+  if (! read_int1 (m_fd, iReadings_per_data_point))
+        return false;
+
+  if (iReadings_per_data_point > 1)
+          return true;
+
+  return false;
+}
+
 WindaqChannel::WindaqChannel (WindaqFile& wdq, const int channel)
   : r_wdq(wdq), m_data(0), m_slope(0), m_intercept (0), m_channel(channel),
     m_valid(false)
@@ -369,11 +546,11 @@ WindaqChannel::WindaqChannel (WindaqFile& wdq, const int channel)
   if (wdq.m_valid) {
     if (channel >= 1 && channel <= wdq.m_nChannels) {
       if (read_channel_data())
-       m_valid = true;
+        m_valid = true;
     } else {
       std::ostringstream os;
       os << "Channel " << channel << " is invalid, valid range 1-" <<
-       wdq.m_nChannels;
+        wdq.m_nChannels;
       error_msg (os.str().c_str());
     }
   }
@@ -385,42 +562,20 @@ WindaqChannel::~WindaqChannel ()
     delete m_data;
 }
 
-bool get_float8 (int fd, double& f)
-{
-  unsigned char buf[8];
-  if (read (fd, &buf, 8) != 8)
-    return false;
-
-#if WORDS_BIG_ENDIAN
-  unsigned char c;
-  c = buf[0]; buf[0] = buf[7]; buf[7] = c;
-  c = buf[1]; buf[1] = buf[6]; buf[6] = c;
-  c = buf[2]; buf[2] = buf[5]; buf[5] = c;
-  c = buf[3]; buf[3] = buf[4]; buf[4] = c;
-#endif
-
-  f = *(reinterpret_cast<double*>(buf));
-
-  return true;
-}
-
 bool
 WindaqChannel::read_channel_data ()
 {
-  unsigned short int tmp2;
-  unsigned int tmp4;
-  
   int fd = r_wdq.m_fd;
 
   m_data = new signed short int [r_wdq.m_nSamples * 2];
 
-  lseek (fd, r_wdq.m_channel_offset + 8 + 
-        (m_channel - 1) * r_wdq.m_nBytes_channel_header,
-        SEEK_SET);
-  if (! get_float8 (fd, m_slope))
+  lseek (fd, r_wdq.m_channel_offset + 8 +
+         (m_channel - 1) * r_wdq.m_nBytes_channel_header,
+         SEEK_SET);
+  if (! read_float8 (fd, m_slope))
     return false;
 
-  if (! get_float8 (fd, m_intercept))
+  if (! read_float8 (fd, m_intercept))
     return false;
 
   char units[7];
@@ -430,40 +585,47 @@ WindaqChannel::read_channel_data ()
     return false;
   }
   m_units = units;
-  unsigned int row_bytes = 2 * r_wdq.m_nChannels;
-  signed short int sample_row [row_bytes];
-  
+
+  long int row_bytes = 2 * r_wdq.m_nChannels;
+
+  signed short int *sample_row = new signed short int [row_bytes];
+
   signed short int* psample = &sample_row[m_channel - 1];
 
   lseek (fd, r_wdq.m_nHeader_bytes, SEEK_SET);
-  long int i;
-  signed short int data_max, data_min;
+  unsigned long int i;
+  signed short int data_max = 0, data_min = 0;
+  double total_data = 0;
   for (i = 0; i < r_wdq.m_nSamples; i++) {
     if (read (fd, sample_row, row_bytes) != row_bytes) {
       std::ostringstream os;
       os << "Error reading file at " << i;
       error_msg (os.str().c_str());
+      delete sample_row;
       return false;
     }
     signed short int v = *psample;
 
 #if WORDS_BIG_ENDIAN
     unsigned char* p = reinterpret_cast<unsigned char*>(&v);
-    unsigned char c = p[0]; p[0] = p[1]; p[1] = c; 
+    unsigned char c = p[0]; p[0] = p[1]; p[1] = c;
 #endif
 
-    signed short int value = v >> 2;
+    signed short int value = v;
+        if (! r_wdq.m_bHires)
+                value >>= 2;
+
     m_data[i] = value;
-    
+    total_data += value;
+
     if (i == 0) {
       data_max = value;
       data_min = value;
     } else {
       if (value > data_max)
-       data_max = value;
+        data_max = value;
       else if (value < data_min)
-       data_min = value;
+        data_min = value;
     }
   }
 
@@ -472,6 +634,9 @@ WindaqChannel::read_channel_data ()
   m_max_scaled_data = (m_slope * data_max) + m_intercept;
   m_min_scaled_data = (m_slope * data_min) + m_intercept;
 
+  m_raw_mean = total_data / static_cast<double>(r_wdq.m_nSamples);
+
+  delete sample_row;
   return true;
 }
 
@@ -485,19 +650,27 @@ WavFile::WavFile (WindaqChannel& wdq_channel, const char* fname)
     m_nBitsPerSample = 16;
     m_nBytesPerSample = 2;
     m_rate = wdq_channel.r_wdq.m_sample_rate;
-    
-    double data_offset = -wdq_channel.m_min_scaled_data;
-    double data_scale = 0.;
-    if (wdq_channel.m_max_scaled_data != wdq_channel.m_min_scaled_data)
-      data_scale = 65535. / (wdq_channel.m_max_scaled_data -
-                            wdq_channel.m_min_scaled_data);
-    
+
+    double data_offset = 0, data_scale = 0;
+    if (g_ignore_zero) {
+      data_offset = -wdq_channel.m_min_scaled_data;
+      if (wdq_channel.m_max_scaled_data != wdq_channel.m_min_scaled_data)
+        data_scale = 65535. / (wdq_channel.m_max_scaled_data -
+                               wdq_channel.m_min_scaled_data);
+    } else {
+      double max_value = fabs(wdq_channel.m_max_scaled_data);
+      if (fabs (wdq_channel.m_min_scaled_data) > max_value)
+        max_value = fabs (wdq_channel.m_min_scaled_data);
+      if (max_value != 0.)
+        data_scale = 32767. / max_value;
+    }
+
     if (g_debug) {
       std::ostringstream os;
       os << "  Wav data_scale: " << data_scale << ", data_offset: " << data_offset;
       info_msg (os.str().c_str());
     }
-    
+
     m_nHeaderBytes = 44;
     m_nDataBytes = m_nSamples * m_nBytesPerSample * m_nChannels;
     m_nFileBytes = m_nHeaderBytes + m_nDataBytes;
@@ -509,20 +682,26 @@ WavFile::WavFile (WindaqChannel& wdq_channel, const char* fname)
     signed short int* output = &m_data[nHeaderShortInts];
     double slope = wdq_channel.m_slope;
     double intercept = wdq_channel.m_intercept;
-    
+
     if (! fill_header ())
       return;
 
-    long int i;
+    unsigned long int i;
+
     for (i = 0; i < m_nSamples; i++) {
       double value = input[i];
       value = (slope * value) + intercept;
-      value = (value + data_offset) * data_scale;
-      value += 0.5 - 32768;
+      if (g_ignore_zero) {
+        value = (value + data_offset) * data_scale;
+        value += 0.5 - 32768;
+      } else {
+        value = value * data_scale;
+      }
+
       signed short int v = static_cast<signed short int>(value);
 #if WORDS_BIG_ENDIAN
       unsigned char* p = reinterpret_cast<unsigned char*>(&v);
-      unsigned char c = p[0]; p[0] = p[1]; p[1] = c; 
+      unsigned char c = p[0]; p[0] = p[1]; p[1] = c;
 #endif
       output[i] = v;
     }
@@ -536,7 +715,7 @@ WavFile::~WavFile ()
 {
   if (m_fd != 0)
     close (m_fd);
-    
+
   if (m_data != NULL)
     delete m_data;
 }
@@ -581,13 +760,13 @@ WavFile::fill_header ()
   // Sample Rate
   put_int4 (pData + 24, static_cast<int> (m_rate + 0.5));
 
-  // Bytes per second 
+  // Bytes per second
   put_int4 (pData + 28, static_cast<int> (m_rate * m_nBytesPerSample + 0.5));
 
   // Bytes per sample
   put_int2 (pData + 32, m_nBytesPerSample * m_nChannels);
 
-  // Bits per sample 
+  // Bits per sample
   put_int2 (pData + 34, m_nBitsPerSample);
 
   strncpy (pData + 36, "data", 4);
@@ -600,15 +779,11 @@ WavFile::fill_header ()
 bool
 WavFile::WriteFile ()
 {
-  unsigned short int tmp2;
-  unsigned int tmp4;
-
   if (! m_valid)
     return false;
 
   if (m_fd == 0)
-    if ((m_fd = open (m_strFile.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 
-                     S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == 0) {
+    if ((m_fd = open (m_strFile.c_str(), O_WRONLY | O_BINARY | O_TRUNC | O_CREAT, g_fileMode)) == 0) {
       std::ostringstream os;
       os << "Error opening output file " << m_strFile.c_str();
       error_msg (os.str().c_str());
@@ -623,15 +798,15 @@ WavFile::WriteFile ()
 
   if (close (m_fd) < 0)
     error_msg ("Error closing output file");
-  
+
   m_fd = 0;
   return true;
 }
 
-#ifdef WIN32
+#ifdef _WIN32
 #include <windows.h>
 #include <mmsystem.h>
-#elif defined(LINUX)
+#elif defined(__linux__)
 #include <sys/ioctl.h>
 #include <sys/soundcard.h>
 #endif
@@ -639,51 +814,59 @@ WavFile::WriteFile ()
 bool
 WavFile::Play ()
 {
-#ifdef WIN32
-  if (PlaySound ((LPCSTR) m_data, 0, SND_MEMORY | SND_NO_DEFAULT))
+#ifdef _WIN32
+  if (PlaySound ((LPCSTR) m_data, 0, SND_MEMORY | SND_NODEFAULT))
     return true;
-#elif defined(LINUX)
+#elif defined(__linux__)
   int fd;
-  if ((fd = open ("/dev/dsp",O_WRONLY)) < 0) {
+  if ((fd = open ("/dev/dsp",O_WRONLY)) == -1) {
     error_msg ("Error opening /dev/dsp");
     return false;
   }
-  
+
   int format = AFMT_S16_LE;
   if (ioctl (fd, SNDCTL_DSP_SETFMT, &format) == -1) {
     error_msg ("Error setting DSP format");
-    close(fd); return false; }
+    close(fd); return false;
+  }
   if (format != AFMT_S16_LE) {
     error_msg ("DSP Format not set");
-    close(fd); return false; }
-  
-  int channels = m_nChannels;
+    close(fd); return false;
+  }
+
+  unsigned int channels = m_nChannels;
   if (ioctl (fd, SNDCTL_DSP_CHANNELS, &format) == -1) {
     error_msg ("Error setting number of channels");
-    close(fd); return false; }
+    close(fd); return false;
+  }
   if (channels != m_nChannels) {
     error_msg ("Number of channels not set");
-    close(fd); return false; }
+    close(fd); return false;
+  }
 
-  int speed = static_cast<int>(m_rate + 0.5);
+  unsigned int speed = static_cast<int>(m_rate + 0.5);
   if (ioctl (fd, SNDCTL_DSP_SPEED, &speed) == -1) {
     error_msg ("Error setting sample rate");
-    close(fd); return false; }
-  double set_speed = speed;
-  if (fabs (set_speed - m_rate) / m_rate > 0.1) {
-    error_msg ("Sample rate not set");
-    close(fd); return false; }
-    
+    close(fd); return false;
+  }
+  if (speed != m_rate && ! g_quiet) {
+    std::ostringstream os;
+    os << "Warning: Sample rate set to " << speed << ", not " << m_rate;
+    error_msg (os.str().c_str());
+  }
+
   if (write (fd, reinterpret_cast<char*>(m_data) + m_nHeaderBytes, m_nDataBytes) !=
       m_nDataBytes) {
     error_msg ("Error writing audio samples");
-    close(fd); return false; }
+    close(fd); return false;
+  }
 
   close (fd);
   return true;
+#else
 #endif
-  
+
   return false;
 }
 
-     
+