%converter for Matt Kittelberger
clear all

MaxClusters = 5;
path = 'C:\Documents and Settings\bruce land\My Documents\Matlab\Kittelberger\';
filename= 'pn05011.020905.002timesMissing33toEnd.txt';
%[filename,path] = uigetfile('*.txt','Choose a data file');
if (filename==0)
    return
end

%cut off '.txt' and add '.xls'
filebase=filename(1:strfind(filename,'.txt')-1);
fname  =  ([path,filename]);

allData = textread (fname,'%s','delimiter','\n','bufsize',2^14)  ;

Nsets=0;

%make each set/sweep/cluster a vector in a cell
% Stimes{Sset,Ssweep,Scluster}
for i=1:length(allData)
    FirstToken = strtok(allData{i});
    
    %skip to next line of input if empty
    if (isempty(FirstToken)) 
           continue 
    end
    %otherwise handle the line    
    switch FirstToken
        case 'Set'
            SetSweep = sscanf(allData{i},'Set %d Sweep %d')
            Sset = SetSweep(1);
            Ssweep = SetSweep(2);
            if (Sset>Nsets) %count the total number of sets
                Nsets=Sset;
            end
            count(1:MaxClusters) = 0;
        otherwise
            TimeCluster = sscanf(allData{i},'%f %f');
            Stime = TimeCluster(1);
            Scluster = TimeCluster(2);
            if (Scluster > 0)
                count(Scluster) = count(Scluster) + 1;
                Stimes{Sset,Ssweep,Scluster}(count(Scluster)) = Stime;
            end
    end
end

%now make some ascii files
[a,b,c] = size(Stimes);
for Scluster=1:c
    fileout = [filebase,'Cluster',num2str(Scluster,'%0d'),'.txt'];
    fileout = ([path,fileout]);
    fid = fopen(fileout,'w');
    rowcounter = 1;
    for Sset=1:a
        for Ssweep=1:b
            if (isempty(Stimes{Sset,Ssweep,Scluster}))
                rowStart = [Sset,Ssweep];
                rowEnd = ' ';
            else
                rowStart = [Sset,Ssweep];
                rowEnd = [Stimes{Sset,Ssweep,Scluster}];
            end
            rowSS = num2str(rowStart,'%d\t%d\t');
            rowSE = num2str(rowEnd,'%d\t');
            fprintf(fid,'%s \t \t %s\n\r',rowSS,rowSE);
            %rowcounter = rowcounter + 1;
            
        end
    end
    %and finish with blank sets
    for Sset=a+1:Nsets
        for Ssweep=1:b
            rowStart = [Sset,Ssweep];
            rowSS = num2str(rowStart,'%d\t%d\t');
            fprintf(fid,'%s\n\r',rowSS);
            %rowcounter = rowcounter + 1;
        end
    end
    
    fclose(fid);
end

%set(gcf,'pointer','arrow');


