function BestROC = BestTPOfROCFamily(caROC)
%function BestROC = BestTPOfROCFamily(caROC)
%
%returns a new ROC with for each fp ROC = max(caROC.tp)

BestROC.normfp = 0:.001:1;
StandardizedTPMat = StandardizeTP(caROC,BestROC.normfp);
BestROC.normtp = max(StandardizedTPMat,[],1);
fprintf('\n');

function tp = StandardizeTP(caROC,fp);
nCells = length(caROC);
nfp = length(fp);
tp = zeros(nCells, nfp);
j = 1;
seedrand;
for j = 1:nCells
  caROC{j} = reverse(caROC{j});
  tp(j,:) = stretchtp(caROC{j},fp);
end


function TP = stretchtp(RocStructure2,newfp)
if(length(RocStructure2.normfp) > 4000)
   p = randperm(length(   RocStructure2.normfp));
   p = sort(p(1:4000));
   RocStructure2.normfp = RocStructure2.normfp(p);
   RocStructure2.normtp = RocStructure2.normtp(p);
   RocStructure2.normfp(1) = 0;
   RocStructure2.normtp(1) = 0;
   RocStructure2.normfp(end) = 1;
   RocStructure2.normtp(end) = 1;

end
TP = zeros(size(newfp));
WarpIdx = zeros(size(newfp));
InterpBelowPart = zeros(size(newfp));

j = 1;
for i = 1:(length(newfp)-1);
  if(mod(i,1000) == 0)
    fprintf('.');
  end
  while(RocStructure2.normfp(j)< newfp(i))
     j = j+1;
   end
   WarpIdx(i) = j;
   if((newfp(i+1) - newfp(i)) == 0)
     InterpBelowPart(i) = 0;
     TP(i) = RocStructure2.normtp(WarpIdx(i));
   else
     InterpBelowPart(i) = (RocStructure2.normfp(j) - newfp(i)) ...
          / (newfp(i+1) - newfp(i));
     if(InterpBelowPart(i) > .99)
       TP(i) = RocStructure2.normtp(WarpIdx(i));
     else 
       TP(i) = InterpBelowPart(i) * RocStructure2.normtp(WarpIdx(i)) ...
          +  (1 - InterpBelowPart(i)) * RocStructure2.normtp(WarpIdx(i)+1);
     end
   end
end
TP(end) = 1;

function [RocStructure1] = reverse(RocStructure1)
if(RocStructure1.normfp(end) < RocStructure1.normfp(1))
  RocStructure1.normfp = RocStructure1.normfp(end:-1:1);
end
if(RocStructure1.normtp(end) < RocStructure1.normtp(1))
  RocStructure1.normtp = RocStructure1.normtp(end:-1:1);
end
