function bad(bin,new_key_bp,nprf)
%
% Usage:  bad(bin)
%         bad(bin,new_key_bp)
%         bad(bin,nprf)
%         bad(bin,new_key_bp,nprf)
%
% Modified: 9-05-89 to accept bin range and no. of profiles for flagging (JR)
% Modified: 9-22-89 to also set error velocity at bad bins to NaN (JR)
%
% A function to set U, V, and W at those bins indicated in the <bin> vector
% to NaN for the key and, optionally, subsequent profiles.
% If the two-element <new_key_bp> vector is provided, the key profile is reset
% to <new_key_bp> and flagging occurs from thereon.
% If the <nprf> argument is provided, the same bins are flagged for the
% <nprf> profiles following the key.

%editglob
global EDIT_MODE IKEY IBLKPRF NBINS NPRFS BADBIN BADBIN_BAK LISTED
global LASTPLOT LASTCOMM


if ~EDIT_MODE
  error('You are not in edit mode.  Set EDIT_MODE = 1 to enable.')
end

if nargin < 1
  zap
  return
end

if isempty(IKEY) & (nargin == 1 | (nargin >= 2 & length(new_key_bp) ~= 2))
  error('Key on profile first before running bad without a new_key_bp arg')
end

if nargin == 1
  nprf = 0;
  new_key_bp = IBLKPRF(IKEY,:);
elseif nargin == 2
  if length(new_key_bp) == 1
    nprf = new_key_bp;
    new_key_bp = IBLKPRF(IKEY,:);
  elseif length(new_key_bp) == 2
    nprf = 0;
    k(new_key_bp(1), new_key_bp(2))
  else
    error('Second argument must either be new_key_bp or nprf')
  end
elseif nargin == 3
  if length(new_key_bp) ~= 2 | length(nprf) > 1
    error('Usage: bad(bin, new_key_bp, nprf)')
  end
  k(new_key_bp(1), new_key_bp(2))
end

if min(bin) < 1 | max(bin) > NBINS
  error('Invalid bin number.')
end;

badi = [IKEY:IKEY+nprf];
if max(badi) > NPRFS
  error('Too many profiles.');
end;

BADBIN_BAK = BADBIN;
iflagged = find(BADBIN ~= 0);
BADBIN(bin,badi) = -2 * ones(length(bin),length(badi));
BADBIN(iflagged) = BADBIN_BAK(iflagged);  % reset already flagged bins to orig. values

LISTED = 0;             % bad bins flagged but not yet recorded in file
LASTCOMM = 'badbin';
eval(LASTPLOT);
