function bugs2avgbugs(basepath,cruise,vprnum,metapath)
%VPR code for converting vpr#bugs files into vpr#avgbugs files. Conversion
%adds depth average and metadata to files.



fn=[basepath filesep cruise filesep 'processed' filesep 'merged' filesep vprnum 'bugs.mat'];
load(fn);
interval1=1;
%Bin by pressure (size=interval1)
    
h=0:interval1:ceil(max(data(:,1))/interval1)*interval1;
avgb=NaN(length(h),size(data,2));
for i=2:length(h)
    j=find(data(:,1)'>h(i-1) & data(:,1)'<=h(i));
    if isempty(j)~=1
        if length(j)==1,avgb(i-1,:)=data(j,:);end
        if length(j)~=1,avgb(i-1,:)=mean(data(j,:));end
    end
end
k=find(~isnan(avgb(:,1)));  %Finds rows with NaNs
avgb=avgb(k,:);
clear h i j k;

%Add depth measurement
depth=ceil(avgb(:,1))-.5;
avgb=[depth,avgb];
variables=['depth',blanks(15);variables];


if exist(metapath,'file')
    eval(['load ' metapath])
    [~,name,~]=fileparts(metapath);
    eval(['vprpos=' name '; clear ' name ' name;'])
    [x,y]=size(avgb);
    run=str2num(vprnum(4:end));
    q=find(vprpos(:,8)==run);
    avgb=[vprpos(q,1)*ones(x,1),vprpos(q,2)*ones(x,1),vprpos(q,3)*ones(x,1),...
          vprpos(q,4)*ones(x,1),vprpos(q,5)*ones(x,1) vprpos(q,6)*ones(x,1),...
          vprpos(q,8)*ones(x,1),vprpos(q,9)*ones(x,1),avgb(:,1:y)];
    clear x y q;

    variables=['Year                ';
               'Month               ';
               'Day                 ';
               'Time (Decimal Hour) ';
               'Latitude            ';
               'Longitude           ';
               'VPR Cast            ';
               'Station             ';
               variables];
end

if exist([basepath filesep cruise filesep 'processed' filesep 'finaloutput'],'dir')~=7,
	dos(['mkdir ' basepath filesep cruise filesep 'processed' filesep 'finaloutput']);
end
    
savepath=[basepath filesep cruise filesep 'processed' filesep 'finaloutput' filesep vprnum 'avgbugs.mat'];
eval(['save ' savepath ' avgb variables'])

clear data avgb 'variables'; 


