function [varargout]=misread(varargin)
% MISREAD for reading of files generated by MISS and preparation for use
%    with MATLAB / SDT
%
% syntax : out = misread('File_name',options,calcomp, ...
%                                       [read_indices],version,lverif)
%
%     File_name : you have to enter the name of the file with its
%          extension. Accepted values of the extension are
%          - 'in' for reading of file MISS.IN
%          - 'miss' for reading of files .miss
%          - 'chp' for reading of files .chp and .imp
%          - 'total' for reading of all files .chp, .imp, .miss and MISS.IN.
%          - binary files extension : all binary files (almost) can be read. 
%     options :  Accepted values are (multiple values are possible) :
%          - 'binary' 'size' reading of entire binary file (default) 
%                    or only size header.
%          - 'single' 'double' precision used for computation single or 
%                    double (default) binary.
%          - 'field' 'nonfield' reading of a binary file of field type
%                    (that is, a recording is of length header(1)*header(2)) 
%                    or non-field type (recording of length header(1)). 
%                    This is useful in case the name of the file has been 
%                    changed and does not contain the correct suffix.
%          - 'drawing' 'nodrawing' allows or not (default value) the 
%                    drawing of graphs and meshes.
%          - 'montecarlo nbmc' indicates that the file read comes from
%                    a stochastic computation in MISS and the number of
%                    monte-carlo trials computed. nbmc is an integer.
%     calcomp : optional argument to specify the computer on which was
%          executed the program. Accepted values are 'mac' 'unix' 'linux'
%          and 'win'.
%          By default the reading and the computation are supposed to be
%          performed on the same platform (you do not have to specify 
%          this for reading of non-binary files).
%     [read_indices] : optional argument for specifying partial reading 
%          of binary files. The syntax is [i1 n1 i2 n2 i3 n3 i4 n4 i5 n5],
%          where 'i' stands for the first item to be read and 'n' 
%          for the number of elements to be read (indices 1 to 5 for each 
%          dimension of the matrix). if n=0 all the items are read. By 
%          default all elements are read. If you use argument 'montecarlo',
%          you have to specify 6 dimensions, last one being for monte-carlo
%          trials.
%     version : there are bugs on old versions of Pro_Miss3D (versions
%          prior to 6.4) that may alter the reading of the files. To fix
%          these bugs enter the name of the version used for the 
%          computation. Accepted values are 'missvar'.
%          By default the version used is supposed to be the latest one.
%     lverif : by default, missread makes several tests on the size of 
%          the file and on its contents to give warnings in case strange  
%          behaviour is encountered. You may prefer to avoid this by 
%          setting lverif = 0.
%          
%
% examples : out = misread('MISS.IN');
%            impdc = misread('civaux.01.IMPDC','double binary','mac',[],[],0);
%            impdc = misread('civaux.01.IMPDC','size');
%            [mean,dev] = misread('greziolles.MVFD','montecarlo 500','sgi');
%            mvfd = misread('essai.MVFD','single','sgi',[1 0 1 0 3 10 6 1 1 0]);
%
%	   See also MISWRITE
%	   Send any comment or bug report to cottereau@mssmat.ecp.fr

% author: Gerald KERGOURLAY with help of Auke Ditzel 19/06/2001
% modif Regis COTTEREAU 11/2003 - 12/2004
% modif Ralf Klein 12/2004

%============================================================================
%============================================================================
%    INPUT 
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
if nargin==0
	error('you have to enter at least one argument')
end

	%==============================================================
	%    INITIALISATIONS
	%--------------------------------------------------------------

lsize = 0;
lbinary = 0;
dim = 1;
ldrawing = 0;
lfield = 0;
lnonfield = 0;
lsingle = 0;
lmiss = 0;
lchp = 0;
lin = 0;
lcomplex = 1;
lmontecarlo = 0;
lvar = 0;

	%==============================================================
	%    FILE NAME
	%--------------------------------------------------------------

FileName=comstr(varargin{1},1);

if isempty(find(FileName=='.'))
	texterror = cat(2,'input name (',FileName, ...
	    ') does not have an extension and therefore cannot be treated by missread');
	error(texterror)
end

[CAM,ext]=comstr(FileName,max(find(FileName=='.'))+1);
	
if comstr(ext,'in')
	lin = 1;
elseif comstr(ext,'miss')
	lmiss = 1;
elseif comstr(ext,'chp')
	lchp = 1;
elseif comstr(ext,'total')
	lin = 1;
	lchp = 1;
	lmiss = 1;
else
	if(nargin==1)|isempty(varargin{2})
		lbinary = 1;
		indices = [1 0 1 0 1 0 1 0 1 0];
		first_read = [1 1 1 1 1];
		number_read = [0 0 0 0 0];
		ldiffcomp=0;
		lvar = 0;
		lverif = 1;
	end
end
	
	%==============================================================
	%    OPTIONS
	%--------------------------------------------------------------
	
if (nargin>1)&(~isempty(varargin{2}))

	options = varargin{2};
	
	while ~isempty(options)
	
		[keyword,options] = nextword(options);
		if comstr(keyword,'binary')
			lbinary = 1;
		elseif comstr(keyword,'size')
			lsize = 1;
		elseif comstr(keyword,'single')
			lsingle = 1;
		elseif comstr(keyword,'double')
			lsingle = 0;
		elseif comstr(keyword,'field')
			lfield = 1;
		elseif comstr(keyword,'nonfield')
			lnonfield = 1;
		elseif comstr(keyword,'drawing')
			ldrawing = 1;
		elseif comstr(keyword,'nodrawing')
			ldrawing = 0;
		elseif comstr(keyword,'montecarlo')
			[keyword,options] = nextword(options);
			nbmc = str2num(keyword);
			lmontecarlo = 1;
		else
	
	%==============================================================
	%    OLD SYNTAX
	%--------------------------------------------------------------
	
			[CAM1,Cam1] = comstr(keyword,1);
			[CAM2,Cam2] = comstr(keyword,2);
			[CAM5,Cam5] = comstr(keyword,5);

			if comstr(Cam1,'s')
				lsingle = 1;
			elseif comstr(Cam1,'d')
				lsingle = 0;
			else
				texterror = cat(2,'unknown option : ',Cam1);
				error(texterror)
			end
			
			if comstr(Cam2,'bin')
				lbinary = 1;
			elseif comstr(Cam2,'fld')
				lfield = 1;
			elseif comstr(Cam2,'nof')
				lnonfield = 1;
			elseif comstr(Cam2,'size')
				lsize = 1;
			else
				texterror = cat(2,'unknown option : ',Cam2);
				error(texterror)
			end
			
			if~isempty(Cam5)
				if comstr(Cam5,'3')
					dim = 3;
				elseif comstr(Cam5,'6')
					dim = 6;
				elseif comstr(Cam5,'e')
				else
					texterror = cat(2,'unknown option : ',Cam5);
					error(texterror)
				end
			end
		
			disp('for more convenience options have been changed and the arguments you have entered are obsolete')

		end
	
	end

end
	
	%==============================================================
	%    COMPUTER TYPE
	%--------------------------------------------------------------
	
ldiffcomp = 0;
[platform,maxsiz,endian] = computer;

if (nargin>2)&(~isempty(varargin{3}))
	calculus_computer = comstr(varargin{3},1);
	if calculus_computer=='1'
		ldiffcomp = 1;
	elseif calculus_computer=='0'
		ldiffcomp = 0;
	elseif (comstr(calculus_computer,'mac')+comstr(calculus_computer,'unix'))* ...
			(1-comstr(endian,'B'))
		ldiffcomp = 1;
	elseif (comstr(calculus_computer,'linux')+comstr(calculus_computer,'win'))* ...
			(1-comstr(endian,'L'))
		ldiffcomp = 1;
	end
end
	
	%==============================================================
	%    PARTIAL READING
	%--------------------------------------------------------------
	
if (nargin>3)&(~isempty(varargin{4}))
	[first_read,number_read] = misread_load('partial_reading',varargin{4},lmontecarlo);
else
	first_read = [1 1 1 1 1 1];
	number_read = [0 0 0 0 0 0];
end
	
	%==============================================================
	%    OLD VERSIONS
	%--------------------------------------------------------------
    
if (nargin>4)&(~isempty(varargin{5}))
	version = varargin{5};
	if(comstr(version,'missvar'))
		lvar = 1;
	else
		error('incorrect version name : bug patches exist for version MISSVAR')
	end
end
	
	%==============================================================
	%    VERIFICATIONS
	%--------------------------------------------------------------
	
lverif = 1;
    
if (nargin>5)&(~isempty(varargin{6}))
	verif = varargin{6};
	if(verif==0)
		lverif = 0;
	else
		disp('argument lverif should be set to 0 if you want to avoid verifications. Otherwise verifications will be done.')
	end
end
	
	%==============================================================
	%    COHERENCE OF INQUIRY
	%--------------------------------------------------------------
	
if ( ~(lsize+lin+lchp+lmiss) | (lfield+lnonfield) )
	lbinary = 1;
end
if(lbinary)
	lsize = 1;
end
	
	%==============================================================
	%    TESTS FOR THE STOCHASTIC CASE
	%--------------------------------------------------------------

if lmontecarlo
	if isempty(nbmc) | (floor(nbmc)~=nbmc)
		texterror = cat(2,'incorrect number of montecarlo trials : ',nbmc, ...
			'. It must be an INTEGER entered right after keyword MONTECARLO');
		error(texterror)
	end
end	

%============================================================================
%============================================================================
%    READING OF FILE HEAD 
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
if (lsize)

	%==============================================================
	%    READ PRECISION
	%--------------------------------------------------------------

    if lsingle
        precision=32;
        bytesize=8;
    else
		precision=64;
		bytesize=8;
    end

    sprecision=sprintf('float%d',precision);

	%==============================================================
	%    COMPUTER TYPE (BIG/LITTLE ENDIAN)
	%--------------------------------------------------------------
	
    if (ldiffcomp==1)
        if comstr(platform,'GLNX86')
            if lsingle
                foreign='b';
            else
                foreign='s';
            end
			
        elseif comstr(platform,'SGI')|comstr(platform,'MAC')
            if lsingle
                foreign='l';
            else
                foreign='a';
            end
			
		elseif comstr(platform,'SGI64')|comstr(platform,'LNX86')
			error('format SGI64 and LNX86 are no longer supported and have to be changed to SGI and GLNX86 respectively')
		end
		
    else
        foreign = 'n';
    end

	%==============================================================
	%    OPENING FILE
	%--------------------------------------------------------------

    if exist(FileName,'file')==2
        [fid,mes]=fopen(FileName,'r',foreign);
        if ~isempty(mes)
            disp(mes)
        end
    else
		texterror = cat(2,'The file ',FileName,' does not exist');
        error(texterror)
    end

	%==============================================================
	%    FILE SIZE
	%--------------------------------------------------------------

    fseek(fid,0,1);
    filesize = ftell(fid);

	%==============================================================
	%    READING MATRIX DIMENSIONS
	%--------------------------------------------------------------

    fseek(fid,0,-1);
    sprecision=sprintf('int%d',precision);
    file_head=fread(fid,5,sprecision);
	file_head = [file_head ; 1];

	%==============================================================
	%    CLOSING FILE
	%--------------------------------------------------------------

	if ~lbinary
		fclose(fid);
		varargout{1}=file_head;
	end

end
%
%============================================================================
%============================================================================
%    READING OF BINARY FILES 
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
if (lbinary)


	%==============================================================
	%    FILE TYPE
	%--------------------------------------------------------------

	if comstr(ext,'coef')
		lcomplex = 0;
	end
	
    if ((comstr(ext,'ctot')+comstr(ext,'ttot')+comstr(ext,'utot')+...
           comstr(ext,'tdm')+comstr(ext,'ui')+comstr(ext,'tui')+...
           comstr(ext,'ug')+comstr(ext,'tg')+comstr(ext,'cui')+...
           comstr(ext,'d0')+comstr(ext,'scui')+comstr(ext,'sctot')+...
           comstr(ext,'sctr')+comstr(ext,'cttot')+comstr(ext,'cext')+...
           comstr(ext,'csol')+comstr(ext,'lm')+comstr(ext,'ctr')+...
		   lfield)) & ~lnonfield
		   
		lfield = 1;
		   
	elseif ((comstr(ext,'mvfd')+comstr(ext,'mass')+comstr(ext,'rigi')+ ...
           comstr(ext,'amor')+comstr(ext,'fs')+comstr(ext,'impdc')+ ...
           comstr(ext,'sort')+comstr(ext,'coef')+comstr(ext,'cpdev')+ ...
		   comstr(ext,'kdelta')+lnonfield)) & ~lfield
		
		lnonfield = 1;
	
	else
	
		texterror = cat(2,'unrecognized extension : ',ext);
		error(texterror)
		
	end

	%==============================================================
	%    DIMENSIONS
	%--------------------------------------------------------------

    if dim == 3
        file_head(1)=file_head(1)*3;
    elseif dim == 6
        file_head(1)=file_head(1)*6;
    end

	%==============================================================
	%    MINIMUM RECORDLENGTH AND PRECISION
	%--------------------------------------------------------------

	size_head = 16;
    sprecision = sprintf('float%d',precision);

	%==============================================================
	%    TYPE OF FILE
	%--------------------------------------------------------------

	if lfield
        shapelength  = file_head(3)*file_head(4)*file_head(5)*file_head(6);
        reclength = file_head(1)*file_head(2);
		recordlength=max((2-lcomplex)*size_head,reclength);
		ind_lec = [file_head(1);cumprod([recordlength;file_head(3:6)])];
	elseif lnonfield
        shapelength  = file_head(2)*file_head(3)*file_head(4)*file_head(5)*file_head(6);
        reclength = file_head(1);
		recordlength = max((2-lcomplex)*size_head,reclength);
		ind_lec = cumprod([recordlength;file_head(2:6)]);
	else
		error('unrecognized type of file')
	end

	%==============================================================
	%    VERIFICATIONS ON THE SIZE OF THE FILE
	%--------------------------------------------------------------

	if(lverif)
		
		filesizeverif1 = (filesize*bytesize/(recordlength*precision*(1+lcomplex))-1)/shapelength;
		
		if(filesizeverif1~=1)
	
		%    MATRIX INDEPENDENT OF FREQUENCY
		%==============================================================

			if((floor(filesizeverif1)==filesizeverif1) & comstr(ext,'fs'))
				texterror = cat(2,'WARNING : the size of the file ',FileName,' (filesize = ' ,num2str(filesize), ...
					') does not seem to correspond with the numbers in the header (',num2str(file_head'), ...
					'). It might be because the matrix you are reading does not depend on the frequency but MISS needs it for every frequency. if nfreq = ', ...
					num2str(filesizeverif1),' is the number of frequency for your problem do not consider this warning. Otherwise report this problem.');
				disp(texterror)
		
		%    NO EXPLANATION FOUND
		%==============================================================

			else
				texterror = cat(2,'the size of the file ',FileName,' (filesize = ' ,num2str(filesize), ...
					') does not seem to correspond with the numbers in the header (',num2str(file_head'), ...
					'). It might be a problem in the writing of the file during computation or a bug in the version of MISS. Please report this problem.');
				error(texterror)
			end
		end
	end

	%==============================================================
	%    NEW HEADERS FOR STOCHASTIC CASE
	%--------------------------------------------------------------

	if lmontecarlo
	
		%    POSITION OF MONTE-CARLO TRIALS LOOP
		%==============================================================

		[ind_mc,lstochastic]=misvar_type_file(ext);
	
		%    TESTS
		%==============================================================

		if((file_head(ind_mc)/nbmc-floor(file_head(ind_mc)/nbmc))~=0)
			texterror =cat(2,'the number of monte carlo trials entered (',num2str(nbmc), ...
				') does not correspond with the size header of the specified file (', ...
				num2str(file_head'),')');
			error(texterror)
		end
	
		%    NEW HEADER
		%==============================================================

		file_head(ind_mc) = file_head(ind_mc)/nbmc;
		file_head(6) = file_head(6)*nbmc;
	
		%    SAVING THE DESIRED FIRST_READ(IND_MC)
		%==============================================================

		first_read_nomc = first_read(ind_mc);

	end

	%==============================================================
	%    CHECKING FILE SIZE
	%--------------------------------------------------------------

    numbnull=find(number_read==0);
    number_read(numbnull)=file_head(numbnull)'-first_read(numbnull)+ones(size(numbnull));
	
	if(size(find(first_read'+number_read'-ones(6,1)>file_head))~=0)
        texterror = cat(2,'you asked for : ',num2str([first_read'+number_read'-ones(6,1) ; 1]'), ...
			' but the number of elements in the file are in each dimension : ', ...
		    num2str(file_head'),'. You cannot read more elements than there are.');
		error(texterror)
    end

	%==============================================================
	%    LOOP ON MONTE-CARLO TRIALS
	%--------------------------------------------------------------

	finalout = zeros(number_read);
	for imc=first_read(6):(first_read(6)+number_read(6)-1)

		if lmontecarlo
			first_read(ind_mc) = first_read_nomc+(imc-1)*file_head(ind_mc);
		end

	%==============================================================
	%    LECTURE OF FILE
	%--------------------------------------------------------------

		I1=[first_read(1):first_read(1)+number_read(1)-1];
		I2=[first_read(2):first_read(2)+number_read(2)-1];
		I3=[first_read(3):first_read(3)+number_read(3)-1];
		I4=[first_read(4):first_read(4)+number_read(4)-1];
		I5=[first_read(5):first_read(5)+number_read(5)-1];
		[i1 i2 i3 i4 i5]=ndgrid(I1,I2,I3,I4,I5);
		j1=reshape(i1,1,prod(size(i1)))-1;
		j2=reshape(i2,1,prod(size(i2)))-1;
		j3=reshape(i3,1,prod(size(i3)))-1;
		j4=reshape(i4,1,prod(size(i4)))-1;
		j5=reshape(i5,1,prod(size(i5)))-1;
		j=j1+ind_lec(1)*j2+ind_lec(2)*j3+ind_lec(3)*j4+ind_lec(4)*j5;

		out=[];
		k=[0 find(diff(j)-1) length(j)]+1;

		for packet = 1:length(k)-1;
			reading_position=recordlength+j(k(packet));
			fseek(fid,reading_position*precision/bytesize*(1+lcomplex),-1);
			size_packet=k(packet+1)-k(packet);
			u = fread(fid,(1+lcomplex)*size_packet,sprecision);
			z=reshape(u,(1+lcomplex),size_packet)';
			if lcomplex
				out = [out;complex(z(:,1),z(:,2))];
			else
				out = [out;z];
			end
		end
		
		finalout(:,:,:,:,:,imc-first_read(6)+1) = reshape(out,number_read(1:5));
		
	%==============================================================
	%    END OF LOOP ON MONTE-CARLO TRIALS
	%--------------------------------------------------------------

	end
	
	finalout = reshape(finalout,number_read);
	
	%==============================================================
	%    CLOSING FILE
	%--------------------------------------------------------------

    fclose(fid);

	%==============================================================
	%    OUTPUT
	%--------------------------------------------------------------

	varargout(1)={finalout};
	
end
%
%============================================================================
%============================================================================
%    READING OF FILE MISS.IN 
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
if (lin) 

	%==============================================================
	%    NO COMMENTS FOR FEMESH
	%--------------------------------------------------------------

%	ldispfemesh = femesh('dispflag');
%	if ldispfemesh
%		femesh('dispflagoff')
%	end

	%===================================================================
	% INPUT
	%-------------------------------------------------------------------
	
    if exist(FileName,'file')==2
        [fid,mes]=fopen(FileName,'r');
        if ~isempty(mes)
            disp(mes)
        end;
    else
		texterror = cat(2,'The file ',FileName,' does not exist');
        error(texterror)
    end

	%===================================================================
	% LOOP ON LINES AND READING OF KEYWORDS
	%-------------------------------------------------------------------
	
	line = 'aaaa';
	lmail = 0;
	
    while ~comstr(line,'FIN ')

		line = num2str(fgetl(fid));
		if length(line)<4
			line = comstr(line,[-4 4]);
		end

		% END OF FILE : error in writing of MISS.IN
        %---------------------------------------------------
	
		if comstr(line,'-1')
		
			error('your MISS.IN file must end with command FIN')

		% COMMENTARY : line starts with '*'
        %---------------------------------------------------
	
		elseif comstr(line,'*')
		
		
		% KEYWORD GENE : generic name of the problem
        %---------------------------------------------------
	
        elseif comstr(line,'GENE')
			
            [keyword,line] = nextword(line);
            if ~exist('gene')
				lmissvar = 0;
                gene{1}=line;
            else
				lmissvar = 1;
                sizegene=size(gene);
                gene{sizegene(1,2)+1}=line;
            end
			
			miss.name=gene;

		% KEYWORD DATA : entering menu DATA
        %---------------------------------------------------
	
        elseif comstr(line,'DATA')
			
			while ~comstr(line,'FIND')
			
				line = fgetl(fid);
				if length(line)<4
					line = comstr(line,[-4 4]);
				end

				% KEYWORD TITR : title of data (menu DATA)
				if comstr(line,'TITR')
				
					if ~exist('titr')
						titr{1}=cat(2,'DATA:',fgetl(fid));
					else
						sizetitr=size(titr);
						titr{sizetitr(1,2)+1}=cat(2,'DATA:',fgetl(fid));
					end
					miss.title=titr;

				% KEYWORD GROU : groups of elements (menu DATA)	
				elseif comstr(line,'GROU')
				
					while ~comstr(line,'FING')
					
						line = fgetl(fid);
						
					end

				% KEYWORD FREQ : frequency range (menu DATA)	
				elseif comstr(line,'FREQ')
					
					miss.freq = missread_freq(line);
							
				% KEYWORD MAIL/MVOL : mesh reading (menu DATA)	
				elseif (comstr(line,'MVOL')|comstr(line,'MAIL'))&~lmail
				
					[keyword,line] = nextword(line);
					[meshfile,line] = nextword(line);

					meshfile = cat(2,FileName(1:max(find(FileName=='/'))),meshfile);
					
					if ~isempty(meshfile)
						if(exist(meshfile,'file'))
							[miss.model.Node,miss.model.Elt,miss.mesh_info] = missread_mesh(meshfile);
						else
							texterror = cat(2,'the mesh file ',meshfile,' does not exist');
							error(texterror)
						end
					else
						error('the reading of a mesh directly in the MISS.IN file has not been implemented yet')
					end
	
					if (ldrawing)
						cf=feplot; cf.model = miss.model;
					end
					lmail = 1;
	
				end

			end
			
		% KEYWORD DOS2M : entering menu DOS2M
        %---------------------------------------------------
	
        elseif comstr(line,'DOS2M')
			
			[keyword,line] = nextword(line);

			if ~isempty(line)
				[keyword,line] = nextword(line);
				if comstr(keyword,'Z0')
					[keyword,line] = nextword(line);
					z0 = sscanf(keyword,'%f');
				else
					texterror = cat(2,'unknown argument ',keyword,' after DOS2M');
					error(texterror)
				end
			else
				z0 = 0;
			end
			
			line = fgetl(fid);
			[keyword,line] = nextword(line);
			if comstr(keyword,'LIRE')
				[dos2mfile,line] = nextword(line);
				dos2mfile = cat(2,FileName(1:max(find(FileName=='/'))),dos2mfile);
				[fid_dos2m,texterror] = fopen(dos2mfile,'r');
				if ~isempty(texterror) 
					error(texterror); 
				end
				miss.soil = missread_dos2m(fid_dos2m);
				fclose(fid_dos2m);
			else
				miss.soil = missread_dos2m(fid);
			end
			miss.soil.z0 = z0;
			% completion of the model.Elt MatID for MatID = Inf
			height_layers = z0 - miss.soil.layers(:,1);
			for ielt = 1:size(miss.model.Elt,1)
				if (miss.model.Elt(ielt,9)==Inf & miss.model.Elt(ielt,1)~=Inf);
					height = miss.model.Node(miss.model.Elt(ielt,1),7);
					MatID = miss.soil.layers(find(height-height_layers,1),2);
					miss.model.Elt(ielt,9) = MatID;
				end
			end
			line = 'aaaa';
			
		% KEYWORD EXEC : entering menu EXECUTION
        %---------------------------------------------------
	
        elseif comstr(line,'EXEC')
			
			[keyword,line] = nextword(line);
		
			if comstr(line,'GLOB')
				[keyword,line] = nextword(line);

				% KEYWORD NBMC : number of monte carlo trials
				if comstr(line,'NBMC')
					[keyword,line] = nextword(line);
					[keyword,line] = nextword(line);
					miss.missvar.nbmc = sscanf(keyword,'%i');
				end
				
			end
			
		% KEYWORD FLUI
        %---------------------------------------------------
	
        elseif comstr(line,'FLUI')
            pl(1)=sscanf(line,'FLUI RO%f');
            pl(2)=sscanf(line(14:end),'CELERITE%f');
            cas.pl=[1, 11, pl(1), phelpl(2)];
        
        elseif comstr(line,'CONT')
            controle= fscanf(fid,'%e');
            cas.controle=reshape(controle,3,length(controle)/3)';
        
        elseif comstr(line,'SOUR')
            i2 = findstr(line,' ');
            cas.source = sscanf(line(i2(1):end),'%e')';
			
		% UNKNOWN KEYWORD
        %---------------------------------------------------
	
%        else
%		
%			texterror = cat(2,'unknown keyword in general loop in MISS.IN : ',line);
%			error(texterror)
		
		end
		
		
	end
	
	if lmissvar
		FEelt = miss.model.Elt;
		femesh('selelt eltname hexa8');
		miss.missvar.nddlhet = (size(FEel0,1)-1)*3;
	end

	fclose(fid);
    
    varargout(1)={miss};

%
%============================================================================
%============================================================================
%    RESETTING OLD VALUE OF DISPFLAG 
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
%	if ldispfemesh
%		femesh('dispflagon')
%	end
end;
%
%============================================================================
%============================================================================
%    READING OF FILE .MISS 
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
if (lmiss)

    if isstr(ext) 
        %FileName=FileName(1:max(find(FileName=='.'))-1);
        File=[FileName,'.',ext];
    else 
        File=[FileName,'.miss'];
    end

    [fid,mes]=fopen(File,'r');
    if ~isempty(mes) 
        error(mes); 
    end

    st	= fgetl(fid);     %Saut de ligne
    nbr 	= fscanf(fid,'%d %d');
    % Reading of  coordinates
    fgetl(fid); 
    r1 	= fscanf(fid,'%e',[3 nbr(1)])';
    %Reading of  elements
    elt	= [];
    for indice = 1:nbr(2),
        r2  = fscanf(fid,'%e')';
        str = fscanf(fid,'%s',[1 1])';
        r3  = fscanf(fid,'%e',[1 1])';
        fgetl(fid);
        elt = [elt;r2 r3];
    end

%  cas.Elt  = [Inf   113   117    97   100    52 0 0 0 0;
%           elt(:,1), elt(:,3), elt(:,5), elt(:,7), ones(nbr(2),1), zeros(nbr(2),5)];

    elt(:,9)= abs(elt(:,9));
    group   = elt(1,9);

    grp_el  = hist(elt(:,9),max(elt(:,9)));
    grp_cs  = cumsum(grp_el); grp_cs = [0 grp_cs];
    cas.Elt = [];
  
    for ii = 1:size(grp_el,2)
        cas.Elt  = [cas.Elt;
% 	format QUAD4: Inf   113   117    97   100    52; n1 n2 n3 n4 00
%           Inf   113   117    97   100    52 ;
%           [Inf abs('tria3')] ;
           [Inf abs('quad4')] ;
        elt(grp_cs(ii)+1:grp_cs(ii+1),1), ...
        elt(grp_cs(ii)+1:grp_cs(ii+1),3), ...
        elt(grp_cs(ii)+1:grp_cs(ii+1),5), ...
        elt(grp_cs(ii)+1:grp_cs(ii+1),7), zeros(grp_cs(ii+1)-grp_cs(ii),2)];           
    end
  
    temp      = [elt(:,1), elt(:,3), elt(:,5), elt(:,7)];
  
  % format NodeID PID DID GID x y z

    r1=[[1:size(r1,1)]' r1];
    r1(1,5)=0; 
    cas.Node =r1(:,[1 5 5 5 2 3 4]);

  %To get rid of orientation problems

    fclose(fid);
    varargout(1)={cas};

end;
%
%============================================================================
%============================================================================
%    READING OF FILES .CHP .IMP
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
if (lchp)

%-----------------------------------------------------------------

    File1=[FileName,'.chp'];
    File2=[FileName,'.imp'];
    [fid1,mes1]=fopen(File1,'r');if ~isempty(mes1) error(mes1); end
    [fid2,mes2]=fopen(File2,'r');if ~isempty(mes2) disp(mes2); end
 
    if ~isempty(mes2)

        line = fgetl(fid1);
        line = fgetl(fid1);
        nb_mode = sscanf(line,'MODE%i');

        compt=-1;
        while ~comstr(line,'FIN')
            line = fgetl(fid1);
            compt=compt+1;
        end
        nb_node=compt;

        fseek(fid1,0,-1); %rewinds

        line = fgetl(fid1);

        mode=[];
        for imode=1:nb_mode
            line=fgetl(fid1);
            % Reading of  coordinates
            r1 = fscanf(fid1,'%e',[4 nb_node])';
            mode=[mode;r1];
            line=fgetl(fid1);
        end

        mode=mode(:,2:4);
        mode=reshape(mode',1,size(mode,1)*size(mode,2));
        mode=reshape(mode,length(mode)/nb_mode,nb_mode);
        cas.zsolide.mode=mode;
        fclose(fid1);
        varargout(1)={cas};

    else

        line = fgetl(fid1);
        line = fgetl(fid1);
        nb_mode = sscanf(line,'MODE%i');

        line2=fgetl(fid2);

        compt=-1;
        while ~comstr(line,'FIN')
            line = fgetl(fid1);
            compt=compt+1;
        end
        nb_node=compt;

        fseek(fid1,0,-1); %rewinds

        line = fgetl(fid1);

        mode=[];
        for imode=1:nb_mode
            line=fgetl(fid1);
            % Reading of  coordinates
            r1 = fscanf(fid1,'%e',[4 nb_node])';
            mode=[mode;r1];
            line=fgetl(fid1);
        end

        freq=[];
        freq = fscanf(fid2,'%e',[2 nb_mode])';

        mode=mode(:,2:4);
        mode=reshape(mode',1,size(mode,1)*size(mode,2));
        mode=reshape(mode,length(mode)/nb_mode,nb_mode);
        cas.zsolide.mode=mode;
        cas.zsolide.freq=freq(:,1);
        cas.zsolide.amor=freq(1,2)
        fclose(fid1);
        fclose(fid2);
        varargout(1)={cas};

    end

end
%
%============================================================================
%============================================================================
%    FUNCTION NEXTWORD 
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
function [keyword,lineout] = nextword(linein)
% syntax : lineout = nextword(linein)
%
%     nextword returns the contents of linein starting at the second word of
%     linein and without possible blanks at the beginning and at the end of
%     linein.

% Regis Cottereau 06/2004

linein = comstr(linein,1);

if ~isempty(find(linein==' '))
	lineout = comstr(linein,min(find(linein==' ')));
	keyword = comstr(linein(1:min(find(linein==' '))),1);
else
	lineout = '';
	keyword = linein;
end
%
%============================================================================
%============================================================================
%    FUNCTION MISSREAD_FREQ 
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
function freq = missread_freq(line)
% syntax : freq = missread_freq(line)
%
%      missread_freq reads the content of line and returns the corresponding
%      frequency vector

% Regis Cottereau 06/2004

[keyword,line] = nextword(line);
[keyword,line] = nextword(line);

if comstr(keyword,'DE')
	[keyword,line] = nextword(line);
	freqfrom = str2num(keyword);
else
	error('unknown chain of commands in FREQ')
end

[keyword,line] = nextword(line);

if comstr(keyword,'A')
	[keyword,line] = nextword(line);
	freqto =  str2num(keyword);
else
	error('unknown chain of commands in FREQ')
	end

[keyword,line] = nextword(line);

if comstr(keyword,'PAS')
	[keyword,line] = nextword(line);
	freqstep =  str2num(keyword);
else
	error('unknown chain of commands in FREQ')
end

freq = [freqfrom:freqstep:freqto];

if comstr(line,'(RAD/S)')
	freq = freq/(2*pi);
end

%
%============================================================================
%============================================================================
%    FUNCTION MISSREAD_MAIL 
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
function [nodes,elts,mesh_info] = missread_mesh(meshfile)
% syntax : [nodes,elts,mesh_info] = missread_mesh(meshfile)
%
%      missread_mesh reads the mesh in meshfile and returns it in 
%      Matlab/SDT format. 

% Regis Cottereau 06/2004

clear global FEelt FEnode FEel0 FEel1

[fid,texterror] = fopen(meshfile,'r');
if ~isempty(texterror) 
	error(texterror); 
end

mesh_info.title=comstr(fgetl(fid),1);
keyword=sscanf(fgetl(fid),'%i');
mesh_info.nb_nodes=keyword(1,1);
mesh_info.nb_elts=keyword(2,1);
mesh_info.format = comstr(fgetl(fid),1);

format = lower(mesh_info.format);
if ((length(format)==0)|(format(1:4) == 'libr'))
	format = '%f';
else
	if(format(1) == '(')
		format = format(2:end-1);
	end
	if(length(find(format =='f'))~=0)
		format = cat(2,'%',format(find(format =='f')+1:find(format =='.')-1),'f');
	elseif(length(find(format =='e'))~=0)
		format = cat(2,'%',format(find(format =='e')+1:find(format =='.')-1),'e');
	elseif(length(find(format =='g'))~=0)
		format = cat(2,'%',format(find(format =='g')+1:find(format =='.')-1),'g');
	else
		texterror = cat(2,'the format ',format,' is unrecognized');
		error(texterror);
	end
end
format = cat(2,format,' ',format,' ',format);

femesh

coord = fscanf(fid,format,[3 mesh_info.nb_nodes])';
FEnode = [cumsum(ones(mesh_info.nb_nodes,1)),zeros(mesh_info.nb_nodes,3),coord];
                
connect=[];
grp=[];
compgrp1 = 0;
compconnect1 = [];
line=fgetl(fid);

for ielt = 1:mesh_info.nb_elts

	line=fgetl(fid);

	compgrp2=sscanf(comstr(line,find(line=='G')+2),'%i');
	if compgrp1~=compgrp2
		grp = [grp ielt];
		compgrp1 = compgrp2;
	end
	
	connect=sscanf(line,'%f',20)';
	compconnect2=find(connect);

	if (length(compconnect2)~=length(compconnect1))
		if ~isempty(compconnect1)
			femesh('addsel');
		end
		if(length(compconnect2)==1)
			FEel0=[Inf abs('mass1') 0 0 0 0];
			lmat = 0;
		elseif(length(compconnect2)==3)
			FEel0=[Inf abs('tria3') 0 0 0 0];
			lmat = 0;
		elseif(length(compconnect2)==4)
			FEel0=[Inf abs('quad4') 0 0 0 0];
			lmat = 0;
		elseif(length(compconnect2)==8)
			FEel0=[Inf abs('hexa8') 0 0 0 0];
			lmat = 1;
		else
			error('unknown element')
		end
	end
		
	if ~lmat
		FEel1 = [connect(compconnect2) zeros(1,8-size(compconnect2,2)) 0 0];
	else
		% Inf is entered as MatID value and will be completed with DOS2M
		FEel1 = [connect(compconnect2) zeros(1,8-size(compconnect2,2)) Inf 0];
	end
	
	FEel0 = [FEel0; FEel1];
	
	compconnect1 = compconnect2;

end

femesh('addsel')

nodes = FEnode;
elts = FEelt;
mesh_info.groups = grp;

fclose(fid);
%
%============================================================================
%============================================================================
%    FUNCTION MISSREAD_DOS2M 
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
function dos2m = missread_dos2m(fid)
% syntax : dos2m = missread_dos2m(fid_dos2m)
%
%      missread_dos2m reads the dos2m info in the file corresponding to
%      fid_dos2m and returns it in Matlab/SDT format. 

% Regis Cottereau 07/2004

line = 'aaaa';

while ~isempty(line) & ~comstr(num2str(line),'-1') & ~comstr(num2str(line),'FIND')

	line = num2str(fgetl(fid));

	%===================================================================
	% KEYWORD GENE : generic name for dos2m files
	%-------------------------------------------------------------------
	
	if comstr(line,'GENE')
		
		[keyword,line] = nextword(line);
		dos2m.info.name = line;

	%===================================================================
	% KEYWORD TITRE : title for soil caracteristics
	%-------------------------------------------------------------------
	
	elseif comstr(line,'TITR')
		
		line = fgetl(fid);
		dos2m.info.title = comstr(line,1);

	%===================================================================
	% KEYWORD MATE : caracteristics of the materials
	%-------------------------------------------------------------------

	elseif comstr(line,'MATE')
	
		[keyword,line] = nextword(line);
		[keyword,line] = nextword(line);
		nb_mat = sscanf(keyword,'%i');
		
		dos2m.pl = zeros(nb_mat,9);
		dos2m.pl(:,1) = cumsum(ones(nb_mat,1));
		dos2m.pl(:,2) = fe_mat('m_elastic','SI',1);
		
		line = fgetl(fid);
		le = 0;
		lv = 0;
		leta = 0;
		for itype = 1:4
			[keyword,line] = nextword(line);
			if comstr(keyword,'RO')|comstr(keyword,'MVOL')
				iro = itype;
			elseif comstr(keyword,'E')|comstr(keyword,'YOUN')
				if lv
					error('you cannot define E or NU at the same time as VS or VP');
				else
					ie = itype;
					le = 1;
				end
			elseif comstr(keyword,'NU')|comstr(keyword,'POIS')
				if lv
					error('you cannot define E or NU at the same time as VS or VP');
				else
					inu = itype;
					le = 1;
				end
			elseif comstr(keyword,'VS')
				if le
					error('you cannot define VS or VP at the same time as E or NU');
				else
					ivs = itype;
					lv = 1;
				end
			elseif comstr(keyword,'VP')
				if le
					error('you cannot define VS or VP at the same time as E or NU');
				else
					ivp = itype;
					lv = 1;
				end
			elseif comstr(keyword,'BETA')|comstr(keyword,'HYST')
				ibeta = itype;
			else
				texterror = cat(2,'unknown argument ',keyword);
				error(texterror)
			end
		end
		if ~isempty(line) & (comstr(line,'ETA')|comstr(line,'VISQ'))
			ieta = 5;
			leta = 1;
		end
		if ((~le)*(~lv))
			error('you have to define at least one of the couples E/NU or VS/VP')
		end
		
		for imat = 1:nb_mat
			line = fgetl(fid);
			if leta
				prop_mat = sscanf(line,'%f %f %f %f %f');
			else
				prop_mat = sscanf(line,'%f %f %f %f');
			end
			if le
				dos2m.pl(imat,3) = prop_mat(ie);
				dos2m.pl(imat,4) = prop_mat(inu);
			else
				mu = prop_mat(iro)*prop_mat(ivs)^2;
				lamb = prop_mat(iro)*prop_mat(ivp)^2 - 2*mu;
				dos2m.pl(imat,3) = mu* (3*lamb+2*mu)/(lamb+mu);
				dos2m.pl(imat,4) = lamb / (2 * (lamb + mu));
			end
			dos2m.pl(imat,5) = prop_mat(iro);
			if le
				dos2m.pl(imat,6) = prop_mat(ie) / (2*(1+prop_mat(inu)));
			else
				dos2m.pl(imat,6) = mu;
			end
			dos2m.pl(imat,7) = prop_mat(ibeta);
		end

	%===================================================================
	% KEYWORD COUC : geometry of the layers
	%-------------------------------------------------------------------

	elseif comstr(line,'COUC')
	
		[keyword,line] = nextword(line);
		[keyword,line] = nextword(line);
		nb_layers = sscanf(keyword,'%i');
		
		layers = zeros(nb_layers+1,2);
		
		line = fgetl(fid);
		[keyword,line] = nextword(line);
		layers(1,1) = sscanf(keyword,'%f');
		[keyword,line] = nextword(line);
		[keyword,line] = nextword(line);
		layers(1,2) = sscanf(keyword,'%i');
		
		nb_layers_id = 0;
		if nb_layers>1
			for ilayer = 2:nb_layers
				line = fgetl(fid);
				[keyword,line] = nextword(line);
				layers(ilayer-nb_layers_id,1) = sscanf(keyword,'%f');
				[keyword,line] = nextword(line);
				[keyword,line] = nextword(line);
				layers(ilayer-nb_layers_id,2) = sscanf(keyword,'%i');
				if (layers(ilayer-nb_layers_id,2)==layers(ilayer-nb_layers_id-1,2))
					layers(ilayer-nb_layers_id-1,1) = layers(ilayer-nb_layers_id-1,1) + layers(ilayer-nb_layers_id,1);
					nb_layers_id = nb_layers_id + 1;
				end
			end
		end
		layers = layers(1:nb_layers-nb_layers_id+1,:);
		
		layers(end,1) = Inf;
		line = fgetl(fid);
		[keyword,line] = nextword(line);
		[keyword,line] = nextword(line);
		[keyword,line] = nextword(line);
		layers(end,2) = sscanf(keyword,'%f');
		
		dos2m.layers = layers;

	%===================================================================
	% KEYWORD ALGO : type and caracteristics of algorithme
	%-------------------------------------------------------------------

	elseif comstr(line,'ALGO')
		
		[keyword,line] = nextword(line);

		if isempty(line)
			dos2m.algo.type = '';
		elseif comstr(line,'DEPL')
			dos2m.algo.type = 'DEPL';
		elseif comstr(line,'REGU')
			dos2m.algo.type = 'REGU';
		else
			texterror = cat(2,'unknown argument after ALGO : ',line);
			error(texterror);
		end
		
		keyword = 'SPEC';
		
		while (comstr(keyword,'SPEC')|comstr(keyword,'OFFS')|comstr(keyword,'DREF'))
	
			line = fgetl(fid);
			[keyword,line] = nextword(line);

		% KEYWORD SPEC
        %---------------------------------------------------
		
			if comstr(keyword,'SPEC')
		
				if ~isempty(find(line == '/'))
					dos2m.algo.pmax = sscanf(comstr(line(1:find(line == '/')-1),1),'%f');
					dos2m.algo.np = sscanf(comstr(line(find(line == '/')+1:end),1),'%i');
					dos2m.algo.dp = dos2m.algo.pmax/(dos2m.algo.np-1);
				elseif ~isempty(find(line == '*'))
					dos2m.algo.np = sscanf(comstr(line(1:find(line == '*')-1),1),'%i');
					dos2m.algo.dp = sscanf(comstr(line(find(line == '*')+1:end),1),'%f');
					dos2m.algo.pmax = (dos2m.algo.np-1)*dos2m.algo.dp;
				else
					texterror = cat(2,'unknown commands after keyword SPEC : ',line);
					error(texterror)
				end

		% KEYWORD OFFS
        %---------------------------------------------------
		
			elseif comstr(keyword,'OFFS')

				if ~isempty(find(line == '/'))
					dos2m.algo.rmax = sscanf(comstr(line(1:find(line == '/')-1),1),'%f');
					dos2m.algo.nr = sscanf(comstr(line(find(line == '/')+1:end),1),'%i');
					dos2m.algo.dr = dos2m.algo.rmax/(dos2m.algo.nr-1);
				elseif ~isempty(find(line == '*'))
					dos2m.algo.nr = sscanf(comstr(line(1:find(line == '*')-1),1),'%i');
					dos2m.algo.dr = sscanf(comstr(line(find(line == '*')+1:end),1),'%f');
					dos2m.algo.rmax = (dos2m.algo.nr-1)*dos2m.algo.dr;
				elseif ~isempty(find(line == 'D'))
					ind_d = find(line == 'D');
					ind_a = find(line == 'A');ind_a = ind_a(1);
					ind_p = find(line == 'P');
					rmin = comstr(line(ind_d+2:ind_a -1),1);
					dos2m.algo.rmax = comstr(line(ind_a+1:ind_p -1),1);
					dr = comstr(line(ind_p+3:end),1);
					dos2m.algo.nr = dos2m.algo.rmax/dr+1;
					dos2m.algo.dr = dr;
				else
					texterror = cat(2,'unknown commands after keyword SPEC : ',line);
					error(texterror)
				end

		% KEYWORD DREF
        %---------------------------------------------------
		
			elseif comstr(keyword,'DREF')
				
				dos2m.algo.dref = sscanf(line,'%f');
				
			end
			
		end
		
	end

end
%
%============================================================================
%============================================================================
%    FUNCTION MISVAR_TYPE_FILE 
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
function [ind_mc,lvar]=misvar_type_file(extension)
% MISVAR_TYPE_FILE type of missvar file
%
%     As of now, Pro_miss does not have a separate marker for
%     the monte carlo trials and uses some other dimension for it,
%     depending on the type of file. this function gives you the 
%     dimension used (ind_mc) and whether this type of file depends
%     on the monte carlo trials (lvar)
%
% syntax : [ind_mc,lvar]=misvar_type_file(filename)
%   extension : name of the extension of the file to be examined
%      alternatively you can enter directly the name of the file
%   ind_mc : indicates the dimension of the matrix that is used to
%      store the monte carlo trials
%   lvar : logical indicator of the dependancy of the file to MC trials
%      (1 = dependant ; 0 = independant)
%
% as of now the only extensions that are supported are :
%   .IMPDC .UTOT .UI .MVFD .FS
% 
% example : [ind_mc,lvar]=misvar_type_file('civaux.MVFD');
%      [ind_mc,lvar]=misvar_type_file('IMPDC');

% R?gis Cottereau 04/2004

if (length(find(extension=='.'))>0)
	extension=extension((max(find(extension=='.'))+1):end);
end

if (comstr(extension,'impdc')+comstr(extension,'utot')+comstr(extension,'fs'))
	ind_mc=3;
	lvar=1;
elseif (comstr(extension,'ui'))
	ind_mc=3;
	lvar=0;
elseif (comstr(extension,'mvfd'))
	ind_mc=2;
	lvar=1;
else
	help misvar_type_file;
	error('invalid extension : extension yet to be implemented')
end
%
%============================================================================
%============================================================================
%    FUNCTION MISREAD_LOAD 
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
%
function varargout = misread_load(varargin)
% MISREAD_LOAD for loading and testing input variables for function MISREAD
%
% syntax : output = misread(operation,options)
%   operation : type of loading performed. Accepted values are
%         'partial_reading'

% R. Cottereau 08/2004

	%==============================================================
	%    INPUT
	%--------------------------------------------------------------

if nargin>0
	
	operation = varargin{1};
	
	if comstr(operation,'partial_reading')
		l_partial_reading = 1;
		
	else
		texterror = cat(2,'unknown operation type : ',operation);
		error(texterror)
	end

end

	%==============================================================
	%    PARTIAL READING
	%--------------------------------------------------------------

if l_partial_reading
	
	if nargin~=3
		error('incorrect number of arguments for operation PARTIAL_READING')
	end
	
	indices = varargin{2};
	lmontecarlo = varargin{3};
	first_read = zeros(1,6);
	number_read = zeros(1,6);
	
	if (length(indices)==10)
		if size(indices,1)==1
			indices = [indices,[1 0]];
		else
			indices = [indices;[1 0]];
		end
	elseif ~lmontecarlo & (length(indices)~=10)
		error('incorrect number of arguments : argument 4 is a vector of length = 10')
	elseif lmontecarlo & (length(indices)~=12)
		error('incorrect number of arguments : argument 4 is a vector of length = 12')
	end

	for iindice = 1:6
		first_read(iindice) = indices(2*(iindice-1)+1);
		number_read(iindice) = indices(2*(iindice-1)+2);
	end

	varargout{1} = first_read;
	varargout{2} = number_read;
	
end

	%==============================================================
	%    END
	%--------------------------------------------------------------

