function fbtmdsget
 
 % FBTMDSGET
 %   Creates the FORTRAN subroutine to read the MGAMS data from the PCS tree in
 %   the MGAMS common block.
 
 MP = mgp(-1);
 name = MP.name;
 eqdp = MP.eqdp;
 dim  = MP.dim;
 mdsclose;
 
 fid = fopen('fbtmgams.inc','r');
 inc = fread(fid,'*char')';
 fclose(fid);
 
 fid = fopen('fbtmdsget.f','w');
 fheader(fid,'\tSUBROUTINE FBTMDSGETCONST(SHOT)\n\tINTEGER SHOT\n')
 for k = find(eqdp == 0)
  if regexp(inc,name{k},'once')
   fvalue(fid,['fix_roprand(f_float(' name{k} '),0.)'],name{k},...
    regexp(inc,[name{k} ' *\( *(\w+) *\)'],'tokens','once'))
  end
 end
 fprintf(fid,'\tEND\n\n');
 
 fheader(fid,'\tSUBROUTINE FBTMDSGETVAR(SHOT,NEQ)\n\tINTEGER SHOT NEQ\n')
 for k = find(eqdp == 1)
  if regexp(inc,name{k},'once')
   if dim(k) == 1
    fvalue(fid,['fix_roprand(f_float(' name{k} '[$1-1]),0.)'],name{k},'')
   else
    fvalue(fid,['fix_roprand(f_float(' name{k} '[*,$1-1]),0.)'],...
     name{k},regexp(inc,[name{k} ' *\( *(\w+) *\)'],'tokens','once'))
   end
  end
 end
 fvalue(fid,'(iansha[$1-1])?(ilie[$1-1]):(sum(fix_roprand(rlim1[*,$1-1],1g200)<1g200,0))','ilie','')
 fvalue(fid,'(iansha[$1-1])?(ilia[$1-1]):(sum(fix_roprand(rlia1[*,$1-1],1g200)<1g200,0))','ilia','')
 fvalue(fid,'sum(fix_roprand(rbro[*,$1-1],1g200)<1g200,0)','ibro','')
 fvalue(fid,'sum(fix_roprand(rbzo[*,$1-1],1g200)<1g200,0)','ibzo','')
 fvalue(fid,'fix_roprand(vsec[$1-1],1g200) < 1g200','ivsec','')
 fprintf(fid,'\tEND\n');
 fclose(fid);
 
function fheader(fid,header)
 fprintf(fid,header);
 fprintf(fid,'\tINCLUDE ''fbtmgams.inc''\n');
 fprintf(fid,'\tINCLUDE ''mdslib.inc''\n');
 fprintf(fid,'\tINTEGER MDSSTATUS MDSLENGTH\n\n');
 fprintf(fid,'\tMDSSTATUS = MDSSETDEFAULT(''\\MGAMS.DATA''//CHAR(0))\n');
 fprintf(fid,'\tIF (MOD(MDSSTATUS,2).EQ.0) THEN\n\t PRINT *,''FBTGET - error selecting MGAMS branch''\n\t STOP 9\n\tENDIF\n\n');
 
function fvalue(fid,expr,name,dim)
 if isempty(dim)
  dim = '';
 else
  dim = [',' dim{1}];
 end
 fprintf(fid,['\tMDSSTATUS = MDSVALUE(\n     1\t''' expr '''//CHAR(0),\n     1\tDESCR(IDTYPE_LONG,NEQ,0),\n     1\tDESCR(' dtype(name) ',' name dim ',0),0,MDSLENGTH)\n']);
 fprintf(fid,['\tIF (MOD(MDSSTATUS,2).EQ.0) THEN\n\t PRINT *,''FBTGET - error reading ' name '''\n\t STOP 9\n\tENDIF\n\n']);
 
function y = dtype(x)
 if regexp(x,'[i-nI-N]','once') == 1
  y = 'IDTYPE_LONG';
 else
  y = 'IDTYPE_FLOAT';
 end
 
