%Data from phodnet/data/cruisedat/WBTS
%Database includes ab01 ab02 ab03 ab0409 ab0509 ab0603 ab0609 ab0703
clear all;
%Check to see if historical databse exists and then load it
if exist('/Users/jhooper/Documents/Work_data/CTDCAL/Jay_toolbox/abico_historical_db.mat')==2,
    
    load /Users/jhooper/Documents/Work_data/CTDCAL/Jay_toolbox/abico_historical_db.mat;
    
else
    
    fprintf('No Database \n');
    
end;
%this gets intial length of matrix for adding nth column
ll=length(lat);
%ll=0;
%Read aoml.cal files
dl=length(dir('*.cal'));
cfiles=dir('*.cal');
cruiseid=cfiles(1).name(1:6);
stt1=str2num(cfiles(1).name(9));
%initiate variables
PRS = [];
TMP = [];
PTMP = [];
SAL = [];
OXY = [];
LAT = [];
LON = [];
stn = [];

%read calibrated data into a historical database
kk=0;
if ll~= 0,
    nn=ll+1;
end;

for jj = 1:dl,
    
    if stt1 == 0;
        kk=jj-1;
    else
        kk=jj;
    end; 
    
    stat=num2str(kk);
   


    % Allows for reading in three digit station numbers
    if (kk < 10)
       stn=['00',stat];
    elseif (kk >= 10 & jj < 100)
       stn=['0',stat];
    elseif (kk >= 100)
        stn=[stat];
    end;
    
    %Allow for read in of missing stations
    if ~exist([cruiseid,stn,'_aoml.cal']),
    %print bad station files    
    disp(['File ',stn,' Does Not Exist'])
    %count bad stations
    %bdstat=bdstat+1;
    
    %Print good stations being loaded
    disp([cruiseid,stn,'_aoml.cal'])
    
    else
    %reads in stations
    [PRS,TMP,PTMP,SAL,OXY]=textread([cruiseid,stn,'_aoml.cal'],'%f%f%f%f%*f%*f%f','headerlines',12);
    
    aoml=read_aoml2([cruiseid,stn,'_aoml.cal']);
    LAT=aoml.lat;
    LON=aoml.lon;
    clear aoml
    %check length of matrix
    if ll==0,
        nn=jj;
    end;
    %create matrix of data sets
    lat(nn) = LAT;
    lon(nn) = LON;
    prs(1:length(PRS),nn) = PRS;
    tmp(1:length(TMP),nn) = TMP;
    ptmp(1:length(PTMP),nn) = PTMP;
    sal(1:length(SAL),nn) = SAL;
    oxygen(1:length(OXY),nn) = OXY;
    stt(nn)=str2num(stn);
    if ll ~= 0,
        nn=nn+1;
    end;
    end;
    tmp(tmp==0)=nan;
    ptmp(ptmp==0)=nan;
    sal(sal==0)=nan;
    oxygen(oxygen==0)=nan;
    clear LAT LON;
end;
clear PRS TMP PTMP SAL OXY ans cfiles cruiseid dl jj kk stat stn stt1 nn ll

%return

save '/Users/jhooper/Documents/Work_data/CTDCAL/Jay_toolbox/abaco_historical_db.mat', 'prs tmp ptmp sal oxygen stt lat lon';
%save '/Users/jhooper/Documents/Work_data/CTDCAL/Jay_toolbox/abaco1202_cal_db.mat', 'prs tmp ptmp sal stt lat lon';
