function [X,head]=openim()


global T INFO
X=[];
head=[];
%% open directory
PathName = uigetdir;
INFO.PathName  = PathName;
cd(PathName)
d=dir('*IHDR');
fnAll = {d.name};
if isempty(fnAll)==0
    INFO.prebehlo = 5;
[s,v] = listdlg('PromptString','Select all image-files:',...
                'SelectionMode','multiple',...
                'ListString',fnAll);
if v==0,
   return;
end
INFO.pomocna = s;
% [FileName,PathName] = uigetfile('*.ihdr','Select the image file')
if isempty(s)==0 
for ii = 1:length(s)
    FileName = d(s(ii)).name;
    if ~(isequal(FileName,0) || isequal(PathName,0))
%        T=[];
       [p,T(ii).FileName,T(ii).FileExt]=fileparts(FileName);
       T(ii).PathName=PathName;
       cd(T(ii).PathName);
       %[T.X,map]=imread(T.FileName);
       [X,head,st]=baselimr(T(ii).FileName,T(ii).PathName,'i');   % main procedure reading the Basel image format
       T(ii).IMAGE = X;
       T(ii).HEAD = head;
    %    save T.mat
    end
%     IMAGES(ii).T = T;
    % modelvstup3_B
end
else
    
end
else
    errordlg('V priecinku niesu obrazky formatu *IHDR')
    INFO.prebehlo = 0;
end
cd(INFO.Current);
function [X,head,st]=baselimr(imfilename,imdir,headim)
%BASELIMR - read picture from Basel
%
% Input parameters: 3 (OK) or 2 (headim='i')
% imfilename ... name of image file without extension
% imdir ... directory of image 
% headim ... 'i' - read both IMAGE and HEAD (default)
%            'h' - read only HEAD; X=[]
%            't' - tests if both IMAGE and HEAD exist; X=[]; head=[]
% X ... image
% head ... image head
% st ... status for reading:
%     = 1 if both IMAG and IHDR files exist			- OK
%     = 2 if IMAG file does not exist 					- O-O
%     = 3 if IHDR file does not exist					- O-O
%     = 4 if both IMAG and IHDR files do not exist	- O-O
% example: [X,head,st]=baselimr('STEM_10800_1','C:\BaselImages','i');

%  Vladislav Krzyzanek, 2003/11/17
%  Inst. for Med. Physics and Biophysics, University of Muenster
%  Revision: 2005/05/24 (VK)

if nargin<2,
   error('Must be 2 or 3 input parameters');
elseif nargin==2,
   headim='i';
end
readimage=0;
readhead=0;
if upper(headim)=='I',
   readimage=1;
   readhead=1;
elseif upper(headim)=='H',
   readimage=0;
   readhead=1;
elseif upper(headim)=='T',
   readimage=0;
   readhead=0;
else
   error('Parameter HEADIM have to be ''i'' or ''h''');
end

filename=fullfile(imdir,imfilename); %filename=upper(fullfile(imdir,imfilename));

filenamePicture=[filename,'.IMAG']; %filenamePicture=upper([filename,'.IMAG']);
filenameHeader =[filename,'.IHDR']; %filenameHeader =upper([filename,'.IHDR']);

st_IMAG = exist(filenamePicture,'file');
st_IHDR = exist(filenameHeader,'file');

if (st_IMAG==2) && (st_IHDR==2),		% OK
   st=1;
elseif (st_IMAG~=2) && (st_IHDR==2),	% no IMAG 
   st=2;
elseif (st_IMAG==2) && (st_IHDR~=2),	% no IHDR
   st=3;
elseif (st_IMAG~=2) && (st_IHDR~=2),	% no both IMAG and IHDR
   st=4;
else											% ???
   st=5;
   error('IMPSYS error')
end

if st==1,
   if readhead,
      %%%
      HEAD=[];
      HEAD.ORIG      =[];     % ORIGINAL HEAD ... ARRAY OF CHAR
      HEAD.FILENAME  ='';     % FILENAME OF HEAD - STRING (e.g. 'STEM_10800_1.IHDR')
      HEAD.IFILENAME ='';     % FILENAME OF IMAGE - STRING (e.g. 'STEM_10800_1.IMAG')
      HEAD.SIZE      =[0 0];  % SIZE OF IMAGE (ROW,COLUMN)
      HEAD.EXTREMS   =[0 0];  % EXTREMS OF ORIG. IMAGE (MIN,MAX)
      HEAD.PIXELTIM  =NaN;    % SCANNING TIME PER 1 PIXEL IN [sec.]
      HEAD.PIXELSIZE =[0 0];  % SIZE OF PIXEL IN [nm] (ROW,COLUMN)
      HEAD.CURRENT   =NaN;    % Current measured on the objective aperture [A]
      HEAD.COUNT_EF  =NaN;    % Counting efficiency of the ADF detector
      HEAD.DOSE      =NaN;    % Dose [el./(nm^2)]
      HEAD.FOC_VOLT  =NaN;    % Focusing voltage [V]
      HEAD.OPERATOR  ='';     % NAME OF OPERATOR - STRING
      HEAD.CREATED   =[];     % DATE AND TIME (real number or string) ... (1,1)
      HEAD.MICROSCO  ='';     % MICROSCOPE - STRING
      HEAD.SPEC_PRE  ='';     % SPECIFICATION OF PREPARAT - STRING
      HEAD.IMAGENR   ='';     % ??? - STRING
      HEAD.TYPE      ='';     % ??? - STRING
      HEAD.MEAN      =0;      % MEAN VALUE OF THE IMAGE
      HEAD.ST_DEV    =0;      % STANDARD DEVIATION OF THE IMAGE
      HEAD.DIVISION  =1;      % ??? - NUMBER (1,1)
      HEAD.E0        =NaN;    % ??? - NUMBER (1,1)
      HEAD.TEMPERAT  =NaN;    % ??? - NUMBER (1,1)
      %%%
      [fid,message] = fopen(filenameHeader,'r');
      [head1,hcount]=fread(fid,'char'); %hcount-number of elements in head1
      fclose(fid);
      numR=fix(hcount/32);
      pom=zeros(numR,32);
      pom=char(pom);
    
      p=find(head1==13);
      if isempty(p),
         p=find(head1==10);
      end
      p1=findstr(char(head1'),char([13,10]));
      if ~isempty(p),
         if length(p1)<length(p),
            for ii=1:length(p),
               head1(p(ii))=' ';
            end
         else
            for ii=length(p):-1:1,
               head1(p(ii))=[];
               head1(p(ii))=' ';
            end
         end
      end
      
      for ii=1:numR,
         for jj=1:32,
            pom(ii,jj)=head1((ii-1)*32+jj);
         end
      end
      % tu su uz nacitane vsetky info v promennej pom
      clear p2
      for ii=1:numR,
         switch upper(pom(ii,1:9)),
         case 'NUM_X_PI:',	
            p3=ReadHeadValue(pom(ii,:),0,[]);
            if ~isempty(p3),
               p4=str2double(p3);
               if ~isnan(p4),
                  HEAD.SIZE(2)=p4;
               else
                  error('Number of pixels of the image is not in Basel image head!');
               end
            else
               error('Number of pixels of the image is not in Basel image head!');
            end
         case 'NUM_Y_PI:',	
            p3=ReadHeadValue(pom(ii,:),0,[]);
            if ~isempty(p3),
               p4=str2double(p3);
               if ~isnan(p4),
                  HEAD.SIZE(1)=p4;
               else
                  error('Number of pixels of the image is not in Basel image head!');
               end
            else
               error('Number of pixels of the image is not in Basel image head!');
            end
         case 'OPERATOR:',
            HEAD.OPERATOR=ReadHeadValue(pom(ii,:),0,HEAD.OPERATOR);
         case 'DATE_TIM:',
            HEAD.CREATED=ReadHeadValue(pom(ii,:),0,HEAD.CREATED);
%             HEAD.CREATED=str2date(pom(ii,(10:(size(pom,2)-2))),1); CHYBA
         case 'SPEC_PRE:',
            HEAD.SPEC_PRE=ReadHeadValue(pom(ii,:),0,HEAD.SPEC_PRE);
         case 'RAW_PROC:',
%            HEAD.RAW_PROC=ReadHeadValue(pom(ii,:),0,HEAD.RAW_PROC);
         case 'PIXELTIM:',
				p3=ReadPIXELTIM(pom(ii,:));
				HEAD.PIXELTIM=p3;
         case 'SIZE_X  :',
            p3=ReadHeadValue(pom(ii,:),0,[]);
            if ~isempty(p3),
               p4=findstr(upper(p3),'NM');
               if ~isempty(p4),
                  p5=str2double(p3(1:(p4-1)));
                  if ~isnan(p5),
                     HEAD.PIXELSIZE(2)=p5;
                  end 
               end
            end 
         case 'SIZE_Y  :',
            p3=ReadHeadValue(pom(ii,:),0,[]);
            if ~isempty(p3),
               p4=findstr(upper(p3),'NM');
               if ~isempty(p4),
                  p5=str2double(p3(1:(p4-1)));
                  if ~isnan(p5),
                     HEAD.PIXELSIZE(1)=p5;
                  end 
               end
            end 
         case 'FORMAT  :',
%            HEAD.FORMAT=ReadHeadValue(pom(ii,:),0,HEAD.FORMAT);
         case 'TYPE    :',
            HEAD.TYPE=ReadHeadValue(pom(ii,:),0,HEAD.TYPE);
         case 'MIN     :',
            HEAD.EXTREMS(1)=ReadHeadValue(pom(ii,:),1,HEAD.EXTREMS(1));
         case 'MAX     :',
            HEAD.EXTREMS(2)=ReadHeadValue(pom(ii,:),1,HEAD.EXTREMS(2));
         case 'MEAN    :',
            HEAD.MEAN=ReadHeadValue(pom(ii,:),1,HEAD.MEAN);
         case 'ST_DEV  :',
            HEAD.ST_DEV=ReadHeadValue(pom(ii,:),1,HEAD.ST_DEV);
         case 'IMAGE_SP:',
%            HEAD.IMAGE_SP=ReadHeadValue(pom(ii,:),0,HEAD.IMAGE_SP);
         case 'LIN_LOG :',
%            HEAD.LIN_LOG=ReadHeadValue(pom(ii,:),0,HEAD.LIN_LOG);		% maybe change 0 or 1
         case 'DIVISION:',
            HEAD.DIVISION=ReadHeadValue(pom(ii,:),1,HEAD.DIVISION);
         case 'CURRENT :',
            HEAD.CURRENT=ReadHeadValue(pom(ii,:),1,HEAD.CURRENT);
         case 'COUNT_EF:',
            HEAD.COUNT_EF=ReadHeadValue(pom(ii,:),1,HEAD.COUNT_EF);
         case 'DOSE    :',
            HEAD.DOSE=ReadHeadValue(pom(ii,:),1,HEAD.DOSE);
         case 'E0      :',
            HEAD.E0=ReadHeadValue(pom(ii,:),1,HEAD.E0);
         case 'HIG_VOLT:',
            p1=strfind(upper(pom(ii,:)), 'KV');
            if numel(p1)==1,
               p1=str2double(pom(ii,10:(p1-1)));
               if ~isnan(p1);
                  HEAD.E0=p1;
               end
            end
         case 'TEMPERAT:',
            HEAD.TEMPERAT=ReadHeadValue(pom(ii,:),1,HEAD.TEMPERAT);
         case 'PRESSURE:',
%            HEAD.PRESSURE=ReadHeadValue(pom(ii,:),1,HEAD.PRESSURE);
         case 'ENERGY_R:',
%            HEAD.ENERGY_R=ReadHeadValue(pom(ii,:),1,HEAD.ENERGY_R);
         case 'FOC_VOLT:',
            HEAD.FOC_VOLT=ReadHeadValue(pom(ii,:),1,HEAD.FOC_VOLT);
         case 'IMAGENR :',
            HEAD.IMAGENR=ReadHeadValue(pom(ii,:),0,HEAD.IMAGENR);
         case 'FILENAME:',
            HEAD.FILENAME=ReadHeadValue(pom(ii,:),0,HEAD.FILENAME);
         case 'MICROSCO:',
            HEAD.MICROSCO=ReadHeadValue(pom(ii,:),0,HEAD.MICROSCO);
         end
      end
      
      HEAD.PIXELSIZE(1)=HEAD.PIXELSIZE(1)/HEAD.SIZE(1);
      HEAD.PIXELSIZE(2)=HEAD.PIXELSIZE(2)/HEAD.SIZE(2);
      HEAD.FILENAME	=[imfilename,'.IHDR'];
      HEAD.IFILENAME =[imfilename,'.IMAG'];
      HEAD.EXTREMS=HEAD.EXTREMS*HEAD.DIVISION;
      HEAD.MEAN   =HEAD.MEAN*HEAD.DIVISION;
      HEAD.ST_DEV =HEAD.ST_DEV*HEAD.DIVISION;
      HEAD.ORIG=pom;
      head=HEAD;
   else
      head=[];
   end
%     T.Head = HEAD;
   
   if (readimage) && (~isempty(head)),
      %%%
      IMAGE=[];
      IMAGE.ORIG     =[];     % ORIGINAL IMAGE
      IMAGE.DISP     =[];     % IMAGE FOR DISPLY
      IMAGE.FILENAME ='';     % FILENAME OF IMAGE - STRING (e.g. 'STEM_10800_1')
      IMAGE.FILETYPE ='';     % Type of image file:
                              %           'Basel-IMAG'    - image from Basel
                              %           'Muenster-TIFF' - image from Muenster
      IMAGE.FILEEXT  ='';     % Extension of image file (e.g. 'IMAG')
      IMAGE.SIZE     =[0 0];  % SIZE OF IMAGE (ROW,COLUMN)
      IMAGE.OEXT     =[0 0 0 0];  % STATISTICS OF ORIG. IMAGE (MIN,MAX,MEAN,STDEV) ... original
      IMAGE.DEXT     =[0 0 0 0];  % STATISTICS OF DISP. IMAGE (MIN,MAX,MEAN,STDEV) ... displayed (<0,1>)
%       IMAGE.OFOS     =[0 0 0 0];  % STATISTICS OF ORIG. IMAGE (MIN,MAX,MEAN,STDEV) ... original after filtering
%       IMAGE.DFOS     =[0 0 0 0];  % STATISTICS OF DISP. IMAGE (MIN,MAX,MEAN,STDEV) ... displayed after filtering
      %%%
      X=IMAGE;
      fid = fopen(filenamePicture,'r');
      [A,count] = fread(fid,'uint8');
      fclose(fid);
      if (head.SIZE(1)*head.SIZE(2))~=count,
         error('Image data and information about image size in the header are not the same');
      end
      sizeR=head.SIZE(1);
      sizeS=head.SIZE(2);
      X.ORIG=zeros(sizeR,sizeS);
      for ii=0:(sizeR-1),
         X.ORIG(ii+1,:)=A((ii*sizeS+1):((ii+1)*sizeS))';
      end
      X.ORIG=X.ORIG*head.DIVISION;
      X.FILENAME	=imfilename;
      X.FILEEXT  	='IMAG';
      X.FILETYPE 	='Basel-IMAG';
      X.SIZE		=size(X.ORIG);
      X.DISP		=mat2gray(X.ORIG);
      X.OEXT		=[min(min(X.ORIG)) max(max(X.ORIG)) mean2(X.ORIG) std2(X.ORIG)];
      X.DEXT		=[min(min(X.DISP)) max(max(X.DISP)) mean2(X.DISP) std2(X.DISP)];
      X.OFOS      =X.OEXT;
      X.DFOS      =X.DEXT;
   else
      X=[];
   end
else
   X=[];
   head=[];

end



% T.Image = IMAGE;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function a=ReadHeadValue(b,vtype,defaultVal)
% vtype=1 for number
%       0 for string

p=find(b==';');
if isempty(p),
   error('Error in header file from Basel picture - each row has to end by ";"');
elseif length(p)>1,
   error('Error in header file from Basel picture - each row has to contain only one ";" (at the end of row)');
else
   if p>10,
      pom=b(10:(p-1));
      if vtype==1,    	% number
         pom1=str2num(pom);
         if isempty(pom1),
            a=defaultVal;
         else
            a=pom1;
         end
      elseif vtype==0, 	% string
         a=pom;
      else
         error('Error in source code');
      end
   else
      a=defaultVal;
   end 
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function p=ReadPIXELTIM(b)

p=find(b==';');
if isempty(p),
   error('Error in header file from Basel picture - each row has to end by ";"');
elseif length(p)>1,
   error('Error in header file from Basel picture - each row has to contain only one ";" (at the end of row)');
else
   if p>10,
      pom=b(10:(p-1));
      pom=upper(strtrim(pom));
      p1=length(pom);
      if (p1>8) || (p1<6),
         error('Error in header file in PIXELTIME');
      else
         if p1==6,
            pom=[pom,'  '];
         elseif p1==7,
            pom=[pom,' '];
         end
         switch pom,
            case '2 USEC  ',   
               TPIXEL=0.000002;
            case '4 USEC  ',   
               TPIXEL=0.000004;
            case '8 USEC  ',   
               TPIXEL=0.000008;
            case '16 USEC ',  
               TPIXEL=0.000016;
            case '32 USEC ',  
               TPIXEL=0.000032;
            case '64 USEC ',  
               TPIXEL=0.000064;
            case '128 USEC', 
               TPIXEL=0.000128;
            case '256 USEC', 
               TPIXEL=0.000256;
            case '1 MSEC  ',   
               TPIXEL=0.001;
            case '2 MSEC  ',   
               TPIXEL=0.002;
            case '4 MSEC  ',   
               TPIXEL=0.004;
            case '8 MSEC  ',   
               TPIXEL=0.008;
            case '16 MSEC ',  
               TPIXEL=0.016;
            case '32 MSEC ',
               TPIXEL=0.032;
            case '64 MSEC ',
               TPIXEL=0.064;
            otherwise
               error('Error in header file in PIXELTIME');
         end 
      end 
   else
      error('Error in header file in PIXELTIME');
   end 
end
p=TPIXEL;


function d=str2date(X,typ)
%STR2DATE - converts string with date and time to real number or vice versa
%
% typ = 1 ... string ==> number
%       0 ... number ==> string

%  Vladislav Krzyzanek, 2003/11/17
%  Inst. for Med. Physics and Biophysics, University of Muenster
%  Revision: 2008/07/09 (VK)

if typ, % 1 ... string (Basel format!!!) ==> number
   st=0;
   d=strtrim(X);
   X_orig=X;
   if ~isempty(X),
      p=findstr(X,':');
      if length(p)==3,
         p1=X((p(3)+1):end);
         if length(p1)==2,
            p2=str2double(p1);
            if (p2>=0) && (p2<60),
               p1=sprintf('%0.3f',p2/60);
               X(length(X)+1)=' ';
               X(p(3):end)=p1(2:end);
               d = datenum(X, 'mm/dd/yyyy HH:MM:SS.FFF');
               st=1;
               %disp(' ')
               %disp(X_orig)
               %disp(datestr(d,'mm/dd/yyyy HH:MM:SS.FFF'))
            else
               vbeep;
               disp(' ')
               disp(['Hundredth of seconds in Date_Tim = ',num2str(p2)])
            end 
         end 
      end 
   end
   if st==0,
      d=nan;
   end
   
else    % 0 ... number ==> string
   if isempty(X),
      d=[];
   elseif ischar(X),
      d=X;
   elseif X==0,
      d=[];
   else 
      d = datestr(X,'dd-mmm-yyyy HH:MM:SS.FFF');
      d(end)='';
      d(end)='';
   end
end

