function   sw06_filespcgrm_shru(filename,rec_num);
% -----------------------------------------------------------
%  function   sw06_filespcgrm_shru(filename,rec_num);
%
%
%  This program loops and plots the spectrogram every 1 record (~64sec) for
%  the input file. It will also write wav audio files if applied (see variables 
%  that can be set in the program).  A full file has 128 records.
%
%       recnum (record number to process) is optional,
%             if specified will only process that one record 
%                  but it can also be an array [ 4 7 128]
%             otherwise will process the entire file by default
%
%  The frequency band of spectrogram plots are 0-4900Hz by default
%    or any range set by users.
%
%  This program reads a certain record into a structure containing
%    all headers and data.
%
%    Using Kaiser window with fft of order 6 (which is close to hanning)
%
%    subroutines needed for this program, 
%     These MUST be in your path or in your current directory
%
%    1) sw06_readFile_shru
%    2) sw06_getAllDRH_shru
%    3) sw06_getDRH_shru
%    4) sw06_gettime_shru
%    5) specgram_yt_t0
%
%  can also save .wav 16bit audio file.  
%	Change iswritewav variable in program
% --------------------------------------------------------------
 
% -------------------------------------------------------------
%  some variables to set

sensitivity    = 170;                   % dB muP/V, it needs double check!!
fft_size       = 1024;                  % fft size (1024 ~.11 sec)
window_length  = 1024;                  % Kaiser of order 6 window 
overlap_length = 0;                     % overlap (will slow down)
crange         = [50 120];              % color ranges for 3 freq bands
norm_fac       = 10;                  % .wav file normalize factor(4 max)
 
save_spec     =  1;                     % save spectrograms in .png file
iswritewav     = 1;                     % also can save wav file


if (nargin == 0)
    fname = input('Enter Filename: ','s');
    rec_num_ = -1;               % flag for later
elseif (nargin == 1)
    fname       = filename;
    rec_num = -1;
else
    fname       = filename;  
end
 
% -------------------------------------------------------------

f_range_setting = ['f_range = [ 0 max(SPL_f)];'];     % default freq band

figure(1);                     % open a figure to plot spectrograms
  
 fprintf('Working on file: %s',fname);
 fid = fopen(fname,'rb','ieee-be');       % big endian for shru
  
 fprintf('\n\tReading file...  please wait...\n');

 [SHRU,status] = sw06_readFile_shru(fid);    % read all records for file, SHRU is a structure
 fclose(fid);
        
 title_string = ['SHRU' SHRU(1).hdr.shru_num ' ' fname ' '];    % spectrogrm title
      
  
if (rec_num == -1)
   ntimes = 1:length(SHRU);
else
    ntimes = rec_num;
end

 
for irec = ntimes,
            
     fprintf('Processing #%d/%d record...\n',irec,length(SHRU))

     [TM] = sw06_gettime_shru(SHRU(irec).hdr);
     start_time = datenum(TM.yr,1,1)-1+TM.yday;             %in days
     start_time_sec = start_time*24*60*60;                  %in seconds

     title_string_final = [title_string datestr(start_time) ' rec' num2str(irec)];      % the title for the spectrogram
            
     Info = strvcat('         sampling freq',sprintf('         [%7.2fHz]',SHRU(irec).hdr.rhfs),...
                '        FFT pts',sprintf('       [%d]',fft_size),...
                '        window pts',sprintf('       [%d]',window_length),...
                '        overlap pts',sprintf('      [%d]',overlap_length),...
                '          conversion factor',sprintf('         [%ddB %sPa/V]',sensitivity,'\mu'));
             
     % Calculate Power Spectrogram -----------------------------------------------------
 
             [SPL,SPL_f,SPL_t_sec] = specgram_yt_t0( SHRU(irec).data*10^(sensitivity/20), ...
                fft_size, SHRU(irec).hdr.rhfs, kaiser(window_length,6), overlap_length, start_time_sec );
                
             eval(f_range_setting)              % set the freq band
             SPL_t = SPL_t_sec/60/60/24;        % the time axis of the power spectrogram [in days]
                
             for ifrq = 1:size(f_range,1);     % dummy loop, but keep it for multiple freq bands

                    clf;
                    itemp = find(SPL_f>=f_range(ifrq,1)&SPL_f<=f_range(ifrq,2));       % select freq band
                    imagesc(SPL_t,SPL_f(itemp),SPL(itemp,:)); axis xy;        % plot the spectrogram

                        % write title, labels and ticks 

                        % settings of fontsize
                        titlefontsize = 16;
                        axislabelfontsize = 14;
                        ticklabelfontsize = 10;
                        infolabelfontsize = 10;
                        colorbarfontsize = 10;

                        xtick = SPL_t(find( mod(SPL_t,15/60/60/24) < SPL_t(2)-SPL_t(1) ));
                        dytick = fix((f_range(ifrq,2)-f_range(ifrq,1))/12/100)*100;    % auto adjust ytick
                        ytick = [f_range(ifrq,1):400:f_range(ifrq,2)];
                        xlabelstr = ['Time (hr:min:sec)'];
                        ylabelstr = ['Frequency (Hz)'];

                        set(gca,'position',[.13 .11 .7 .815],...
                            'xtick',xtick,'xticklabel',datestr(xtick,'HH:MM:SS'),...
                            'ylim',[f_range(ifrq,1) f_range(ifrq,2)],...
                            'ytick',ytick,...
                            'FontSize',ticklabelfontsize);
                        set(get(gca,'title'),'string',title_string_final,'FontSize',titlefontsize)
                        set(get(gca,'xlabel'),'string',xlabelstr,'FontSize',axislabelfontsize)
                        set(get(gca,'ylabel'),'string',ylabelstr,'FontSize',axislabelfontsize)

                    % plot the colorbar
                    caxis(crange(ifrq,:))       % set the color range
                    hcb = colorbar;           % plot the colorbar
                    
                        % write info and label
                        ytick = [crange(ifrq,1):10:crange(ifrq,2)];

                        set(hcb,'position',[.865 .11 .03 .4],...
                            'ytick',ytick,...
                            'FontSize',colorbarfontsize);
                        set(get(hcb,'title'),'string',strvcat(Info,' ',' '),...
                            'fontsize',infolabelfontsize,...
                            'HorizontalAlignment','center');
                        set(get(hcb,'ylabel'),'string',strvcat('Power Spectral Density', ...
                            '(dB re 1\muPa per 1Hz)'),...
                            'fontsize',colorbarfontsize);
                    
                   
                    
                    % save the spectrogram
 
                    pixname = sprintf('shru%s_%s_%s_r%3.3d.png', SHRU(irec).hdr.shru_num, fname(1:end-4), ...
                              SHRU(irec).hdr.atime([1 2 4 5]), irec);
                                          
                        % switch ifrq                         %% keep it for multiple freq bands
                        %     case 1
                        %         pixname = [pixdir '/1stfreq_' pixname];
                        %     case 2
                        %         pixname = [pixdir '/2ndfreq_' pixname];
                        % end
                        
        
                        
                    % write spec file
                    if(save_spec),
                          print('-dpng','-r150',pixname)
                    end
  
                % -------------------------------------------------------------------------
                % write 16 bit audio files if specified
                if iswritewav, 
 
                   wavname = sprintf('shru%s_%s_%s_r%3.3d.wav', SHRU(irec).hdr.shru_num, fname(1:end-4), ...
                              SHRU(irec).hdr.atime([1 2 4 5]), irec);

                   % normalize with norm_fac
                   wavwrite(SHRU(irec).data*norm_fac,SHRU(irec).hdr.rhfs,16,wavname); 
 
                   % convert to mp3,, ONLY FOR NEWHALL SYSTEMS
                   %% [s,w] = system(['lame --silent ', wavname_lg, '.wav   ', wavname_lg, '.mp3 ' ]);
                   %% [s,w] = system(['rm ',wavname_lg, '.wav   ']);
                  
                   
                end    
                % ------------------------------------------------------------------------
                
       end % frequency band loop
 
  end % records loop
   
% -------------------------------------------------------------------------------------
