function code_chart_source_file_rtw(fileNameInfo,chart)

%%   Copyright 1995-2004 The MathWorks, Inc.
%%   $Revision: 1.1.6.13 $  $Date: 2004/08/10 02:23:54 $


   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   %%%%%  GLOBAL VARIABLES
   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

   global gMachineInfo gChartInfo

   chartNumber = sf('get',chart,'chart.number');
   fileName = fullfile(fileNameInfo.targetDirName,fileNameInfo.chartSourceFiles{chartNumber+1});
   sf_echo_generating('Coder',fileName);

   file = fopen(fileName,'wt');
   if file<3
      construct_coder_error([],sprintf('Failed to create file: %s.',fileName),1);
      return;
   end

fprintf(file,'%%implements "chartSource" "C"\n');

fprintf(file,'%%function ChartConfig(block, system) void\n');
fprintf(file,'  %%createrecord chartConfiguration { ...\n');
fprintf(file,'          executeAtInitialization  %.15g ...\n',sf('get',chart,'chart.executeAtInitialization'));
fprintf(file,'  }\n');
fprintf(file,'  %%return chartConfiguration\n');
fprintf(file,'%%endfunction\n');

fprintf(file,'%%function ChartFunctions(block,system) void\n');
      x = sf('Cg','get_cg_fcn_data',chart);
      excludedFcn = x.chartGateway.ptr(1);
      funcs = sf('Cg','get_unshared_functions',chart);
fprintf(file,'   %%openfile chartFcnsBuf\n');

        % Inserting Target Math Fcn generation here
        fcnGenString = sf('Cg','get_module_used_target_fcns',chart);
fprintf(file,'     %s\n',strip_trailing_new_lines(fcnGenString));
%        % Inserting Target Math Includes here
%        moduleIncludeString = sf('Cg','get_module_target_include_directives',chart);
%...     $strip_trailing_new_lines(moduleIncludeString)$

         namedConsts = sf('Cg','get_named_consts',chart);
         for namedConst = namedConsts
            codeStr = sf('Cg','get_named_const_def',namedConst,1);
fprintf(file,'         %s\n',strip_trailing_new_lines(codeStr));
         end

         for func = funcs
            codeStr = sf('Cg','get_fcn_decl',func,1);
fprintf(file,'         %s\n',strip_trailing_new_lines(codeStr));
         end
         
         for func = funcs
            if func{1}.ptr(1) ~= excludedFcn
               codeStr = sf('Cg','get_fcn_def',func,1);
fprintf(file,'            %s\n',strip_trailing_new_lines(codeStr));
            end
         end

         %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
         % RTW symbol naming pass for unshared fncs and named constants
         symbols  = [funcs namedConsts];
         numSym   = length(symbols);
         symNames = cell(1, numSym);

         for i = 1:numSym
            % Extract symbol name only if following pattern exists.
            % Otherwise regexprep() would leave the original symbol string untouched.
            symNames{i} = regexprep( sf('Cg', 'get_symbol_name', symbols(i)), ...
                                     '^%<block\.SymbolMapping\.(\S+)>$', '$1' );
         end

         sf('set',chart,'chart.rtwInfo.sfSymbols', symNames);
         %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
         
fprintf(file,'   %%closefile chartFcnsBuf\n');
fprintf(file,'   %%return chartFcnsBuf\n');
fprintf(file,'%%endfunction %%%% ChartFunctions\n');


fprintf(file,'%%function ChartSharedFunctions(block,system) void\n');
fprintf(file,'   %%openfile chartFcnsBuf\n');
         modelName = sf('get',get_relevant_machine,'machine.name');
         if(~rtw_gen_shared_utils(modelName))
            sharedFuncs = sf('Cg', 'get_shared_functions', chart);
            if(~isempty(funcs))
               for func = sharedFuncs
                  fcnName = sf('Cg','get_symbol_name', func);
                  fcnDefCodeStr = sf('Cg','get_fcn_def',func,1);
fprintf(file,'                 %%if %%<!SFLibLookupUtilityFunction("%s")>\n',fcnName);
fprintf(file,'                    %s\n',strip_trailing_new_lines(fcnDefCodeStr));
fprintf(file,'                    %%<SFLibInsertUtilityFunction("%s")>\n',fcnName);
fprintf(file,'                 %%endif\n');
               end
            end
         end
fprintf(file,'   %%closefile chartFcnsBuf\n');
fprintf(file,'   %%return chartFcnsBuf\n');
fprintf(file,'%%endfunction %%%% ChartSharedFunctions\n');



% The chart gateway is always inlined so we only emit the body
% for this function
fprintf(file,'%%function Outputs(block,system) void\n');
      x = sf('Cg','get_cg_fcn_data',chart);
fprintf(file,'   %%openfile codeBuf\n');
         codeStr = sf('Cg','get_fcn_body',x.chartGateway);
fprintf(file,'      %s\n',strip_trailing_new_lines(codeStr));
fprintf(file,'   %%closefile codeBuf\n');
fprintf(file,'   %%return codeBuf\n');
fprintf(file,'%%endfunction  %%%% Outputs\n');

% The chart data initializer is always inlined so we only emit the body
% for this function
fprintf(file,'%%function InlinedInitializerCode(block,system) Output\n');
fprintf(file,'   %%<SLibResetSFChartInstanceAccessed(block)>\\\n');
fprintf(file,'   %%openfile initBodyBuf\n');
         x = sf('Cg','get_cg_fcn_data',chart);
         str = sf('Cg','get_fcn_body',x.chartDataInitializer);
fprintf(file,'      %s\n',str);
fprintf(file,'   %%closefile initBodyBuf\n');
fprintf(file,'   %%if !WHITE_SPACE(initBodyBuf)\n');
fprintf(file,'      /* Initialize code for chart: %%<LibParentMaskBlockName(block)> */\n');
fprintf(file,'      %%<initBodyBuf>\\\n');
fprintf(file,'   %%endif\n');
fprintf(file,'%%endfunction\n');
fprintf(file,'\n');
fprintf(file,'\n');
% The chart enable is always inlined so we only emit the body
% for this function
fprintf(file,'%%function EnableUnboundOutputEventsCode(block,system) Output\n');
fprintf(file,'   %%openfile initBodyBuf\n');
         x = sf('Cg','get_cg_fcn_data',chart);
         str = sf('Cg','get_fcn_body',x.chartEnable);
fprintf(file,'      %s\n',str);
fprintf(file,'   %%closefile initBodyBuf\n');
fprintf(file,'   %%if !WHITE_SPACE(initBodyBuf)\n');
fprintf(file,'      /* Enable code for chart: %%<LibParentMaskBlockName(block)> */\n');
fprintf(file,'      %%<initBodyBuf>\\\n');
fprintf(file,'   %%endif\n');
fprintf(file,'%%endfunction\n');
fprintf(file,'\n');
% The chart disable is always inlined so we only emit the body
% for this function
fprintf(file,'%%function DisableUnboundOutputEventsCode(block,system) Output\n');
fprintf(file,'   %%openfile initBodyBuf\n');
         x = sf('Cg','get_cg_fcn_data',chart);
         str = sf('Cg','get_fcn_body',x.chartDisable);
fprintf(file,'      %s\n',str);
fprintf(file,'   %%closefile initBodyBuf\n');
fprintf(file,'   %%if !WHITE_SPACE(initBodyBuf)\n');
fprintf(file,'      /* Disable code for chart: %%<LibParentMaskBlockName(block)> */\n');
fprintf(file,'      %%<initBodyBuf>\\\n');
fprintf(file,'   %%endif\n');
fprintf(file,'%%endfunction\n');
fprintf(file,'\n');

% Emit shared functions and header files.
fprintf(file,'%%function DumpSharedUtils(block,system) void\n');
   funcs = sf('Cg', 'get_shared_functions', chart);
   if(~isempty(funcs))
      modelName = sf('get',get_relevant_machine,'machine.name');
      if(rtw_gen_shared_utils(modelName))
fprintf(file,'      %%if EXISTS(::GenUtilsSrcInSharedLocation) && (::GenUtilsSrcInSharedLocation == 1)\n');
fprintf(file,'         %%if !ISFIELD(::CompiledModel, "RTWInfoMatFile")\n');
fprintf(file,'            %%<LoadRTWInfoMatFileforTLC()>\n');
fprintf(file,'         %%endif    \n');
         for func = funcs
            fcnName = sf('Cg','get_symbol_name', func);
            fcnDefCodeStr = sf('Cg','get_fcn_def',func,1);
            fcnDeclCodeStr = sf('Cg','get_fcn_decl',func,0);         
            sharedUtilTargetIncludes = sf('Cg','get_shared_fcn_target_includes',func);
            dump_single_shared_util(file, fcnName, fcnDefCodeStr, fcnDeclCodeStr, sharedUtilTargetIncludes);
         end
fprintf(file,'      %%else\n');
fprintf(file,'         %%error WISH change error message, unable to dump shared utils\n');
fprintf(file,'      %%endif  \n');
      end
   end
fprintf(file,'%%endfunction\n');
fprintf(file,'\n');

   dump_chart_data_map(file, chart);

   fclose(file);
   try_indenting_file(fileName);
   sf('Cg','destroy_module',chart);
   
   
function dump_single_shared_util(file, fcnName, fcnDefCodeStr, fcnDeclCodeStr, sharedUtilTargetIncludes)
fprintf(file,' %%if %%<!SFLibLookupUtilityFunction("%s")>\n',fcnName);
fprintf(file,'     %%<SFLibInsertUtilityFunction("%s")>\n',fcnName);
fprintf(file,'     %%openfile defCode\n');
fprintf(file,'     %s\n',sharedUtilTargetIncludes);
fprintf(file,'     %s\n',fcnDefCodeStr);
fprintf(file,'     %%closefile defCode\n');
fprintf(file,'     %%openfile declCode\n');
fprintf(file,'     %s\n',fcnDeclCodeStr);
fprintf(file,'     %%closefile declCode\n');
fprintf(file,'     %%<SLibDumpUtilsSourceCode("%s", declCode, defCode)>\n',fcnName);
fprintf(file,' %%endif\n');

function dump_chart_data_map(file, chart)
% Emit chart data record function, for testpointed data only.
   global gChartInfo gDataInfo

   testPointData   = gChartInfo.testPoints.data;
   testPointStates = gChartInfo.testPoints.state;
   
   numTpData       = length(testPointData);
   numTpStates     = length(testPointStates);
   numTestPoints   = numTpData + numTpStates;
   
fprintf(file,'%%function ChartDataMap(block, system) void\n');
fprintf(file,'  %%createrecord ChartDataElements {\\\n');
fprintf(file,'    NumChartData   %.15g \\\n',numTestPoints);
fprintf(file,'    ChartDataDefaults {\\\n');
fprintf(file,'      RecordType   "ChartData"\\\n');
fprintf(file,'      DataTypeIdx  0\\\n');
fprintf(file,'      IsComplex    0\\\n');
fprintf(file,'      IsFixPoint   0\\\n');
fprintf(file,'      With         1\\\n');
fprintf(file,'      Dimensions   [1,1]\\\n');
fprintf(file,'    }\\\n');

   isComplex     = sf('get', testPointData, 'data.parsedInfo.complexity');
   dataNames     = sf('Cg', 'get_testpoint_mangled_name', testPointData); % Mangled symbol name
   
   % Emit individual data record
   for i = 1:numTpData
      dataId   = testPointData(i);
      
      sfName   = sf('get', dataId, 'data.name'); % Stateflow data dictionary name
      dataPath = sf('FullNameOf', dataId, chart, '.');
      dataSize = sf('get', dataId, 'data.parsedInfo.array.size');
      dataType = sf('CoderDataType', dataId);
      
fprintf(file,'    ChartData {\\\n');
fprintf(file,'      Name         "%s"\\\n',dataNames{i});
fprintf(file,'      SFName       "%s"\\\n',sfName);
fprintf(file,'      Path         "%s"\\\n',dataPath);

      if isComplex(i)
fprintf(file,'      IsComplex    1\\\n');
      end

      if ~strcmp(dataType, 'fixpt')
fprintf(file,'      DataTypeIdx  %%<SLibGetIdFromMLDataType("%s")>\\\n',dataType);
      else
         [baseType, exponent, slope, bias, nBits, isSigned] = sf('FixPtProps', dataId);
fprintf(file,'      DataTypeIdx  %%<SLibGetIdFromMLDataType("%s")>\\\n',baseType);
fprintf(file,'      IsFixPoint   1\\\n');
fprintf(file,'      FixedPointInfo {\\\n');
fprintf(file,'        NumBits    %.15g\\\n',nBits);
fprintf(file,'        IsSigned   %.15g\\\n',isSigned);
fprintf(file,'        FixedExp   %.15g\\\n',exponent);
fprintf(file,'        FracSlope  %.15g\\\n',slope);
fprintf(file,'        Bias       %.15g\\\n',bias);
fprintf(file,'      }\\\n');
      end
      
      if ~isempty(dataSize) && prod(dataSize) ~= 1
         % Otherwise, data is scalar
         if length(dataSize) == 1
            % Stateflow column vector
            dataSize = [dataSize 1];
         end
         Width = prod(dataSize);
         dimStr = sprintf('%d,', dataSize);
         dimStr = ['[' dimStr(1:end-1) ']'];
fprintf(file,'      With         %.15g\\\n',Width);
fprintf(file,'      Dimensions   %s\\\n',dimStr);
      end
fprintf(file,'    }\\\n');
   end

   stateTpNames = sf('Cg', 'get_testpoint_mangled_name', testPointStates); % Mangled symbol name

   % Emit individual state record
   for i = 1:numTpStates
      stateId   = testPointStates(i);
      stateName = sf('get', stateId, 'state.name');
      statePath = sf('FullNameOf', stateId, chart, '.');
      
fprintf(file,'    ChartData {\\\n');
fprintf(file,'      Name         "%s"\\\n',stateTpNames{i});
fprintf(file,'      SFName       "%s"\\\n',stateName);
fprintf(file,'      Path         "%s"\\\n',statePath);
fprintf(file,'      DataTypeIdx  %%<SLibGetIdFromMLDataType("uint8")>\\\n');
fprintf(file,'    }\\\n');
   end
   
fprintf(file,'  }\n');
fprintf(file,'  %%return ChartDataElements\n');
fprintf(file,'%%endfunction\n');
