function asos_wx

% *************** Prompt User to Select ASOS files **********************
% check for temporary file with pathname from last analysis:
if exist('tmp_ASOS_path.mat','file'), load('tmp_ASOS_path'); end;
if ~exist('pathname','var') || ~isstr(pathname), pathname = filesep; end
% open dialog box for file selection:
[filename, pathname] = uigetfile({'*.op', 'ASOS Files (*.op)'; '*.*',...
    'All Files (*.*)'},'Select ASOS file(s) to process',pathname,...
    'MultiSelect','on');
% check whether user pressed OK or not:
if pathname==0
    err = errordlg('ASOS file selection cancelled by user.','Analysis cancelled');
    uiwait(err); return;
else
    save('tmp_ASOS_path','pathname'); % save 'pathname' as default for next analysis
end
% convert filename to a cell if only one file was selected:    
if ~iscell(filename)
    tmp_filename = filename; clear filename; 
    filename{1}= tmp_filename; clear tmp_filename;
end

% ***** Extract peak wind data and ASOS station codes from selected files
% initialize variables:
ws = [];
wd = [];
date_time = [];
station_id = [];
max_length = 1/2; %defined maximum length of t-storm
% loop through files and extract data
for i=1:length(filename)
    filename_i = fullfile(pathname,filename{i});
    % Extract peak gust wind data from current file (see documentation for function 'PK_WND'):
    [ws_i, wd_i, date_time_i, station_id_i]= PK_WND(filename_i);
    ws = [ws; ws_i];
    wd = [wd; wd_i];
    date_time = [date_time; date_time_i];
    station_id = [station_id; station_id_i];
    file_station_id{i} = unique(station_id_i);
end
unique_id = unique([station_id]); % list of stations found in selected files
if isempty(unique_id)
    error_msg = {'No peak wind reports found in the selected file(s):'};
    error_msg(2:length(filename)+1) = filename;
    err=errordlg(error_msg,'Error: analysis aborted');
    uiwait(err); return;
end

% ******* Prompt User to Select One ASOS Station *************************
% load ASOS station numbers with descriptive names from file:
if exist ('ASOS_stations.mat','file')
    load('ASOS_stations');
else
    [station_no, station_dn]=ASOS_id;
end
% assemble labels with descriptive names for the ASOS stations found:
for i = 1:length(unique_id)
    station_ind = find(station_no == unique_id(i));
    if ~isempty(station_ind)
        station_label{i} = ['Station ' num2str(unique_id(i)) ': ' station_dn{station_ind(1)} ...
            ' (' num2str(length(find(station_id==unique_id(i)))) ' peak wind reports)'];
    else
        station_label{i} = ['Station ' num2str(unique_id(i))  ...
            ' (' num2str(length(find(station_id==unique_id(i)))) ' peak winds reports)'];
    end
end
% open dialog box and prompt user to select one ASOS station:
[station_sel, ok] = listdlg('ListString',station_label, 'SelectionMode', 'single',...
    'InitialValue', [1],'Name', 'Select ASOS station','PromptString',...
    {'Records from the following stations were found in the selected files.',...
    'Please select one station for analysis'}, 'ListSize',[450 100]);
% check if the user pressed OK or not:
if ~ok
    err = errordlg('Selection of ASOS station cancelled by user.','Analysis cancelled');
    uiwait(err); return;
end
asos_id = unique_id(station_sel); % number of selected ASOS station

% Eliminate wind data from ASOS stations other than the one selected:
ws = ws(find(station_id == asos_id));
wd = wd(find(station_id == asos_id));
date_time = date_time(find(station_id == asos_id));

[date_time, date_time_ind] = unique(date_time);
ws = ws(date_time_ind);
wd = wd(date_time_ind);

% Make a list of files containing data from the selected ASOS station:
file_ctr = 0;
for i=1:length(filename)
    if ismember(asos_id, file_station_id{i})
        file_ctr = file_ctr +1;
        sel_full_filename{file_ctr} = fullfile(pathname,filename{i}); % list of files for opening
        sel_filename{file_ctr} = filename{i}; % list of files for displaying
    end
end
sel_filename_list = [];
if length(sel_filename)>1
    for i=1:length(sel_filename)-1
        sel_filename_list = [sel_filename_list sel_filename{i} '; ']; % list of files to print in output file
    end
end
sel_filename_list = [sel_filename_list sel_filename{end}];

% **** Prompt user to select desired output files and where to write them:
list_string = {'All Winds', 'Non-Thunderstorm Winds', 'Thunderstorm Winds',...
    'Non-Thunderstorm Winds, separated by specified time interval',...
    'Thunderstorm Winds, separated by specified time interval', ...
    'Manual Thunderstorm Observations', 'Thunderstorm beginning and end times'};
sel = []; try_count = 0;
while isempty(sel) & try_count<3
    [sel, ok] = listdlg('ListString',list_string, 'SelectionMode', 'multiple',...
        'InitialValue', [1],'Name', 'Select output file(s) to write',...
        'PromptString',{'Separate CSV files will be written for each selection each with columns giving'...
        'appropriate reported values for the selected file'}, 'ListSize',[400 100]);
    try_count = try_count+1;
end
if isempty(sel)
    err = errordlg('Output file selection cancelled by user.','Analysis cancelled');
    uiwait(err); return;
end
out_dir = 0; try_count = 0;
while out_dir==0 & try_count<3
    out_dir = uigetdir(pathname, 'Select folder for writing output files');
    try_count = try_count+1;
end
if out_dir == 0
    err = errordlg('Selection of output file location cancelled by user.','Analysis cancelled');
    uiwait(err); return;
end

%  If any output files other than "All winds" are selected, then extract manual thunderstorm observations:
if any(ismember(sel, [2 3 4 5 6 7]))    
    % extract manual thunderstorm observations (see documentation for function 'MW'):
    [MW_B_date_time, MW_E_date_time,MW_date_time,MW_code] = MW(sel_full_filename, asos_id);
    if length(MW_date_time)==0
        wrn = warndlg('No valid manual thunderstorm reports found in the specified files: only the first output file ("All winds") can be written',...
            'Warning: no "MW" thunderstorm reports found');
        uiwait(wrn);
        sel = 1;
    end
end

% If any output files other than "All winds" and "Manual thunderstorm observations" are selected,
% then extract thuderstorm beginning and end times 
% and match manual thunderstorm observations with 
% thunderstorm beginning and end times:
if any(ismember(sel, [2 3 4 5 7]))
    % extract thunderstorm beginning and end times (see documentation for function 'tsBE'):
    [B_date_time, E_date_time] = tsBE(sel_full_filename, asos_id);

    % match manual thunderstorm observations with thunderstorm beginning and end times:
    [B,E] = matchBE(B_date_time, E_date_time, MW_B_date_time, MW_E_date_time);
end

% If "Thunderstorm winds" or "Non-Thunderstorm Winds" selected for output (whether separated by specified interval or not)
% then classify winds as thunderstorm or non-thunderstorm:
if any(ismember(sel, [2 3 4 5]))
    % prompt user to specify time windows for extending thunderstorm durations:
    [wind_neg, wind_pos, ok] = set_ts_windows; % (see documentation for function 'set_ts_windows')
    if ~ok
        err = errordlg('Thunderstorm window specification cancelled by user.','Analysis cancelled');
        uiwait(err); return;
    end

    % Classify winds as thunderstorm or non-thunderstorm:
    twind=zeros(size(date_time)); % initialize boolean vector:  0 -> non-thunderstorm, 1 -> thunderstorm
    if ~isempty(B) & ~isempty(E)
        BE_wind = zeros(size(date_time));
        for i=1:length(B)
            BE_ind = find(date_time>(B(i)-wind_neg) & date_time<(E(i)+wind_pos));
            twind(BE_ind) = 1;
        end
       
    end % if ~isempty(B_date_time) & ...

    ts_ws = ws(find(twind));
    nts_ws = ws(find(~twind));
    ts_wd = wd(find(twind));
    nts_wd = wd(find(~twind));
    ts_date_time = date_time(find(twind));
    nts_date_time = date_time(find(~twind));
end

% Construct data sets separated by at least specified time intervals, if requested:
if any(ismember(sel,[4 5]))
    % prompt user to specify intervals for separation of wind speeds:
    [interval_nts, interval_ts, ok] = set_sep_intervals; % (see documentation for function 'set_sep_intervals')
    if ~ok
        err = errordlg('Separation interval specification cancelled by user.','Analysis cancelled');
        uiwait(err); return;
    end

    if ~isempty(ts_ws)
        % separate thunderstorm wind speeds by specified interval (see documentation for function 'interval_sep'):
        [ts_ws_sep, ts_date_time_sep, ts_ind_sep] = interval_sep(ts_ws, ts_date_time, interval_ts);
        ts_wd_sep = reshape(ts_wd(ts_ind_sep),size(ts_ws_sep));
    else    
        ts_ws_sep = []; ts_date_time_sep = []; ts_wd_sep = [];
    end

    if ~isempty(nts_ws)
        % separate non-thunderstorm wind speeds by specified interval (see documentation for function 'interval_sep'):
        [nts_ws_sep, nts_date_time_sep, nts_ind_sep] = interval_sep(nts_ws, nts_date_time, interval_nts);
        nts_wd_sep = reshape(nts_wd(nts_ind_sep),size(nts_ws_sep));
    else
        nts_ws_sep = []; nts_date_time_sep = []; nts_wd_sep = [];
    end
end

%*************************** Write Output Files ****************************

out_file_count = 0;
out_file_label{1} = 'The following output files have been written:';

if ismember(1,sel)
    out_filename = fullfile(out_dir,['station_' num2str(asos_id) '_ALL.csv']);
    fw = fopen( out_filename,'w' );
    try_count=0;
    while fw == -1
        err = errordlg({['Cannot write file: ' strrep(out_filename,'\','\\')], 'Make sure this file is not currently open.'},...
            'Error writing file');
        uiwait(err);
        try_count=try_count+1;
        if try_count>3, return; end
        fw = fopen( out_filename,'w' );
    end
    fprintf(fw, '%s\n', ['ASOS filename(s):,' sel_filename_list]);
    fprintf(fw, '%s\n', ['Station code:,' num2str(asos_id)]);
    fprintf(fw, '%s\n', ['Station description:,' station_dn{find(asos_id == station_no)}]);
    fprintf(fw, '%s\n', ['Output file type:,All winds']);
    fprintf(fw, '%s\n', ['Wind speed units:,knots']);
    fprintf(fw, '%s\n', ['Wind direction units:,degrees clockwise from true north']);
    fprintf(fw, '\n');
    fprintf(fw, '%s\n', 'Date/Time, Wind Speed, Wind Direction');
    for i = 1:length(ws)
        fprintf(fw, '%s\n', [datestr(date_time(i),0) ',' num2str(ws(i)) ',' num2str(wd(i))]);
    end
    fclose(fw);
    out_file_count = out_file_count+1;
    out_file_label{out_file_count+1}=out_filename;
end
 


if ismember(2,sel) 
    out_filename = fullfile(out_dir,['station_' num2str(asos_id) '_NTS.csv']);
    fw = fopen(out_filename ,'w' );
    try_count=0;
    while fw == -1
        err = errordlg({['Cannot write file: ' strrep(out_filename,'\','\\')], 'Make sure this file is not currently open.'},...
            'Error writing file');
        uiwait(err);
        try_count=try_count+1;
        if try_count>3, return; end
        fw = fopen( out_filename,'w' );
    end
    fprintf(fw, '%s\n', ['ASOS filename(s):,' sel_filename_list]);
    fprintf(fw, '%s\n', ['Station code:,' num2str(asos_id)]);
    fprintf(fw, '%s\n', ['Station description:,' station_dn{find(asos_id == station_no)}]);
    fprintf(fw, '%s\n', ['Output file type:,Non-Thunderstorm winds']);
    fprintf(fw, '%s\n', ['Window before T-storm beginning (h):,' num2str(wind_neg*24)]);
    fprintf(fw, '%s\n', ['Window after T-storm end (h):,' num2str(wind_pos*24)]);
    fprintf(fw, '%s\n', ['Wind speed units:,knots']);
    fprintf(fw, '%s\n', ['Wind direction units:,degrees clockwise from true north']);
    fprintf(fw, '\n');
    fprintf(fw, '%s\n', 'Date/Time, Wind Speed, Wind Direction');
    for i = 1:length(nts_ws)
        fprintf(fw, '%s\n', [datestr(nts_date_time(i),0) ',' num2str(nts_ws(i)) ',' num2str(nts_wd(i))]);
    end
    fclose(fw);
    out_file_count = out_file_count+1;
    out_file_label{out_file_count+1}=out_filename;
end
 
if ismember (3,sel)
    out_filename = fullfile(out_dir,['station_' num2str(asos_id) '_TS.csv']);
    fw = fopen(out_filename ,'w' );
    try_count=0;
    while fw == -1
        err = errordlg({['Cannot write file: ' strrep(out_filename,'\','\\')], 'Make sure this file is not currently open.'},...
            'Error writing file');
        uiwait(err);
        try_count=try_count+1;
        if try_count>3, return; end
        fw = fopen( out_filename,'w' );
    end
    fprintf(fw, '%s\n', ['ASOS filename(s):,' sel_filename_list]);
    fprintf(fw, '%s\n', ['Station code:,' num2str(asos_id)]);
    fprintf(fw, '%s\n', ['Station description:,' station_dn{find(asos_id == station_no)}]);
    fprintf(fw, '%s\n', ['Output file type:,Thunderstorm winds']);
    fprintf(fw, '%s\n', ['Window before T-storm beginning (h):,' num2str(wind_neg*24)]);
    fprintf(fw, '%s\n', ['Window after T-storm end (h):,' num2str(wind_pos*24)]);
    fprintf(fw, '%s\n', ['Wind speed units:,knots']);
    fprintf(fw, '%s\n', ['Wind direction units:,degrees clockwise from true north']);
    fprintf(fw, '\n');
    fprintf(fw, '%s\n', 'Date/Time, Wind Speed, Wind Direction');
    for i = 1:length(ts_ws)
        fprintf(fw, '%s\n', [datestr(ts_date_time(i),0) ',' num2str(ts_ws(i)) ',' num2str(ts_wd(i))]);
    end
    fclose(fw);
    out_file_count = out_file_count+1;
    out_file_label{out_file_count+1}=out_filename;
end

if ismember(4,sel)
    out_filename = fullfile(out_dir,['station_' num2str(asos_id) '_NTS_sep.csv']);
    fw = fopen( out_filename,'w' );
    try_count=0;
    while fw == -1
        err = errordlg({['Cannot write file: ' strrep(out_filename,'\','\\')], 'Make sure this file is not currently open.'},...
            'Error writing file');
        uiwait(err);
        try_count=try_count+1;
        if try_count>3, return; end
        fw = fopen( out_filename,'w' );
    end
    fprintf(fw, '%s\n', ['ASOS filename(s):,' sel_filename_list]);
    fprintf(fw, '%s\n', ['Station code:,' num2str(asos_id)]);
    fprintf(fw, '%s\n', ['Station description:,' station_dn{find(asos_id == station_no)}]);
    fprintf(fw, '%s\n', ['Output file type:,Non-Thunderstorm winds separated by specified interval']);
    fprintf(fw, '%s\n', ['Window before T-storm beginning (h):,' num2str(wind_neg*24)]);
    fprintf(fw, '%s\n', ['Window after T-storm end (h):,' num2str(wind_pos*24)]);
    fprintf(fw, '%s\n', ['Separation interval (d):,' num2str(interval_nts)]);
    fprintf(fw, '%s\n', ['Wind speed units:,knots']);
    fprintf(fw, '%s\n', ['Wind direction units:,degrees clockwise from true north']);
    fprintf(fw, '\n');
    fprintf(fw, '%s\n', 'Date/Time, Wind Speed, Wind Direction');
    for i = 1:length(nts_ws_sep)
        fprintf(fw, '%s\n', [datestr(nts_date_time_sep(i),0) ',' num2str(nts_ws_sep(i)) ',' num2str(nts_wd_sep(i))]);
    end
    fclose(fw);
    out_file_count = out_file_count+1;
    out_file_label{out_file_count+1}=out_filename;
end

if ismember (5,sel)
    out_filename = fullfile(out_dir,['station_' num2str(asos_id) '_TS_sep.csv']);
    fw = fopen( out_filename,'w' );
    try_count=0;
    while fw == -1
        err = errordlg({['Cannot write file: ' strrep(out_filename,'\','\\')], 'Make sure this file is not currently open.'},...
            'Error writing file');
        uiwait(err);
        try_count=try_count+1;
        if try_count>3, return; end
        fw = fopen( out_filename,'w' );
    end
    fprintf(fw, '%s\n', ['ASOS filename(s):,' sel_filename_list]);
    fprintf(fw, '%s\n', ['Station code:,' num2str(asos_id)]);
    fprintf(fw, '%s\n', ['Station description:,' station_dn{find(asos_id == station_no)}]);
    fprintf(fw, '%s\n', ['Output file type:,Thunderstorm winds separated by specified interval']);
    fprintf(fw, '%s\n', ['Window before T-storm beginning (h):,' num2str(wind_neg*24)]);
    fprintf(fw, '%s\n', ['Window after T-storm end (h):,' num2str(wind_pos*24)]);
    fprintf(fw, '%s\n', ['Separation interval (d):,' num2str(interval_ts)]);
    fprintf(fw, '%s\n', ['Wind speed units:,knots']);
    fprintf(fw, '%s\n', ['Wind direction units:,degrees clockwise from true north']);
    fprintf(fw, '\n');
    fprintf(fw, '%s\n', 'Date/Time, Wind Speed, Wind Direction');
    for i = 1:length(ts_ws_sep)
        fprintf(fw, '%s\n', [datestr(ts_date_time_sep(i),0) ',' num2str(ts_ws_sep(i)) ',' num2str(ts_wd_sep(i))]);
    end
    fclose(fw);
    out_file_count = out_file_count+1;
    out_file_label{out_file_count+1}=out_filename;
end

if ismember (6,sel)
    out_filename = fullfile(out_dir,['station_' num2str(asos_id) '_MW.csv']);
    fw = fopen( out_filename,'w' );
    try_count=0;
    while fw == -1
        err = errordlg({['Cannot write file: ' strrep(out_filename,'\','\\')], 'Make sure this file is not currently open.'},...
            'Error writing file');
        uiwait(err);
        try_count=try_count+1;
        if try_count>3, return; end
        fw = fopen( out_filename,'w' );
    end
    fprintf(fw, '%s\n', ['ASOS filename(s):,' sel_filename_list]);
    fprintf(fw, '%s\n', ['Station code:,' num2str(asos_id)]);
    fprintf(fw, '%s\n', ['Station description:,' station_dn{find(asos_id == station_no)}]);
    fprintf(fw, '%s\n', ['Output file type:,Manual Thunderstorm Observations']);
    fprintf(fw, '\n');
    fprintf(fw, '%s\n', ['Section I: Manual thunderstorm observations and times']);
    fprintf(fw, '%s\n', 'Date/Time, Thunderstorm Code');
    for i = 1:length(MW_date_time)
        fprintf(fw, '%s\n', [datestr(MW_date_time(i),0) ',' num2str(MW_code(i))]);
    end
    fprintf(fw, '\n');
    fprintf(fw, '%s\n', ['Section II: Thunderstorm beginning and end times estimated from manual observations']);
    fprintf(fw, '%s\n', 'Estimated Beginning,Estimated End,Estimated Duration (h)');
    for i = 1:length(MW_B_date_time)
        fprintf(fw, '%s\n', [datestr(MW_B_date_time(i),0) ',' datestr(MW_E_date_time(i),0) ',' num2str((MW_E_date_time(i)-MW_B_date_time(i))*24)]);
    end
    fprintf(fw, '\n');
    fclose(fw);
    out_file_count = out_file_count+1;
    out_file_label{out_file_count+1}=out_filename;
end

if ismember (7,sel)
    out_filename = fullfile(out_dir,['station_' num2str(asos_id) '_tsBE.csv']);
    fw = fopen( out_filename,'w' );
    try_count=0;
    while fw == -1
        err = errordlg({['Cannot write file: ' strrep(out_filename,'\','\\')], 'Make sure this file is not currently open.'},...
            'Error writing file');
        uiwait(err);
        try_count=try_count+1;
        if try_count>3, return; end
        fw = fopen( out_filename,'w' );
    end
    fprintf(fw, '%s\n', ['ASOS filename(s):,' sel_filename_list]);
    fprintf(fw, '%s\n', ['Station code:,' num2str(asos_id)]);
    fprintf(fw, '%s\n', ['Station description:,' station_dn{find(asos_id == station_no)}]);
    fprintf(fw, '%s\n', ['Output file type:,Thunderstorm beginning and end times']);
    fprintf(fw, '\n');
    fprintf(fw, '%s\n', ['Section I: Matching thunderstorm beginning and end times']);
    fprintf(fw, '%s\n', 'Beginning,End,Duration (h)');
    for i = 1:length(B)
        fprintf(fw, '%s\n', [datestr(B(i),0) ',' datestr(E(i),0) ',' num2str((E(i)-B(i))*24)]);
    end
    fprintf(fw, '\n');
    fprintf(fw, '%s\n', ['Section II: Reported thunderstorm beginning and ending times']);
    fprintf(fw, '%s\n', 'Reported Beginning,Reported End');
    for i = 1: max([length(B_date_time) length(E_date_time)])
        if i > length(B_date_time)
            fprintf(fw, '%s\n', [' ,' datestr(E_date_time(i),0)]);
        elseif i > length(E_date_time)
            fprintf(fw, '%s\n', [datestr(B_date_time(i),0) ', ']);
        else
            fprintf(fw, '%s\n', [datestr(B_date_time(i),0) ',' datestr(E_date_time(i),0)]);
        end
    end

    fclose(fw);
    out_file_count = out_file_count+1;
    out_file_label{out_file_count+1}=out_filename;
end

h = msgbox(out_file_label,'Analysis complete');
uiwait(h); 



