function mkbadtimes(tr, sm_file, yr)
%  mkbadtimes(tr, sm_file, yr)
%
%  Makes a badprf.asc type file for all profiles within input time ranges
%
%  INPUT:  
%   tr is an array of size n X 2 containing the endpoints
%     of the timeranges which define the segments
%
%   reads in output of smoothr:  *.sm 
%	   Edit input filename below. 
%
%  OUTPUT: file badprf_times.asc (edit below as needed)
%
%  Times are decreased by 1 second (to deal with roundoff 
%  error) then input into function to_date, to generate
%  times in the yy/mm/dd hh:mm:ss format necessary for input to dbupdate.
%  Creates (and appends to) file badtimes.asc in the badprf.asc format.
%
%  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 
%  98/01/05 JF modified mkbadprf.asc to a do what it says above...
%
% EDIT next section or pass in values as arguments
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if (nargin < 3)
   yr=1997;				% must edit year
end

if (nargin < 2) 
   sm_file = '../nav/rot001052.sm';	% path and filename of smoothr output
end

if (nargin == 0)
   help mfilename
   error('must (at least) specify time range')
end


outfile = 'badtimes.asc';   	% writes here by default

%%%%%%%%%%%%%%%%%%%%%%%%%%% END of EDITING %%%%%%%%%%%%%%%%%%%%%%%%%%%
sm = read_asc(sm_file);	

te = sm(:,1);                            % ensemble times
[nsm,nc]=size(te);
 
[ntr,nn]=size(tr);			 % ntr = # segments

% create a logical mask, the size of t, where value is set
%  to 1 for those times which fall within the timeranges
 
seg_mask=zeros(nsm,1);                  % initialize use mask
 
for ii=1:ntr
 seg_mask=seg_mask | (te>= tr(ii,1) & te<= tr(ii,2));
end
i_use=find(seg_mask);                   % indices to use
[ne,ns]=size(i_use);


 onesec= 1/(3600*24);
 tbad=te(i_use);
 tbad=tbad-onesec;		% subtract one second for roundoff error

 ddate=to_date(yr,tbad,'s');	% convert to string format

 fil=[ -1 0 0 ];
 fill=fil(ones(length(tbad),1),:);	% first 3 columns

%create an ASCII file in the format as same as badprf.asc

aa=ddate(:,3:19);
bb='  -1    0   0 ';
bb=bb(ones(length(tbad),1),:);
cc=[bb aa];
  FID=fopen(outfile, 'a');
	for ii=1:length(tbad)
		fprintf(FID,'%31s\n',cc(ii,:));
	end
fclose(FID);

fprintf('wrote %d bad profile times to %s\n', length(tbad), outfile)

