function [ jd, wl, a, c ] = ac_import_profile( filename, start_line )
%AC_IMPORT Import data from ac-meter for both absorption and attenuation
%
% Inputs: 
%    Required:
%        filename string containing file name
%    Optional:
%        start_line integer containing the line at which data start
%          default: line 91
%
%
% Outputs:jd Nx1 double containing date in julian day
%         wl Mx1 double containing the wavelength 
%         a NxM double containing the absorption of the file
%         c NxM double containing the attenuation of the file
%
% Example:
% addpath ac_meters % add path to the toolbox, need to be adjusted
% [jd, wl, a, c] = ac_import_profile('run_21_ACS.001');
%
% Tested with: Matlab R2015a
%
% Author: Nils Haentjens, Ms, University of Maine
% Email: nils.haentjens@maine.edu
% Created: 14th July 2015
% Last update: 21th July 2015
%
% Inspired by:
%   read_acs91_v2
%     Written by Emmanuel Boss, UMAINE, 2009 for TARA.
%     Modified for 007 - Nov 6 2013
%     Modified by James Allen, 7/7/15

% Check input
if nargin > 2
   error('Too many input arguments')
elseif nargin < 1
   error('Not enough input arguments')
end
if nargin < 2;
  start_line = 91;
end;

% Read file
[jd, wl_a, wl_c, a, c] = import_file(filename, start_line);

% Interpolate wavelength
wl = wl_a;
c = interp1(wl_c, c, wl, 'linear', 'extrap');
a = a';
c = c';
end

function [jd, wl_a, wl_c, a, c] = import_file(filename, start_line)
  % Read file for a
  [fid, errmsg] = fopen(filename);
  if fid < 0; error(errmsg); end;

  % Skip first part
  for foo=1:start_line;
    tline = fgetl(fid);
  end;
  
  % Get wavelength
  data = strsplit(tline);
  wl_a = []; wl_c = [];
  i_a = []; i_c = [];
  for i=2:size(data, 2);
    foo = sscanf(data{i}, '%c%f');
    if ~isempty(foo)
      if foo(1) == char('a') % a
        wl_a(end+1) = foo(2);
        i_a(end+1) = i;
      elseif foo(1) == char('c') % c
        wl_c(end+1) = foo(2);
        i_c(end+1) = i;
      else
        warning('Wavelength not recognise %s', data{i});
      end;
    end;
  end;

  % Get data
  a=[]; c=[]; jd = [];
  tline = fgetl(fid);
  while ischar(tline)
    data = strsplit(tline);
    jd(end+1, 1) = str2double(data(1));
    a(:, end+1) = str2double(data(i_a));
    c(:, end+1) = str2double(data(i_c));
    tline = fgetl(fid);
  end;
  fclose(fid);
end
