% Given the outputs of his_extract, writes text files for the locations of
% the maximum and minimum mass and momentum flux locations

clearvars -except chan_dist_max distance_cell Ma_cell max_min_cell ...
    max_t max_t_r min_t min_t_r Mo_cell model_time Q_cell raw_cell ...
    segment250pts t_steps xs_cell

%%
f_loc = ['/Users/Colin/Documents/MATLAB/DFlow/mass_Mo_chap3/'...
    'max_min_flux/data/txt_outputs/'];
[num_runs,~] = size(distance_cell);

for i = 1:num_runs
    run_name = max_min_cell{i,1};
    f_run = run_name(1:17);
    f_name = strcat(f_run,'_max_min');
    
    lb_xy = distance_cell{i,2};
    rb_xy = distance_cell{i,3};
    
    lb_Ma_max = max_min_cell{i,14};
    rb_Ma_max = max_min_cell{i,15};
    lb_Ma_min = max_min_cell{i,16};
    rb_Ma_min = max_min_cell{i,17};
    lb_Mo_max = max_min_cell{i,26};
    rb_Mo_max = max_min_cell{i,27};
    lb_Mo_min = max_min_cell{i,28};
    rb_Mo_min = max_min_cell{i,29};
    
    write_matrix(:,1:2) = [lb_xy; rb_xy];
    write_matrix(:,3) = [lb_Ma_max(:,1); rb_Ma_max(:,1)];
    write_matrix(:,4) = [lb_Ma_min(:,1); rb_Ma_min(:,1)];
    write_matrix(:,5) = [lb_Mo_max(:,1); rb_Mo_max(:,1)];
    write_matrix(:,6) = [lb_Mo_min(:,1); rb_Mo_min(:,1)];
    
    [r,~] = size(write_matrix);
    
    % Write file for model run
    output_fname = strcat(f_loc,f_name);
    fileID = fopen(output_fname,'w');
    for j = 1:r
            fprintf(fileID,'%10.2f,%10.2f,%2.2f,%2.2f,%2.2f,%2.2f\n',...
                write_matrix(j,:));
    end
    
    fclose(fileID);
    
    if i < num_runs
        clear write_matrix
    end
end