% readbuddynetcdf - 
%
% reads the buddy profiles so they can be plotted.  You must supply "ss"
% which is the unique id of the profile to be retrieved and "filenam" which 
% is the database prefix.
%  
%   Outputs are btemp, bdepth and bqc which can then be plotted.


clear temp depth qc ;

%profiledata=handles.profile_data;

nss=num2str(ss);
if(exist('raw','var'))
    if(raw)
    else
        raw=0;
    end
else
    raw=0;
end
filen=getfilename(nss,raw);

filenam=[filenam '\' filen];
if(ispc)
    findslash=strfind(filenam,'/');
    if(~isempty(findslash))
        filenam(findslash)='\';
    end
else
    findslash=strfind(filenam,'\');
    if(~isempty(findslash))
        filenam(findslash)='/';
    end
end

format short g
bfile=netcdf(filenam);


nprof=bfile{'No_Prof'}(:);
ptype=getnc(filenam,'Prof_Type');

if(nprof==1);ptype=ptype';end

%if(nprof==1);ptype=ptype';end

pt=strmatch('TEMP',ptype);

h=squeeze(bfile{'Profparm'}(:,:,:,:,:));
    
de=bfile{'Depthpress'}(:,:);

if(nprof==1)
    de=de';
end
tempqc=squeeze(bfile{'ProfQP'}(:,:,:,:,:,:));

close(bfile);
dnan=find(~isnan(de));
%de=de(dnan);
%h=h(dnan);
[m,n]=size(h);
clear bqc
clear bqct
if(n==nprof)
     temp=h(:,pt);
     bdepth=de(:,pt);
     bqct=tempqc(:,pt);
     bb=find(bqct=='3' | bqct=='4');
     bqc=zeros(size(bqct));
     bqc=bqc+1;
     bqc(bb)=4;
     
else
     temp=h(pt,:);
     bdepth=de(pt,:);
     bqct=tempqc(pt,:);
     bb=find(bqct=='3' | bqct=='4');
     bqc=zeros(size(bqct));
     bqc=bqc+1;
     bqc(bb)=4;
end

%if(nprof==1);bqc=bqc';end

gg=find(temp>=99. | temp <-99.);
btemp=temp ;  %;change(temp,'>',99.,NaN);
if(~isempty(gg))
    btemp(gg)=NaN;
    bdepth(gg)=NaN;
    bqc(gg)=NaN;
end


