function indexFile2termCountMatrix(inFile,outFile,vocabFile,...
    rareWordsThresh,stopWordList)

V=file2lineCell(vocabFile);
h=zeros(length(V),1);
fidR=fopen(inFile,'r');
while 1
    tline = fgetl(fidR);
    if ~ischar(tline), break, end
    I=sscanf(tline,'%f')+1;
    h(I)=h(I)+1;
end
fclose('all');
% remove stopwords and rare-words
stopWords=file2wordCell(stopWordList);
badWordsInd=zeros(1,length(V));
for i=1:length(V),
    if sum(strcmp(strtrim(V{i}),stopWords))>0,
        badWordsInd(i)=1;
    end
end
I=find(h<rareWordsThresh);
badWordsInd(I)=1;
% write matrix to file
fidR=fopen(inFile, 'r');
fidW=fopen(outFile,'w');
numGoodWords=length(V)-sum(badWordsInd);
while 1
    tline = fgetl(fidR);
    if ~ischar(tline), break, end
    I=sscanf(tline,'%f')+1;
    if length(I)<2, continue;end
    I=hist(I,length(V));
    I(badWordsInd==1)=[];
    ind=find(I>0);
    st=[num2str(length(ind))];
    for i=1:length(ind)
        st=[st ' ' num2str(ind(i)) ':' num2str(I(ind(i)))];
    end
    fprintf(fidW,'%s\n',st);
end
V=V(find(badWordsInd==0));
save goodWordsVocab V;
fclose('all');