%---------------------------------------------------------------------  
% function [blocks] = FT_read_blocks_from_file(filename)
% 
% Scans a file for blocks and reads them.
%
% filename: string giving filename to read
% blocks: vector of blocks found in file
%
% Part of the SimTools package
% Andreas Freise 22.05.08 afreise@googlemail.com
%---------------------------------------------------------------------  

function [blocks] = FT_read_blocks_from_file(filename)
  
  baseid='FT_read_blocks_from_file';

  if (~isstr(filename))
    msgid=[baseid,':checkinarg'];
    result='input argument must be a filename';
    error(msgid,result);
  end
  
  [FID, result]=fopen(filename,'r');
  
  if (FID==-1)
    msgid=[baseid,':fileopen'];
    error(msgid,result);
  end
  
  file=textscan(FID,'%s','delimiter', '\n', 'whitespace', '', 'commentstyle',{'/*','*/'});
  fclose(FID);
  
  % Now scan file
  disp('--------------------------------------------------------------------');
  
  [n_lines,tmp]=size(file{1});
  disp(sprintf('Read %d lines in file %s',n_lines, filename));
    
  block_index=1;
  i=1;
  while (i<=n_lines)
    txt_linec=file{1}(i);
    [found,blockname]=FT_search_string_for_block_commands(cell2mat(txt_linec));
    switch found
     case 1
      disp(sprintf('Reading block "%s"',blockname));
      blocks(block_index)=FT_create_new_block(blockname);
      blocks(block_index).filename=filename;
      blocks(block_index).n_lines=0;
      blocks(block_index).edited=0;
      blocks(block_index).txt_lines={};
      endnotfound=1;
      while(endnotfound)
        i=i+1;
        if (i>n_lines)
          msgid=[baseid,':readblock'];
          error(msgid,'file ended before block "%s" was finished',blocks(block_index).name);
        end
        txt_linec=file{1}(i);
        txt_line=cell2mat(txt_linec);
        [found,blockname]=FT_search_string_for_block_commands(txt_line);
        switch found
         case 1
          msgid=[baseid,':readblock'];
          error(msgid,'found block "%s" before block "%s" was finished', blockname, blocks(block_index).name);
         case 2
          endnotfound=0;
          block_index=block_index+1;
         otherwise
          %txt_line=FT_remove_comment_from_line(txt_line);
          if (txt_line)
            blocks(block_index).txt_lines=[blocks(block_index).txt_lines,txt_line];
            blocks(block_index).n_lines=blocks(block_index).n_lines+1;
            %disp(sprintf('read line %s',txt_line));
          end          
        end
      end
     case 2
      msgid=[baseid,':readblock'];
      error(msgid,'found end of block but no start');
     otherwise
    end
    i=i+1;
  end
  

  
  