"""
Scripts to transform PCM data to WAV file.

Usage:
    bin_to_wav.py (stereo|mono) [options]

Options: 
    -h --help                                      Show this screen.
    -i, --input=<pcm_bin_file_name>                Input path of pcm data file.[default: ./record_data.bin]
    -o, --output=<wave_file_name>　　　　　　　　　Output path of wav file to be generated [default: output]
    -s, --swap=<0,1>                               apollo PDM module is configured to swap left and right channel [default: 0]
    -r, --samplerate=<Hz>                          audio sample rate in Hz, [default: 16000]
"""
from docopt import docopt
import struct
import soundfile as sf
import numpy as np
import time

args = docopt(__doc__)
print(args)

audioDataFilePath = args['--input'] 

now = time.strftime("-%Y-%m-%d-%H_%M", time.localtime(time.time()))
if args['--output']:
    outputFilePath = args['--output'] + now + '.wav' 
else:
    outputFilePath = now + '.wav'

if args['--swap']:
    LRswap = int(args['--swap'])
else:
    LRswap = 0

if args['--samplerate']:
    sampleRate = int(args['--samplerate'])
else:
    sampleRate = 16000

binFile = open(audioDataFilePath, 'rb')

context=binFile.read()

if args['stereo']:
    audioStream = struct.unpack('<'+'h'*(len(context)//2), context)
    audioStream = np.array(audioStream)
    wavLeftStream = np.array([0]*(len(audioStream)//2), dtype=float)
    wavRightStream = np.array([0]*(len(audioStream)//2), dtype=float)
    
    for i in range(len(wavLeftStream)):
        if LRswap != 0:
            wavLeftStream[i] = audioStream[2*i+1]
            wavRightStream[i] = audioStream[2*i]
        else:
            wavRightStream[i] = audioStream[2*i+1]
            wavLeftStream[i] = audioStream[2*i]

    wavLeftStream = wavLeftStream / 32768.
    wavRightStream = wavRightStream / 32768.

    sf.write('stereo_left_' + outputFilePath, wavLeftStream, sampleRate)
    print('Generated file:'+ 'stereo_left_' + outputFilePath)
    sf.write('stereo_right_' + outputFilePath, wavRightStream, sampleRate)
    print('Generated file:'+ 'stereo_right_' + outputFilePath)
	
    # Normlization for human listening
    wavLeftStream = wavLeftStream/np.max([np.max(wavLeftStream),np.abs(np.min(wavLeftStream))])
    wavRightStream = wavRightStream/np.max([np.max(wavRightStream),np.abs(np.min(wavRightStream))])
    
    sf.write('stereo_left_norm_' + outputFilePath, wavLeftStream, sampleRate)
    print('Generated file:'+ 'stereo_left_norm_' + outputFilePath)
    sf.write('stereo_right_norm_' + outputFilePath, wavRightStream, sampleRate)
    print('Generated file:'+ 'stereo_right_norm_' + outputFilePath)

if args['mono']:
    audioStream = struct.unpack('<'+'h'*(len(context)//2), context)
    wavStream = np.array(audioStream)
    wavStream = wavStream / 32768.

    sf.write('mono_' + outputFilePath, wavStream, sampleRate)
    print('Generated file:'+ 'mono_' + outputFilePath)

    # Normlization for human listening
    wavStream = wavStream/np.max([np.max(wavStream),np.abs(np.min(wavStream))])

    sf.write('mono_norm_' + outputFilePath, wavStream, sampleRate)
    print('Generated file:'+ 'mono_norm_' + outputFilePath)

