%polysplit
%convert line or polygon parts from vector form to cell array 
%form, essentially does the reverse of polysplit
%returns the NaN ended segments of vectors latcells and loncells 
%one vector per cell of new cell arrays lat and lon
%latcells and loncells must be either column or row vectors, lat 
%and lon are outputted cell arrays



function [lat, lon] = polysplit(latcells, loncells)

%check to make sure there are the correct amount of arguments and they are of correct size, type, and format
if ~(nargin == 2)
  error('Incorrect number of input arguments.');
end


if(isempty(latcells) | isempty(loncells))
    error('Inputted vectors must not be empty.');
end

if~(isnumeric(latcells) | isnumeric(loncells))
  error('Inputted vectors must be of numeric type.');
end


if ~(size(latcells) == size(loncells))
  error('input vector sizes must match');
end

latnan = find(isnan(latcells));
lonnan = find(isnan(loncells));
if  ~(isequal(latnan, lonnan))
  error('Vectors must have Identically Placed NaNs')
end
column = false;

%check if input vectors are of column type or not;
if(iscolumn(latcells) | iscolumn(loncells))
  latcells = latcells';
  loncells = loncells';
  column = true;
end

%outputs column vectors to cell array
if column
  latcells = [latcells, NaN];
  loncells = [loncells, NaN];
  latnan = find(isnan(latcells));
  lonnan = find(isnan(loncells));
  lat{1} = latcells(1:(latnan(1)-1))';
  lon{1}= loncells(1:(lonnan(1)-1))';
  for i= 2:length(latnan)
    lat{i} = latcells(latnan(i - 1) + 1:(latnan(i)-1))';
    lon{i}= loncells(lonnan(i -1) +1:(lonnan(i) - 1))';
  end
end

%outputs row vectors to cell array
if ~column
  latcells = [latcells, NaN];
  loncells = [loncells, NaN];
  latnan = find(isnan(latcells));
  lonnan = find(isnan(loncells));
  lat{1} = latcells(1:(latnan(1)-1));
  lon{1}= loncells(1:(lonnan(1)-1));
  for i= 2:length(latnan)
   lat{i} = latcells(latnan(i - 1) + 1:(latnan(i)-1));
   lon{i}= loncells(lonnan(i -1) +1:(lonnan(i) - 1));
   end
end
 endfunction
