import numpy as np
import tensorflow as tf
import sys
import scipy.io as io

from tensorflow.python.ops import variable_scope as vs

recname=sys.argv[1]

aux=io.loadmat(recname+'_spectrogram.mat')
spec=np.asarray(aux['S'], dtype=np.float32)
input_size,Length=spec.shape
print "original record length is ",Length/25, " secs"
if Length>600:
    newL=600
    print "using only the firs 24 secs"
else:
    newL=Length
newspec=np.zeros((newL,1,input_size), dtype=np.float32)
newspec[:,0,:]=np.transpose(spec[:,:newL])
#inputs=tf.split(2,Length,newspec)
batch_size=1
inputs=[tf.reshape(i, (batch_size, input_size)) for i in\
            tf.split(0, newL, newspec)]
# model

fake_outputsize=2 # s1s2
lstm_size = 250

lstm1 = tf.nn.rnn_cell.LSTMCell(lstm_size,input_size)
lstm2 = tf.nn.rnn_cell.LSTMCell(lstm_size,lstm_size) 
stacked_lstm1 = tf.nn.rnn_cell.MultiRNNCell([lstm1,lstm2])
initial_state = state=stacked_lstm1.zero_state(1, tf.float32)


name = "BiRNN"
# Forward direction
with vs.variable_scope(name + "_FW"):
    lstm_outputs1, state1 =tf.nn.rnn(stacked_lstm1,inputs,initial_state)
    #for i in range(newL):
    #    if i>0: vs.get_variable_scope().reuse_variables()
    #    output, state =stacked_lstm1(newspec[i,:,:],state)


with vs.variable_scope("classNet"):
    WClass = tf.Variable(tf.truncated_normal(shape=[lstm_size,1],
                                             stddev=0.01))
    biasClass = tf.Variable(tf.ones(shape=[1]))
 
output=tf.matmul(lstm_outputs1[newL-1],WClass) + biasClass
#output=tf.matmul(output,WClass) + biasClass

output=tf.sigmoid(output) # ]0,1[ values
output=tf.round(output) # 0,1 values 
output=2*output-1 # ]-1,1[ values

saver = tf.train.Saver()
session = tf.Session()
# load trained weights
saver.restore(session,"ClassificationHeartSounds_250_impVar.ckpt")


simplename=recname.split('/')[-1]
prediction=session.run(output)
f=open('answers.txt','a')
f.write('%s,%d\n'% (simplename,prediction))
f.close()
#np.save("result",prediction)
