function write_hydrolight_4(varargin)
% 13 write_hydrolight(filename,acdepth,adata,cdata,agdepth,agdata,cgdata,wvl,bbdepth,bbdata,bbwvl,chldepth,chldata)
% 11 write_hydrolight(filename,acdepth,adata,cdata,agdepth,agdata,cgdata,wvl,bbdepth,bbdata,bbwvl)
% 10 write_hydrolight(filename,acdepth,adata,cdata,agdepth,agdata,cgdata,wvl,chldepth,chldata)
% 9 write_hydrolight(filename,acdepth,adata,cdata,wvl,bbdepth,bbdata,bbwvl,rnd)
% 8 write_hydrolight(filename,acdepth,adata,cdata,agdepth,agdata,cgdata,wvl)
% 7 write_hydrolight(filename,acdepth,adata,cdata,wvl,chldepth,chldata)
% 5 write_hydrolight(filename,acdepth,adata,cdata,wvl)
% 4 write_hydrolight(filename,bbdepth,bbdata,bbwvl)
% 3 write_hydrolight(filename,chldepth,chldata)
%
% Does some simple error-checking and writes Hydrolight compatible input
% files.  Uses number of inputs to determine which hyrdolight files to
% write.  Explanation of which inputs are which is above.  
% Input
% Explanations:
%
% filename is a string that will be a common part of each file written
% acdepth is a vector of depths total acs data is collected at (recommend using
%       GSW toolbox gsw_z_from_p and gsw_depth_from_z to get depths from
%       recorded pressure if applicable)
% adata is a_t total absorption array (minus a_w)
% cdata is c_t total attenuation array (minus c_w)
% agdepth is a vector of depths CDOM (filtered) acs data is collected at
% agdata is a_g CDOM absorption array (minus a_w)
% cgdata is c_g CDOM absorption array (minus c_w)
% wvl is wavelengths for your acs instrument
% bbdepth is a vector of depths backscatter is collected at
% bbdata is b_t total backscatter array (including bb_w)
% bbwvl is wavelengths for your bb instrument
% chldepths is a vector of depths at which chl data is collected
% chldata is chl data vector
% rnd is a meaningless random number (or anything else, really)
%
% Output Explanations:
% ACS<filename>.txt contains a_t and c_t
% ACS_CDOM<filename>.txt contains a_g and c_g
% BB<filename>.txt contains bb_t
% CHL<filename>.txt contains chl (extrapolated from line height if chl is
%      not given but a_t and a_g are)
% APSTAR<filename>.txt contains a_p* averaged by depth

% ENA 7/30/2013
%% Define inputs
if length(varargin)<3
    error('err:wronginputsize','Not enough inputs')
elseif length(varargin)>13
    error('err:wronginputsize','Too many inputs')
elseif length(varargin)==12 || length(varargin)==6
    error('err:wronginputsize','Wrong number of inputs')
elseif length(varargin)==3
    chldataus=varargin{3};
    chldepthus=varargin{2};
elseif length(varargin)==4
    bbdepthus=varargin{2};
    bbdataus=varargin{3};
    bbwvl=varargin{4};
else
    acdepthus=varargin{2};
    adataus=varargin{3};
    cdataus=varargin{4};
    if length(varargin)==5 || length(varargin)==9 || length(varargin)==7
        wvl=varargin{5};
        if length(varargin)==9
            bbdepthus=varargin{6};
            bbdataus=varargin{7};
            bbwvl=varargin{8};
        elseif length(varargin)==7
            chldataus=varargin{7};
            chldepthus=varargin{6};
        end
    elseif length(varargin)>7
        agdepthus=varargin{5};
        agdataus=varargin{6};
        cgdataus=varargin{7};
        wvl=varargin{8};
        if length(varargin)==10
            chldataus=varargin{10};
            chldepthus=varargin{9};
        else
            bbdepthus=varargin{9};
            bbdataus=varargin{10};
            bbwvl=varargin{11};
            if length(varargin)==13
                chldataus=varargin{13};
                chldepthus=varargin{12};
            end
            
        end
    end
end
filename=varargin{1};

%% Double Check Inputs
if exist('acdepthus','var')
    if ~isvector(acdepthus)
        error('err:baddepth','Depth must be scalar or vector')
    elseif ~iscolumn(acdepthus)
        acdepthus=acdepthus';
    end
end
if exist('bbdepthus','var')
    if ~isvector(bbdepthus)
        error('err:baddepth','Depth must be scalar or vector')
    elseif ~iscolumn(bbdepthus)
        bbdepthus=bbdepthus';
    end
end
if exist('chldepthus','var')
    if ~isvector(chldepthus)
        error('err:baddepth','Depth must be scalar or vector')
    elseif ~iscolumn(chldepthus)
        chldepthus=chldepthus';
    end
end
if ~ischar(filename)
    warning('err:badfilename','Filename must be string')
end
if exist('wvl','var')
    if ~isvector(wvl)
        error('err:badwvl','Wavelength must be scalar or vector')
    elseif iscolumn(wvl)
        wvl=wvl';
    end
end
if exist('bbwvl','var')
    if ~isvector(bbwvl)
        error('err:badbbwvl','Wavelength must be scalar or vector')
    elseif iscolumn(bbwvl)
        bbwvl=bbwvl';
    end
end

%% ACS File
if length(varargin)>4
    if exist(['ACS',filename,'.txt'],'file')
        warning('wrn:exists','filename already exists.  overwriting.')
        delete(['ACS',filename,'.txt'])
    end
acsstr={'Example data file of ac-9 data on the Hydrolight "ac-9 standard format."';                                      
'This file contains ac-9 data binned in 25 cm depth bins, starting with ';
'the first measured depth.  The absorption coefficient at 412 nm is ';
'plotted as the left-hand curve of Fig. 1 in the Hydrolight 4.0 Users Guide.';
'This file will be read by user "ab" routine "abac9"';
'Ten ascii header records (for identification of the users data) are expected. ';
'record 11 contains the number of wavelengths and the nominal wavelengths (free format)';
'records 12 and onward contain the (free-format) ac-9 data ordered as:';
'   depth, a(wavelength 1), ..., a(wavelength n), c(wavelength 1), ..., c(wavelength n)';
'Flag the end of file with a negative depth or an end of file.'};

[acdepthu,acsort]=sort(acdepthus);
[acdepth,acunique,~]=unique(acdepthu);
adatau=adataus(acsort,:);
adata=adatau(acunique,:);
cdatau=cdataus(acsort,:);
cdata=cdatau(acunique,:);

acsfname = ['ACS',filename,'.txt'];
fid3 = fopen(acsfname, 'wt');
wvlline=[length(wvl) wvl];        

for j=1:10
fprintf(fid3, '%s\n', acsstr{j});
end
fclose(fid3);

dlmwrite(acsfname,wvlline,'delimiter',' ','-append');
dlmwrite(acsfname,[acdepth adata cdata],'delimiter',' ','-append');
dlmwrite(acsfname,-1.*ones(1,length(wvl).*2+1),'delimiter',' ','-append');
end
%% ACS CDOM File
if length(varargin)>9 || length(varargin)==8
    if exist(['ACS_CDOM',filename,'.txt'],'file')
        warning('wrn:exists','filename already exists.  overwriting.')
        delete(['ACS_CDOM',filename,'.txt'])
    end

[agdepthu,agsort]=sort(agdepthus);
[agdepth,agunique,~]=unique(agdepthu);
agdatau=agdataus(agsort,:);
agdata=agdatau(agunique,:);
cgdatau=cgdataus(agsort,:);
cgdata=cgdatau(agunique,:);

acsgfname = ['ACS_CDOM',filename,'.txt'];
fid3 = fopen(acsgfname, 'wt');       

for j=1:10
fprintf(fid3, '%s\n', acsstr{j});
end
fclose(fid3);

dlmwrite(acsgfname,wvlline,'delimiter',' ','-append');
dlmwrite(acsgfname,[agdepth agdata cgdata],'delimiter',' ','-append');
dlmwrite(acsgfname,-1.*ones(1,length(wvl).*2+1),'delimiter',' ','-append');
end

%% BB File
if length(varargin)>10 || length(varargin)==4 || length(varargin)==9
    if exist(['BB',filename,'.txt'],'file')
        warning('wrn:exists','filename already exists.  overwriting.')
        delete(['BB',filename,'.txt'])
    end
  bbstr={'EXAMPLE HYDROSCAT-6 DATA showing the Hydrolight Standard Format for HS-6 data.';
'(These data were taken in conjunction with files AC9_total.txt and AC9_filtered.txt.)';
'NOTE: These bb values are the total (water + particle) backscatter coef b_b, ';
'which is customary for Hydroscat data.  Pure sea water bb values will be removed';
'by Hydrolight to get the particle bb. ';
'The original Hydroscat data were binned in 0.5 meter depth bins, starting with the ';
'first recorded depth; the depths shown here are the average depth of the data in each bin.  ';
'Column headers (depth in m and bb in 1/m):';
 'depth      bb442       bb488       bb532       bb590       bb620       bb671';
'Record 11 gives the number of wavelengths and the wavelengths:  '};

[bbdepthu,bbsort]=sort(bbdepthus);
[bbdepth,bbunique,~]=unique(bbdepthu);
bbdatau=bbdataus(bbsort,:);
bbdata=bbdatau(bbunique,:);

bbfname = ['BB',filename,'.txt'];
fid3 = fopen(bbfname, 'wt');
bbwvlline=[length(bbwvl) bbwvl];        

for j=1:10
fprintf(fid3, '%s\n', bbstr{j});
end
fclose(fid3);

dlmwrite(bbfname,bbwvlline,'delimiter',' ','-append');
dlmwrite(bbfname,[bbdepth bbdata],'delimiter',' ','-append');
dlmwrite(bbfname,-1.*ones(1,length(bbwvl).*2+1),'delimiter',' ','-append');
end

%% CHL File
if length(varargin)==3 || length(varargin)==8 || length(varargin)>9
    if exist(['CHL',filename,'.txt'],'file')
        warning('wrn:exists','filename already exists.  overwriting.')
        delete(['CHL',filename,'.txt'])
    end
    chlstr={'Example "chlzdata" file showing the Hydrolight "Chlorophyll-data standard format"';
'These files are read by Hydrolight subroutine "chlzdata" on file ..\maincode\chlzdata.f';
'Ten ascii header records (for identification of the users data) are expected.';
'Record 11 begins with (free format) pairs of depth (in m) and Chl (in mg Chl / m^3) values.';
'The last value is flagged by either an end of file or by negative depth and Chl values';
'Record 6:  unused in this example';
'Record 7:   "';
'Record 8:   "';
'Record 9:   "';
'depth (m)   Chl (mg/m^3)'};
if length(varargin)==8 || length(varargin)==11
    warning('wrn:nochl','No chl data supplied.  Calculating from line height')
    atchl=zeros(size(adata,1),3);
    agchl=zeros(size(agdata,1),3);
    for i=1:size(adata,1)
        atchl(i,:)=interp1(wvl,adata(i,:),[650 676 715]);
    end
    for i=1:size(agdata,1)
        agchl(i,:)=interp1(wvl,agdata(i,:),[650 676 715]);
    end
    if max(agdepth)<max(acdepth)
% if min(agdepth)<min(acdepth)
% agshrink=agdepth(agdepth>min(acdepth));
% else
agshrink=agdepth;
% end
        atchli=zeros(size(adata,1),3);
        for i=1:3
            atchli(:,i)=interp1(acdepth,atchl(:,i),agshrink);
        end
        achln=atchli-agchl;
% achl=achln(~isnan(achln));
achl=achln;
chldepth=agdepth;
% chldepth=agshrink(~isnan(achln));
    elseif max(acdepth)<max(agdepth)
% if min(acdepth)<min(agdepth)
% acshrink=acdepth(acdepth>min(agdepth));
% else
acshrink=acdepth;
% end
        agchli=zeros(size(adata,1),3);
        for i=1:3
            agchli(:,i)=interp1(agdepth,agchl(:,i),acshrink);
        end
        achln=atchl-agchli;
% achl=achln(~isnan(achln));
achl=achln;
% chldepth=acshrink(~isnan(achln));
chldepth=acdepth;
    end
    chldata=(achl(:,2)-(39.*achl(:,1)./65)+(26.*achl(:,3)./65))./0.014;
else
    [chldepth,chlsort]=sort(chldepthus);
    chldata=chldataus(chlsort,:);
end
chlfname = ['CHL',filename,'.txt'];
fid3 = fopen(chlfname, 'wt');

for j=1:10
    fprintf(fid3, '%s\n', chlstr{j});
end
fclose(fid3);

dlmwrite(chlfname,[chldepth chldata],'delimiter',' ','-append');
dlmwrite(chlfname,-1.*ones(1,2),'delimiter',' ','-append');
end
%% APSTAR File
if length(varargin)==8 || length(varargin)>9
    if exist(['APSTAR',filename,'.txt'],'file')
        warning('wrn:exists','filename already exists.  overwriting.')
        delete(['APSTAR',filename,'.txt'])
    end
medat=nanmedian(adata);
medag=nanmedian(agdata);
medap=medat-medag;
apstar=medap/nanmedian(chldata);
apstarstr={'"CHLOROPHYLL-SPECIFIC ABSORPTION" coefficient, achl*(wavelength) in m^2/mg, ';
'for use by the IOP (ab) and chlorophyll-fluorescence routines.  This file contains ';
'the ac* data of Prieur and Sathyendranath, 1981, Limnol & Oceanogr, 26(4), 671-689,'; 
'Table 2 Columm 3, scaled so that ac*(440nm) equals 0.05.  This file is consistent ';
'with the Prieur-Sathyendranath-Morel model for absorption by Chl (Light & Water Eq. 3.27)';
'as used in routine abcase1.  Values below 400 and above 700 nm were extrapolated by eye.';
'Note that the abcase1 model normalizes these values to 1 at 440nm, whereas';
'fluorescence routine shatchl (in file shat.f) requires absolute values, as given here. ';
'wavelength    a*';
'(nm)        (m^2/mg'};
apsfname = ['APSTAR',filename,'.txt'];
fid3 = fopen(apsfname, 'wt');

for j=1:10
    fprintf(fid3, '%s\n', apstarstr{j});
end
fclose(fid3);

dlmwrite(apsfname,[wvl' apstar'],'delimiter',' ','-append');
dlmwrite(apsfname,-1.*ones(1,2),'delimiter',' ','-append');
end


    
  