function [aa,h,N,IV]=RCMlese(Datei,varargin)
%function [aa,h,N,IV]=RCMlese(Datei,varargin)
% Variable arguuments:
% NOMAT
% ARC,LOW,WIDE,HIGH
%        sets the temperature range
% XTIME; zum setzen des Anfangszeitpunktes und increment
%        als nachstes Argument (julday,timeincrement)
%        wird nur benutzt, falls keine Zeit vorhanden
% NODATE; damit wird angegeben, dass 0007 Records keine Zeit
%        sondern Daten enthalten
%
% J.Holfort

%  1 dbar = 1e4 Pascal
aa=[];h=[];N=[];IV=zeros(6,1);
nomat=0;  % use/write matlab file is possible
Xtemp=0;  % take standard temperature
nodate=0;
rcm_id='';

timestep=1/24; timestart=0;

%% decode variable arguments
ii=2;
while ii<=nargin
  t=varargin{ii-1};
  if ischar(t) & strcmp(upper(t),'NOMAT')
    nomat=1;
  elseif ischar(t) & strcmp(upper(t),'DCM')
    Xtemp=-1;
  elseif ischar(t) & strcmp(upper(t),'ARC')
    Xtemp=1;
  elseif ischar(t) & strcmp(upper(t),'LOW')
    Xtemp=2;
  elseif ischar(t) & strcmp(upper(t),'WIDE')
    Xtemp=3;
  elseif ischar(t) & strcmp(upper(t),'HIGH')
    Xtemp=4;
  elseif ischar(t) & strcmp(upper(t),'XTIME')
    ii=ii+1;
    t=varargin{ii-1};
    if ischar(t); error('XTIME must be folllowed by nummber'); end
    timestart=t(1);
    if length(t)>1; timestep=t(2); end
  elseif ischar(t) & strcmp(upper(t),'NODATE')
    nodate=1;
  elseif ischar(t) & strcmp(upper(t),'RCM5')
    nodate=1;
  elseif ischar(t) & strcmp(upper(t),'RCM7')
    nodate=0;
  elseif ischar(t) & strncmp(upper(t),'ID=',3)
    rcm_id=t(4:end);
  else
    warning('unknown variable argument')
  end
  ii=ii+1;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% start in reading, first read in matlab file if present
[PATH,NAME,EXT,VER] = fileparts(Datei);
if nomat==0
  if exist(fullfile(PATH,[NAME '.mat']))==2
    load(fullfile(PATH,[NAME '.mat']))
    return
  end
end

if ~isempty(strfind(upper(EXT),'DSU'))
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%%%%%%%%%%%%%%%%%% reading binary DSU format
  %% up till now reads only data and time, but there seems to be some more
  %% information. Done by reverse engeniering (that is I looked at the data
  %% files and came up with a way to read it).
  % read in all data from file
  fid=fopen(Datei,'r');
  T=fread(fid,inf,'uint8');
  fclose(fid);
  % find beginning of records
  ii=find(T==64); ii=[ii;numel(T)]; jump=0;
  % search if we have 6 or 15 Variables
  jvar=6;
  for jj=1:length(ii)-1
    if T(ii(jj)-1)==226 & ( T(ii(jj)+1)==15 | T(ii(jj)+1)==17)
      jvar=15;
      break
    end
  end
  % reserve data space
  DD=zeros(length(ii)-1,jvar)+NaN;
  IVAR=0;
  % process the data
  for jj=1:length(ii)-1
    if T(ii(jj)-1)~=226;
      if jump>0; jump=jump-1; continue; end
      fprintf('anfang ~=226 \n');
    end
    if T(ii(jj)+1) ==5      % 36 bytes
      if ii(jj+1)-ii(jj)~=36
        if ii(jj+1)-ii(jj)<36
          for jump=1:length(ii)
            if ii(jj+1+jump)-ii(jj)==36; break; end
            if ii(jj+1+jump)-ii(jj)>36; jump=0; break; end
          end
          if jump==0
            fprintf('NR 5:');
            fprintf('%3i ',T(ii(jj):ii(jj+1)));
            fprintf('\n');
            continue
          end
        end
      end
      IVAR=IVAR+1;
      for kk=1:6
        DD(IVAR,kk)=T(ii(jj)+kk*4+1)+T(ii(jj)+kk*4+2)*256;
      end
    elseif T(ii(jj)+1) ==6      % 40 bytes
      if ii(jj+1)-ii(jj)~=40
        if ii(jj+1)-ii(jj)<40
          for jump=1:length(ii)
            if ii(jj+1+jump)-ii(jj)==40; break; end
            if ii(jj+1+jump)-ii(jj)>40; jump=0; break; end
          end
          if jump==0
            fprintf('NR 6:');
            fprintf('%3i ',T(ii(jj):ii(jj+1)));
            fprintf('\n');
            continue
          end
        end
      end
      IVAR=IVAR+1;
      for kk=1:6
        DD(IVAR,kk)=T(ii(jj)+kk*4+1)+T(ii(jj)+kk*4+2)*256;
      end
    elseif T(ii(jj)+1) ==15 | T(ii(jj)+1) ==17       % 76 bytes, dcm
      if ii(jj+1)-ii(jj)~=76
        if ii(jj+1)-ii(jj)<76
          for jump=1:length(ii)
            if ii(jj+1+jump)-ii(jj)==76; break; end
            if ii(jj+1+jump)-ii(jj)>76; jump=0; break; end
          end
          if jump==0
            fprintf('NR1x:');
            fprintf('%3i ',T(ii(jj):ii(jj+1)));
            fprintf('\n');
            continue
          end
        end
      end
      IVAR=IVAR+1;
      for kk=1:15
        DD(IVAR,kk)=T(ii(jj)+kk*4+1)+T(ii(jj)+kk*4+2)*256;
      end
    end
  end
  % delete not used records
  DD=DD(1:IVAR,:);
  [idata jdata]=size(DD);
else
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%%%%%%%%%%%%%%%%%% now the ascii part
  %% try to read in the full file, if it does not work, read in line by line
  h=' ';
  %%M6
  %%dd=load([disk char(D(i).name)]);
  %%M5
  jFehler=0;
  [PATH,NAME,EXT,VER] = fileparts(Datei);
  eval('DD=load(Datei);','jFehler=1;');
  if jFehler==0;
    %eval(['dd=X' NAME ';']);
    [idata jdata]=size(DD);
  else
    DD=[];
    fid=fopen(Datei);
    l=' '; idata=0; jdata=0;
    if fid<=0; l=1; end
    while ischar(l);
      l=fgetl(fid); jfehler=0;
      eval('d1=str2num(l);','jfehler=1;');
      if jfehler==0
        idata=idata+1;
        if jdata<length(d1)
          for ii=1:length(d1)
            DD(idata,ii)=d1(ii);
          end
          jdata=length(d1);
        else
          DD(idata,1:length(d1))=d1;
        end
      end
    end
    if fid>0; fclose(fid); end
    fprintf(['datei ' Datei 'war nicht matlab lesbar\n']);
  end

end

%% search for time stamps and append time, then delete time stamps
jtime=0;
if nodate==1;
  aa=DD;
else
  kk=~(DD(:,1)==7);
  if jdata>=6 & sum(~kk)>1
    DD=[DD zeros(idata,1)+NaN];
    jtime=jdata+1;
    for ii=1:idata-1
      if DD(ii,1)==7;
        jahr=DD(ii,2)+1900; if jahr<1970; jahr=jahr+100; end
        datum=julianday(DD(ii,4),DD(ii,3),jahr)+(DD(ii,5)+DD(ii,6)/60)/24;
        DD(ii+1,jdata+1)=datum;
      end
    end
  else
    fprintf('no time decoding posible')
  end
  aa=DD(kk,:);
  idata=sum(kk);
end

%% try to decode RCM serial number
if ~isempty(DD)
  if isempty(rcm_id); rcm_id=iles(NAME); end
  if isempty(rcm_id); error('no rcm_id found'); end
else
  return
end

if Xtemp==0
  switch rcm_id
    case { 9870 , 5328 , 6052, 12301, 204, 209, 9841 }
      aaTEMP='l';
    otherwise
      %  9879, 11295, 11297, 12321, 81
      % 12322, 12334,  9841,  9875, 9876, 9878
      %  8414,  8415,  8416,  9840
      aaTEMP='a';
  end
elseif Xtemp==1
  aaTEMP='a';
elseif Xtemp==2
  aaTEMP='l'
elseif Xtemp==3
  aaTEMP='w'
elseif Xtemp==4
  aaTEMP='h'
elseif Xtemp==-1
  aaTEMP='DCM';
end


[RCM_CAL,N]=aandread(rcm_id,aaTEMP);
if strcmp(N(1),'Chn-1')==1
  fprintf('Keine Koeffizienten fr RCM %i gefunden, nehme Standardwerte\n',rcm_id)
  [RCM_CAL,N]=aandread(0,aaTEMP);
end

if aaTEMP=='a' & strncmp(N(4),'Pressure',4)
  %RCM_CAL(4,:)=RCM_CAL(1,:);
  N(4)={'Temp.ArcX'};
  fprintf('Keine Arctic Temperature Koeffizienten gefunden, nehme Standardwerte\n')
  RCM_CAL(4,:)=[-2.635 8.154E-3 -1.601E-7 7.991E-11];
  % falls arctic angegeben aber nicht gefunden, nehme
  % Standard koeffizenten aus RCM 7&8 operating manual, page 3-08
end

%keyboard
for kk=2:6
  a=RCM_CAL(kk,:); ll=length(aa(:,kk));
  aa(:,kk)=a(1)+a(2)*aa(:,kk)+a(3)*aa(:,kk).^2+a(4)*aa(:,kk).^3;
end

if jtime>0
  N(jtime)={'time'};
  ii=~isnan(aa(:,jtime));
  if sum(ii)>2
    xx1=find(ii);xxi=find(~ii);
    aa(~ii,jtime)=interp1(xx1,aa(ii,jtime),xxi,'linear','extrap');
  end
else
  jtime=jdata+1;
  N(jtime)={'time'};
  aa=[aa [0:idata-1]'*timestep+timestart];
end
IV(6)=jtime;

% IV Position of Pres,Temp,Cond,Dire,Velo
% falls Temperature zweifach (low+arctic, wird arctic genommen, da
% diese ja nach low in den Namen steht.

for kk=1:length(N)
  if strncmpi(N(kk),'Temp',4)
    IV(2)=kk;
  elseif strncmpi(N(kk),'Conduct',4)
    IV(3)=kk;
  elseif strncmpi(N(kk),'Pressure',4)
    IV(1)=kk;
  elseif strncmpi(N(kk),'Direction',4)
    IV(4)=kk;
  elseif strncmpi(N(kk),'Speed',4)
    IV(5)=kk;
  else
    continue;
  end
end

if nomat==0
  save(fullfile(PATH,[NAME '.mat']),'aa','h','N','IV')
end
