%This program changes the statements in files so that a single file which
%prints figures is called.
%
%Zachary Wolf
%2/4/15

%Get directory list
dir_list = dir('C:\Analysis Test Edit\Lib');

%Loop over directories
for ii = 3 : length(dir_list)
    
    %Show progress
    display(ii)
    
    %Set the current directory
    sub_dir = ['C:\Analysis Test Edit\Lib\', dir_list(ii).name];
    cd(sub_dir);
    
    %Find plot files
    file_list1 = dir('*_plot_*');
    file_list2 = dir('*_plt_*');
    file_list = [{file_list1.name}, {file_list2.name}];
    
    %Loop over plot files
    for jj = 1 : length(file_list)
        
        %Open the file
        file_name = file_list{jj};
        fid = fopen(file_name, 'r');
        
        %Open a temporary file
        temp_file_name = [file_name, '_tmp'];
        tfid = fopen(temp_file_name, 'w');
        
        %Loop through the file and write the contents to the temporary file
        %Change the print statement when it comes up
        while 1
            in_line = fgetl(fid);
            if ~ischar(in_line)
                break
            end
            if strfind(in_line, 'orient landscape') > 0
                continue;
            elseif strfind(in_line, 'print(''-dpsc'', plt_file)') > 0
                fprintf(tfid, 'util_print_fig_init(plt_file);\r\n');
            elseif strfind(in_line, 'print(''-append'', ''-dpsc'', plt_file)') > 0
                fprintf(tfid, 'util_print_fig(plt_file);\r\n');
            elseif strfind(in_line, 'util_plt_fig(plt_file)') > 0
                fprintf(tfid, 'util_print_fig(plt_file);\r\n');
            else
                fprintf(tfid, '%s\r\n', in_line);
            end
        end

        %Close the files
        fclose('all');
    
        %Delete original file
        delete(file_name);

        %Rename temporary file
        movefile(temp_file_name, file_name);
    
    %End loop over plot files
    end
    
%End loop over directories
end

%Set the current directory to Analysis
cd('c:\analysis');

%Done