// dtmf123.cc  P. Conrad   CISC181 Fall 2005
// Write a WAV file that sounds out the DTMF for 123 (touch tones)

// @@@ Add your own comment here indicating that you
// @@@ updated the file; include your name, date, section, and "CISC181 proj1b"

#include <iostream>
using namespace std;


// the following header files are needed for writing binary files
// they provide the functions open() and write(), as well as O_CREAT, O_RDWR

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <stdio.h> // for perror

#include <cmath>   // for sin, floor
#include <cstdlib> // for atoi, atof


#include "endian.h"
#include "wavLibrary.h"


int main(int argc, char *argv[])
{
  
  if (argc!=3)
    {
      cerr << "Usage: " << argv[0] << " numSeconds filename" << endl;
      exit(1);
    }

  // toneDuration is the length of each tone, and the space between.
  // we'll leave a space at the end too, so 1 (space) 2 (space) 3 (space)
  // is 6 times the tone duration

  double toneDuration = atof(argv[1]);
  
  if (toneDuration <= 0 || toneDuration > 3.0)
    {
      cerr << "Error: numSeconds must be between 0 and 3.0" << endl;
      exit(2);
    }

  const int samplesPerSecond = 11025;


  // OLD: @@@  int fd = open(argv[2], O_RDWR | O_CREAT );
  

  int fd = open(argv[2], O_RDWR | O_CREAT, 0755 ); // @@@ NEW: specifies mode
  
  // make sure open was successful
  
  if (fd < 0)
    {
      cerr << "File " << argv[2] << " could not be opened" << endl;
      perror("open:");
      exit(1);
    }
  
  int numSamples = (int) floor(toneDuration * 6 * samplesPerSecond);
  
  // Write the header to the file
  
  writeWAVheader(numSamples, samplesPerSecond, fd);
  
  // Write the samples to the file
  
  
  writeDTMFTones(fd, toneDuration, '1');
  writeSilenceSamples(fd, toneDuration);

  writeDTMFTones(fd, toneDuration, '2');
  writeSilenceSamples(fd, toneDuration);

  writeDTMFTones(fd, toneDuration, '3');
  writeSilenceSamples(fd, toneDuration);
  
  close(fd);
  
  int status;

  // leading zero on 0755 is NECESSARY; makes it an octal number
  status = chmod(argv[2],0755); // like a chmod at command line
  
  if (status != 0)
    {
      perror("Trouble with chmod command");
      exit(4);
    }


}





