// morseSOS.cc  P. Conrad   CISC181 Fall 2005
// Write a WAV file containing a Morse code signal of a given duration

// @@@ 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] << " wavFile totalDuration" 
	   << endl;
      exit(1);
    }

  // for an explanation of ditDuration, dahDuration,
  // spaceInsideChars, spaceBetweenChars and spaceBetweenWords,
  // see the comment at the end of this file.

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

  double totalDits = 12; // ... dit space dit space dit spaceBetweenWords

  double ditDuration = totalDuration / totalDits;

  double dahDuration = ditDuration * 3.0;
  double spaceInsideChars = ditDuration;
  double spaceBetweenChars = ditDuration * 3.0;
  double spaceBetweenWords = ditDuration * 7.0;


  const int samplesPerSecond = 11025;
  const int morseCodeFrequency = 500; // 500Hz

  int fd = open(argv[1], O_RDWR | O_CREAT , 0755);
  
  // make sure open was successful
  
  if (fd < 0)
    {
      perror("open:");
      cerr << "File " << argv[1] << " could not be opened" << endl;
      exit(3);
    }
  

  int numSamples = (int) floor(totalDuration * samplesPerSecond);
  
  // Write the header to the file
  
  writeWAVheader(numSamples, samplesPerSecond, fd);
  
  // Write the samples to the file
  
  writeS(fd, ditDuration, dahDuration, spaceInsideChars, morseCodeFrequency);
  writeSilenceSamples(fd, spaceBetweenWords);


  close(fd);

  int status;

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








