
function [data, st_name, colat_lon, orient] = getBinaryIntermagnet(name)
    
    %data - data array, (days number) x 4
    %st_name - station code
    %colat_lon - colatitude, longitude
    %orient - sensor orientation

    %name - full path and filename of .bin file    
    
    fid = fopen(name, 'rb');
    fseek(fid, 0, 'eof');
    lenf = ftell(fid);
    kolday = lenf/5888/4;
    data = zeros(1440*kolday, 4);
    
    fseek(fid, 0, 'bof');
    st_name = fread(fid, 4, '*char');
    st_name = st_name (2:4);
    st_name = st_name';
    fseek(fid, 8, 'bof');
    colat_lon = fread(fid, 2, 'int32');
    colat_lon(1) = colat_lon(1) / 1000;
    colat_lon(2) = colat_lon(2) / 1000;
    
    fseek(fid, 4, 'cof');
    orient = fread(fid, 4, '*char');
    orient = orient';
    
    fseek(fid, 0, 'bof');
    i1 = 1;
    i2 = 1440;
    for i = 1: kolday        
        fseek(fid, 16*4, 'cof');
        %for j = 1: col-1
        %    fseek(fid, 1440*4, 'cof');
        %end
        
        data (i1:i2, 1) = fread(fid, 1440, 'int32');
        data (i1:i2, 2) = fread(fid, 1440, 'int32');
        data (i1:i2, 3) = fread(fid, 1440, 'int32');
        data (i1:i2, 4) = fread(fid, 1440, 'int32');
        
        %for j = col+1: 4
        %    fseek(fid, 1440*4, 'cof');
        %end
        fseek(fid, 112*4, 'cof');
        i1 = i1 + 1440;
        i2 = i2 + 1440;
    end
    fclose(fid);
    
    for i = 1: size(data,1)
        for j = 1: size (data, 2)
            if (data(i,j) ~= 999999)
                data(i,j) = data(i,j) / 10;
            end
        end
    end
   
    %linear interpolation of 'miss_val' values 
    
    for j = 1: size (data, 2)
        
        [keg, beg] = get_potential(find(data(:,j) == 999999));
        for i = 1: keg
            i1 = beg(i, 1);
            i2 = beg(i, 2);
            if i1 == 1
                if (i2 ~= length(data(:,j)))
                    data(i1:i2,j) = data(i2+1,j);
                end
            elseif i2 == length(data(:,j))
                data(i1:i2,j) = data(i1-1,j);
            else
                i1 = i1-1;
                i2 = i2+1;
                data(i1:i2,j) = linspace(data(i1,j), data(i2,j), i2-i1+1);
            end
        end
    end
    %-------------------------------------------
end

function [keg, beg] = get_potential(indg)

    dl = length(indg);
    if dl<2
        keg = 0;
        beg = 0;
        return;
    end
    kk = find(indg(2:dl)-indg(1:dl-1)-1);
    yy1 = cat(1, indg(1), indg(kk+1));
    yy2 = cat(1, indg(kk), indg(dl));
    beg = cat(2, yy1, yy2);

    [keg rw] = size(beg);

end

    