function gridfree = gridremover( im )

% im = double(im);
gridfree = nan( size( im ) );
% rl = size(im,2);

for rowidx = 1 : size( im, 1),
    
    row = double(im( rowidx, : ));
    
    dark = find( row == 0 );
    s = diff( dark );    
    
    s(s>1)=nan;
    
    if sum(isnan(s)) >0,
        ns = nansnip( s);
    else
        if sum(s) == 0,
            gridfree( rowidx, : ) = 1;
            continue % continuous horizontal line skip looking for thickest line
        else
            gridfree( rowidx, dark) = 0;
            continue;
        end
    end
    
    maxsize = 0;
    lineidx = 1;
    for idx = 1 : length(ns)              
        if length( ns{idx} ) > maxsize, 
            maxsize = length( ns{idx} );
            if lineidx >0 ,
                thickestlineidx = lineidx ;
            else
                thickestlineidx = 1;
            end
        end
        if ~ isempty( ns{idx} ),
            lineidx = lineidx + length( ns{idx} ) + 1; %+1 for nans
        end
    end
    
    gridfree( rowidx, : ) = 1;
    if maxsize < 0.1 * size(im,2), % otherwise it is a horizontal grid line
        gridfree( rowidx, dark(thickestlineidx+1 : thickestlineidx+maxsize) ) = 0;
    end
        
end