% file      : packSrc.m
% usuage    : pack all verilog source file into one file, source file name
%           : are set in the function, output file name are set as arg
% author    : weitao.du
% date      : 2006.Otc31th
% version   : 0.2
% modification
% 0.2 - 0.1
%   use cell as input parameter
% --------------------------------------------------------------------

function packSrc(inFileList, outfilename)
  version = 0.2;
  % check arg
  error(nargchk(1,2,nargin));
  if(~iscell(inFileList))
    fprintf(1, 'packSrc: ERROR, inFileList should be a Nx1 cell with string element\n');
    return;
  end
  check = isstr(outfilename);
  if(~check)
    fprintf(1,'packSrc: ERROR input arg should be a string\n');
    return;
  end
  outfilename = DelWhiteSpace(outfilename);
  logFileName = 'pack.log';


  [row, col] = size(inFileList) ;

  row = row + 1; % one more file for LOG

  inFileName = cell(row, 1);
  
  inFileName{1} = logFileName;
  
  for idx = 2 : row
    inFileName{idx} = DelWhiteSpace(inFileList{idx-1,:});
    if(strcmp(inFileName{idx}, outfilename))
      fprintf(1, 'packSrc: ERROR, input file(%d) has the same name with output file\n', idx-1);
      return;
    end
  end

  % Generate Log file
  wrFid = fopen(logFileName, 'w');
  fprintf(wrFid, '//###############################################################################\n');
  fprintf(wrFid, '// packed by packSrc.m version %-3.1f\n', version);
  fprintf(wrFid, '// Date %s \n',  datestr(now));
  fprintf(wrFid, '// packed file list\n');
  for(idx = 2:row)
    fprintf(wrFid, '//     %s \n', inFileName{idx});
  end
  fprintf(wrFid, '//################################################################################\n');
  fclose(wrFid);


  % open output file 
  wrFid = fopen(outfilename, 'w');
  if(wrFid == 0)
    fprintf(1,'packSrc: create file "%s" failed\n', outfilename);
  end


  % pack each INPUT FILE
  for(idx = 1 : row)     % the first file is log file
    rdFileName = inFileName{idx};
    rdFid      = fopen(rdFileName, 'r');
    if(rdFid == -1)
      fprintf(1,'packSrc: open file "%s" failed\n', rdFileName);
      return;
    else
      fprintf(1,'packSrc: pack file "%s" \n', rdFileName);
      src = fread(rdFid);
      fwrite(wrFid, src, 'uchar');
    end
    rdFid      = fclose(rdFid);
  end   % for(idx)
  
  fprintf(1,'packSrc: file "%s" writed \n', outfilename);
  fclose(wrFid);


% ##############################################################
% function : DelWhithSpace(), delete the space in the string
% ##############################################################
function strOut = DelWhiteSpace(strIn)
  strLen    = length(strIn);
  inIdx     = 1;
  outIdx    = 1;
  for inIdx = 1:strLen
    if(strIn(inIdx) ~= ' ')
      strOut(outIdx) = strIn(inIdx);
      outIdx = outIdx + 1;
    end
  end
return
