clear 

get_expocodes='n';

if get_expocodes=='y',

% this part extracts the EXPOCODEs from the adjustment csv file and stores them in a .mat file
 fclose('all'); fx1='../PACIFICAadjustment.csv'; fopen(fx1); n0=fread(3);
 n=length(n0); o0=[n0(2:n);0]; p0=[n0(3:n);0;0];

% strip off headers
 ip=find(n0==40&o0==43&p0==41); ip=max(ip);      % looking for '(+)'
 iend=find(n0==10);    % find line ends
 iend=iend(min(find(iend>ip)));     % this should give the end of the first line after the headers
 n0(1:iend)=[];
 clear ip iend o0 p0 n

 iend=find(n0==10);    % find line ends
 n=length(iend);      % number of lines = number of xpos
 expocodes=cell(n,1);
 axpocodes=cell(n,1);

 linetext=n0(1:(iend(1)-1));
 ic=find(linetext==44);      % find all commas
 xpo=sprintf('%c',linetext((ic(1)+1):(ic(2)-1)));       % EXPOCODE should be the text between the first and second commas
 expocodes(1)={xpo};
 xpp=sprintf('%c',linetext((ic(2)+1):(ic(3)-1)));       % alt EXPOCODE used by excread.m
 axpocodes(1)={xpp};
 for i=2:n,
  linetext=n0((iend(i-1)+1):(iend(i)-1));
  ic=find(linetext==44); 
  xpo=sprintf('%c',linetext((ic(1)+1):(ic(2)-1))); 
  expocodes(i)={xpo};
  xpp=sprintf('%c',linetext((ic(2)+1):(ic(3)-1)));
  axpocodes(i)={xpp};
 end

 clear n0 xpo xpp i ic iend linetext ans

 save EXPO

else

 load EXPO expocodes axpocodes

 cd output
 load 1-BIGARRAY
 n=length(DATAEXPOCODES);
 nadj=length(expocodes);
 amatch=zeros(n,1);
 for i=1:n,
  current=DATAEXPOCODES(i);
  for ix=1:nadj, 
   if strcmp(current,expocodes(ix))==1 | strcmp(current,axpocodes(ix))==1, amatch(i)=ix; end 
  end
 end
 cd ..

% this tests whether the matching worked (bxx should be empty)
% i=find(amatch>0); axx=[DATAEXPOCODES(i) expocodes(amatch(i))];
% i=find(amatch==0); bxx=DATAEXPOCODES(i);

 adjmat=csvread('../PACIFICAadjustment.csv',3,4);
% #ID,EXPOCODE,Original Cruise No.,Project,SALNTY(+),OXYGEN(x),NITRAT(x),SILCAT(x),PHSPHT(x),TCARBN(+),ALKALI(+)
 indx=[12 30 32 14 18 16 20];      % indices for these 7 fields (as ordered in adjustment.csv file but with additive/multiplicative fields grouped) in data matrix
% DATAVARIABLES(indx)       % just for testing

adjmat=adjmat(:,[1 6 7 2 3 4 5]);     % reorder columns to group additive/multiplicative fields

 DATA0=DATA;
 crn=DATA(:,1);
 for i=1:n,
  ic=find(crn==i);
  for j=1:3,   % additive for S, DIC, TA otherwise multiplicative
   adj=adjmat(amatch(i),j);
   if adj<500,  % I put codes 999, 888, 777 etc to replace some nonnumeric stuff that csvread can not handle
    DATA(ic,indx(j))=DATA(ic,indx(j))+adj; 
   end
  end 
  for j=4:7,
   adj=adjmat(amatch(i),j);
   if adj<500,
    DATA(ic,indx(j))=DATA(ic,indx(j))*adj; 
   end
  end 
 end 

 clear i j ic ix crn current adj expocodes axpocodes get_expocodes
 save adjusted_data

end    % if get_expocodes

