function mkbadprf(navfile, outfile, year, flag_neighbors)
% function mkbadprf(navfile, outfile, year, flag_neighbors)
%
%  Makes a badprf.asc type file based on percent_good criteria;
%       for data where the PG is spotty and large regions of data
%       need to be flagged bad (but not physically removed from the
%       database) due to poor or no confidence.
%
%  INPUT:  the output of adcpsect run for navigation (*nav file) with
%          pg_min = minimum criteria for the reference layer bin range
%          to be used. We have used 80% for this criteria.
%
%
%  OUTPUT: outfile: file in badprf.asc format
%
%  Any profile is flagged bad if it, or either of its nearest neighbors,
%  has a bad velocity in the input .nav file.
%  Optional argument flag_neighbors, if set to 0, turns off the
%  flagging of neighbors.
%
%  Apply this file as you would any badprf.asc file.
%
%  96/07/23, JF, 96/11/27 modified for more general use
%  97/03/03 Shuiming modified to create badprf_pg80.asc
%  97/05/14 JF use read_asc to load data, eliminating need to strip
%   off header comments; input and output filenames now set by user
%  2000/09/21 EF changed it from script to function and simplified it.
%             Added ability to turn off neighbor flagging.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


if nargin < 3,
   error('Error: input arguments (navfile, outfile, year) are required.')
end

if ~ischar(navfile) | ~ischar(outfile) | ischar(year)
   error('Error: first two arguments must be filenames, third must be a year.')
end

if nargin == 3,
   flag_neighbors = 1;
end

[t, u] = read_asc(navfile);       % output from adcpsect run

badmask = ( u > 1000);        % bad values show up as 1E38

if flag_neighbors,
   badmask = badmask | [0; badmask(1:(end-1))] | [badmask(2:end); 0];
end

tbad=t(badmask) - 1/86400;      % subtract one second for CODAS search

ddate=to_date(year, tbad, 's');

%create an ASCII file in the same format as badprf.asc
bb = '  -1    0   0 ';
bb = bb(ones(length(tbad),1),:);
cc = [bb, ddate];

FID = fopen(outfile, 'w');
for ii = 1:length(tbad)
   fprintf(FID, '%31s\n', cc(ii,:));
end
fclose(FID);
