%---------------------------------------------------------------------  
% function [] = FT_write_blocks_into_file(blocks,filename)
% 
% Writes list of blocks to file, which then can be used as
% a input file.for a simulation program like Finesse
%
% blocks: vector of blocks
% filename: string, name of file
%
% Part of the SimTools package
% Andreas Freise 22.05.08 afreise@googlemail.com
%---------------------------------------------------------------------  

function [] = FT_write_blocks_into_file(blocks,filename)
  
  baseid='FT_write_blocks_into_file';
  
  if (~isstruct(blocks))
    msgid=[baseid,':checkinarg'];
    result='first input argument must be a block structure';
    error(msgid,result);
  end

  if (~isstr(filename))
    msgid=[baseid,':checkinarg'];
    result='second input argument must be a filename';
    error(msgid,result);
  end
  
  FT_make_backup(filename);
  
  bl=length(blocks);
  
  [FID, result]=fopen(filename,'W');
  
  if (FID==-1)
    msgid=[baseid,':fileopen'];
    error(msgid,result);
  end

  % walk through the list of blocks
  for i=1:bl
    
    % add a comment if the block has been read from another file
    if (~isempty(blocks(i).filename))
      fprintf(FID,'%% read from file "%s"',blocks(i).filename);
      line_started=1;
    else
      line_started=0;
    end
    
    % add a comment if the block has been edited or created by hand
    if (blocks(i).edited)
      if (line_started)
        fprintf(FID,',');
      else
        fprintf(FID,'%%');
      end
      fprintf(FID,' manually edited');
    end
    fprintf(FID,'\n');
    fprintf(FID,'%%%%%% FTblock %s\n',blocks(i).name);
    ll=blocks(i).n_lines;
    for j=1:ll
      blocks(i).txt_lines{j};
      fprintf(FID,'%s\n',blocks(i).txt_lines{j});
    end
    fprintf(FID,'%%%%%% FTend %s\n', blocks(i).name);
    fprintf(FID,'\n');
  end

  fclose(FID);

  % A silly try to force Matlab to re-read the directory we are in so
  % that the new file is recognised if it's an m-file
  dummy=ls(filename);
  
