%-------------------------------------------------------------------------------
%
%  David S. De Lorenzo
%  January 05, 2018
%
%  Convert T04 record type 35 with viewdat.exe
%
%  Basic viewdat usage:  'viewdat -m --mat=temp.mat -d35:28:3 T04_file_name'
%  To run this headless from a windows command prompt (not PowerShell):
%
%     matlab -nodesktop -nosplash -noFigureWindows -r "try; run('C:\Users\ddelore\OneDrive - Trimble Inc\Documents\MATLAB\Code\T04_Handling\Quick_Run_Viewdat.m'); catch; end; quit"
%
%% -- NOTES ----------------------------------------------------------------
%
%  This script grabs the latest copy of viewdat.exe from EngCon and puts
%  it into your C:\Software directory.
%
%  For some reason, viewdat creates bloated MATLAB output files, probably
%  because of the line-by-line writing in the mat-writer.  If I load the
%  data and then re-save the file, then files come out much smaller in size.
%
%  Running viewdat for some records returns a lower-case filename!!  It's
%  going to be easier to let viewdat output 'temp' named files and then
%  re-name them to the correct filename, otherwise there has to be a bunch
%  of extra logic to distinguish lower-case filenames from upper-case
%  filenames.  So this is why the viewdat system commands are using temp.mat
%  input arguments.
%  ** The 'temp' files are created in the current working directory **
%
%  Also, this presumes that viewdat.exe is on your system path.
%        --> for me, it's in 'C:\Software'
%
%  And the latest version can be copied from here:
%        \\uss-am-dat-06.am.trimblecorp.net\Groups\Unreleased\
%          EngCon\Survey-Eng\TNL\Tools\ViewDat\ViewDAT.exe
%
%  For more information on viewdat:
%    http://wiki.eng.trimble.com/index.php/Viewdat
%
%% -----------------------------------------------------------------------------

clear

path_name = 'C:\DATA\T04_Files\fir_sweep_test_2023_0705\RX1-1401';

d = dir(fullfile(path_name, '*.T04'));
file_list = sort({d.name}.');

%  Sub-type     Contents
% -----------------------
%    19       measurements
%    24         1Hz FFT
%    25         60s FFT
%    28     jamming detection
%    29     spectral features
%    30     jamming mitigation
%    31     LG2 auto switching
%   258     software performance
%   259     processor task list
% subtype_list = [19 24 25 28 29 30 31];
subtype_list = 19;
% subtype_list = [258 259];

% Copy the latest version of viewdat.exe
%{
    d = dir(['\\uss-am-dat-06.am.trimblecorp.net\Groups\Unreleased\', ...
               'EngCon\Survey-Eng\TNL\Tools\ViewDat\ViewDAT.exe']);
    if isempty(d)
        error('ViewDAT.exe was not where we expected it!!');
    else
        copyfile(fullfile(d.folder, d.name), fullfile('C:\Software', d.name));
    end
%}

%% --- No changes should be required below this line -----------------------

fprintf('\nConverting T04 record type 35 with viewdat.exe\n\n');

olddir = pwd;

% Change to your data folder
cd(path_name);

% Loop over input files
for ii = 1:length(file_list)
    filename = file_list{ii};
    if endsWith(filename, '.T04', 'IgnoreCase', true)
        filename = filename(1:end-4);
    end
    fprintf('    %s\n', filename);
    
    % Your input filename
    infile = [filename '.T04'];
    if (exist(fullfile(path_name, infile), 'file') ~= 2)
        error('Your input file does not exist:  %s!!', filename);
    end
    
    % Loop over sub-types for de-coding
    for subtype = subtype_list
        fprintf('      record 35 sub-type %d\n', subtype);
        
        % Execute the viewdat command
        switch subtype
            % case {258, 259}
            %     status = ...
            %         system(sprintf('viewdat -m -otemp.txt -d35:%d %s', ...
            %                        subtype, fullfile(data_folder, infile)));
            case {264}
                status = ...
                    system(sprintf('viewdat -m --mat=temp.mat -d35:%d:3 %s', ...
                                   subtype, fullfile(path_name, infile)));
            otherwise
                status = ...
                    system(sprintf('viewdat -m --mat=temp.mat -d35:%d %s', ...
                                   subtype, fullfile(path_name, infile)));
        end
        
        % Check return status
        if (status ~= 0)
            error('You had a problem converting record type 35!!');
        end
        
        % Check for temp output file
        switch subtype
            % case {258, 259}
            %     if (exist('temp.txt', 'file') ~= 2)
            %         error('Your output file seems missing!!');
            %     end
            otherwise
                if (exist('temp.mat', 'file') ~= 2)
                    error('Your output file seems missing!!');
                end
        end
        
        % Load & re-save the output file
        switch subtype
            % case {258, 259}
            %     data = importdata('temp.txt', ' ');
            %     save('temp.mat', 'data');
            %     delete('temp.txt');
            otherwise
                load('temp.mat', 'data');
                save('temp.mat', 'data');
        end
        
        % Re-name the output file
        outfile = sprintf('%s_rec35_sub%d.mat', filename, subtype);
        success = movefile('temp.mat', fullfile(path_name, outfile));
        if (success ~= 1)
            error('You had a problem re-naming your ".mat" file!!');
        end
        
    end % loop over subtype
    
    fprintf('\n');
    
end % loop over file_list

% Change back to your working directory
cd(olddir);

%% --- ALL DONE ------------------------------------------------------------

fprintf('\n  --> ALL DONE!!\n\n');

%%
return
%-------------------------------------------------------------------------------