function res = kakuro_convert(in)
%
% res = kakuro_convert(in)
%
% Diese Programm konvertiert Kakuros von der Struktur-Form in die 3D-Form
% und umgekehrt. Die Beschreibung der beiden Formen findet man in
% kakuro_example.
%
% Winfried Kernbichler 13.05.2007

if isstruct(in)
   siz = size(in.hm);
   res = nan([siz,2]);
   
   % horizontal goes into res(:,:,1)
   val = unique(in.hm(in.hm~=0)).';
   for k = val
       num = find(in.hm == k);
       [kz,ks] = ind2sub(siz,num(1));
       res(kz,ks,1) = in.hv(k);
       res(num(2:end)) = 0;
   end

   % vertical goes into res(:,:,2)
   val = unique(in.vm(in.vm~=0)).';
   for k = val
       num = find(in.vm == k);
       [kz,ks] = ind2sub(siz,num(1));
       res(kz,ks,2) = in.vv(k);
       res(num(2:end)+prod(siz)) = 0;
   end
    
else
    % horizontal
    k = 1;
    kak = in(:,:,k).';
    ind_sum = find(kak~=0 & ~isnan(kak));
    ind_nan = [find(isnan(kak));numel(kak)+1];
    res.hv = kak(ind_sum).';
    res.hm = zeros(size(kak));
    for i = 1:length(ind_sum)
        i1 = ind_sum(i); 
        i2 = find(ind_nan > i1); i2 = ind_nan(i2(1))-1;
        [kz1,ks1] = ind2sub(size(kak),i1);
        [kz2,ks2] = ind2sub(size(kak),i2);
        if ks2 > ks1, i2 = sub2ind(size(kak),size(kak,1),ks1); end
        res.hm(i1:i2) = i;
    end
    res.hm = res.hm.';
    
    % vertical
    k = 2;
    kak = in(:,:,k);
    ind_sum = find(kak~=0 & ~isnan(kak));
    ind_nan = [find(isnan(kak));numel(kak)+1];
    res.vv = kak(ind_sum).';
    res.vm = zeros(size(kak));
    for i = 1:length(ind_sum)
        i1 = ind_sum(i); 
        i2 = find(ind_nan > i1); i2 = ind_nan(i2(1))-1;
        [kz1,ks1] = ind2sub(size(kak),i1);
        [kz2,ks2] = ind2sub(size(kak),i2);
        if ks2 > ks1, i2 = sub2ind(size(kak),size(kak,1),ks1); end
        res.vm(i1:i2) = i;
    end
    
end