You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
    Metadata details:
    filename: reshapetimeseries.m
    path of file: ./repos/CDT/cdt
    
    the code of the file until where you have to start completion: function [xg, yr, tmid] = reshapetimeseries(t, x, varargin)
%RESHAPETIMESERIES Reshapes timeseries data to year by time-of-year grid
%
% [xg, yr] = reshapetimeseries(t, x)
% [xg, yr] = reshapetimeseries(t, x, p1, v1, ...)
% [xg, yr, tmid] = reshapetimeseries(t, x, p1, v1, ...)
%
% This function reshapes timeseries data onto a grid, taking care of any
% concatenation issues that would result from leap days or uneven data
% spacing.
%
% Input variables:
% 
%   t:          vector of datetime values
%
%   x:          vector of values corresponding to times in t
%
% Optio
    
function handle, function to apply to data when
%               mutliple data points fall within a single time bin.
%               [@nanmean]  
%
%   pivotdate:  1 x 2 vector of month and day that marks the switch from
%               one year to the next.  By default this is [1 1], i.e. Jan
%               1.
%
% Output variables:
%
%   xg:         x data regridded to a time-of-year x year matrix.  
%               
%   yr:         years corresponding to the columns of the output matrix xg.
%               Note that when a custom pivot date is entered, these years
%               correspond to the dates in the first row of the matrix, but
%               a calendar year change will occur within each column.
%
%   tmid:       datetime from first non-leap year in dataset corresponding
%               to rows of output matrix.

% Copyright 2019 Kelly Kearney

p = inputParser;
p.addParameter('bin', 'date');
p.addParameter('yrlim', [NaN NaN], @(x) validateattributes(x, {'numeric'}, {'integer', 'nondecreasing','size', [1 2]}));
p.addParameter('func', @nanmean, @(x) validateattributes(x, {'function_handle'}, {}));
p.addParameter('pivotdate', [1 1], @(x) validateattributes(x, {'numeric'}, {'vector', 'numel', 2}));

p.parse(varargin{:});
Opt = p.Results; 

% Parse and check bin input

if isnumeric(Opt.bin)
    validateattributes(Opt.bin, {'numeric'}, {'scalar', 'positive', 'integer'}, 'reshapetimeseries', 'bin');
    flag = false;
else
    validateattributes(Opt.bin, {'char','string'}, {'scalartext'}, 'reshapetimeseries', 'bin');
    validatestring(Opt.bin, {'date', 'month'});
    flag = true;
end

% Calculate date limits

if isnan(Opt.yrlim(1))
    if min(t) < datetime(min(year(t)), Opt.pivotdate(1), Opt.pivotdate(2))
        Opt.yrlim(1) = min(year(t)) - 1;
    else
        Opt.yrlim(1) = min(year(t));
    end