function [xst, cutIndex, pointsCut] = cutVecforReshape(xstruct,window_sec,varargin)

% Cut time vector for reshape bin avging (e.g., 5 sec bins)

time = xstruct.time;
time_step = xstruct.time_step;

if any(strcmpi(varargin, 'end')) || any(strcmpi(varargin, 'start'))
    
    m = input('date_cutoff entered - Truncate time vector?, Y/N [Y]:','s');
    if isempty(m); m='Y'; end
    if m~='N'
        date_cutoff = varargin{2};
        
        if numel(date_cutoff)==1
            if any(strcmpi(varargin, 'end'))
                % case datestr
                if ischar(date_cutoff)
                    time = time(1:closest(datenum(date_cutoff),xstruct.time));
                    % case index
                elseif isnumeric(date_cutoff)
                    time = time(1:date_cutoff); % 62931
                end
                
                if date_cutoff~=size(time,2)
                    warning('[cutVecforReshape]: Truncated time vector!')
                end
            end
            
            if any(strcmpi(varargin, 'start'))
                % case datestr
                if ischar(date_cutoff)
                    time = time(closest(datenum(date_cutoff),xstruct.time):end);
                    % case index
                elseif isnumeric(date_cutoff)
                    time = time(date_cutoff:end);
                end
            end
            
        elseif len(date_cutoff)==2
            
            if iscell(date_cutoff)
                time = time(closest(datenum(date_cutoff(1)),xstruct.time):closest(datenum(date_cutoff(2)),xstruct.time));                
                % case index
            elseif isnumeric(date_cutoff)
                time = time(date_cutoff(1):date_cutoff(2));                
            end
            
        end
    end
else
    warning('[cutVecforReshape]: Got it. Setting truncate time index to size(time,2)...')
end

int = round(window_sec/time_step); timemod=time; k=0;
while mod(length(timemod),int)~=0 && k<200
    k=k+1;
    timemod = time(1:end-k);
end; clear timemod

t1 = time(1);
t2 = time(end-k);
cutIndex = find(time>=t1 & time<=t2); % 1:length(time);
pointsCut=k;


% quick-chopp state-struct and controls-mat
fn = fieldnames(xstruct);
for k=1:len(fn)
    if ~isstruct(xstruct.(fn{k}))
        if len(xstruct.(fn{k}))>=len(cutIndex)
            tmp = xstruct.(fn{k});
            xst.(fn{k})=tmp(cutIndex);
        else
            xst.(fn{k})=xstruct.(fn{k});
            warning(['[cutVecforReshape]: Did not process struct field: ' fn{k}]);
        end
    end
end
xst.int = int;


% quick-fix some funky values for certain variables
xst.propOmega(xst.propOmega>50) = NaN;
xst.z(xst.z<0)=0;
xst.u(xst.u>3)=NaN;
% xstruct.z(xstruct.z>100)=NaN;

end
