## -*-octave-*-

function write_ibg(system_name,bonds);
  
  fid = fopen([system_name,"_ibg.m"], "wt");
  [nbonds, junk] = size(fieldnames(bonds));
  format_hc = "  %s.bonds.bond%i.head.component\t= \"%s\";\n";
  format_tc = "  %s.bonds.bond%i.tail.component\t= \"%s\";\n";
  format_hp = "  %s.bonds.bond%i.head.ports\t= \"%s\";\n";
  format_tp = "  %s.bonds.bond%i.tail.ports\t= \"%s\";\n";
  format_ce = "  %s.bonds.bond%i.causality.effort\t= \"%s\";\n";
  format_cf = "  %s.bonds.bond%i.causality.flow\t= \"%s\";\n";

  fprintf(fid, "## -*-octave-*-\n\n");
  fprintf(fid, "function [%s] = %s_ibg\n\n", system_name, system_name);
  fprintf(fid, "  ## Intermediate bond graph representation of %s\n", ...
	  system_name);

  fprintf(fid, "  ## Generated by MTT on %s\n", ctime(time));
  fprintf(fid, "  ## head refers to the harpoon end of a bond\n");
  fprintf(fid, "  ## tail refers to the other end of a bond\n");
  fprintf(fid, "  ## causality.? is the end at which ? is imposed\n\n");

  for i=1:nbonds
    fprintf(fid, "\n  ## bond %i\n", i);
    fprintf(fid, format_hc, system_name, i, ...
	    eval(sprintf("bonds.bond%i.head.component", i)));
    fprintf(fid, format_tc, system_name, i, ...
	    eval(sprintf("bonds.bond%i.tail.component", i)));
    fprintf(fid, format_hp, system_name, i, ...
	    eval(sprintf("bonds.bond%i.head.ports", i)));
    fprintf(fid, format_tp, system_name, i, ...
	    eval(sprintf("bonds.bond%i.tail.ports", i)));
    fprintf(fid, format_ce, system_name, i, ...
	    eval(sprintf("bonds.bond%i.causality.effort", i)));
    fprintf(fid, format_cf, system_name, i, ...
	    eval(sprintf("bonds.bond%i.causality.flow", i)));
  endfor;

  fprintf(fid, "\nendfunction\n");
  fclose(fid);

endfunction;