
function scan=readspec_hash(filename,scannum)
% filename='C:\Documents and Settings\mhupton.ANL.000\My Documents\beamline misc\BeamMotion\2010-1\comm';
% scannum=200;

%readspec(filename,scannum)
[fid,message]=fopen(filename,'r');

%find file size so can tell if hash table is complete
fseek(fid, 0, 'eof');
filesize = ftell(fid);
%Rewind to beginning of file
fseek(fid,0,'bof');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%% WRITE HASH TABLE/FILE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
hashfilename=strcat(filename,'_hash.mat');
hashexist=fopen(hashfilename);
if (hashexist~=-1)
%    fprintf('Hash table exists\n');    
    fclose(hashexist);
    load(hashfilename);
    if (hash(1,1)~=filesize)
        hashexist=-1;
        fprintf('Hash table made when file was a different size\n');
    end
end
if (hashexist==-1)    
    fprintf('Hash table does not exist, preparing hash table\n');

    %First line of the hash table is the filesize
    hash(1,1)=filesize;
    hash(1,2)=filesize;
    
    tline = fgetl(fid);
    
    scan=0;
    index=2;
    foundscan=0;
    compstr=strcat('#S ',num2str(scannum));
    %Put hash table into array before writing to file at the end of the while
    %loop.  Start on second line since the first line is the file size
    % Array is called hash
    index=2;
    nline=0;
    %Make hash table
    while ischar(tline)
        nline=nline+1;
        %disp(tline);
        tline = fgetl(fid);
        [token,remain]=strtok(tline);
        if strcmp(token,'#S'); %check if at the beginning of a scan
            number=str2num(strtok(remain));
            hash(index,1)=nline;
            hash(index,2)=number;
            hash(index,3)=ftell(fid);
            index=index+1;
        end
    end
    save(hashfilename,'hash');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%% Hash table has been created or loaded %%%%%%%%%%%%%%%%%% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%% Find correct scan %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

linenumindex=find(hash(:,2)==scannum);
linenum=hash(linenumindex,1);
position=hash(linenumindex,3);

if (~exist('linenumindex'))
    printf('Scan number does not exist\n');
end

%Go to correct positon in the file
fseek(fid,position,'bof');
index=1;
tline=fgetl(fid);
while tline~=-1
    [token,remain]=strtok(tline); 

    if ~isempty(str2num(token))~=0
        A=str2num(tline);
%        tline=fgetl(fid);

        if ~isempty(A)
            index;
            if index==1
                scan=A;
            else
                scan=[scan; A];
            end
            index=index+1;
        elseif isempty(A)
            break;
        end
    end
    tline = fgetl(fid);
    % isempty(tline)
end


fclose(fid);
