0001 function out = pr_spm_justify(n,varargin)
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033 out = {};
0034 for i=1:nargin-1,
0035 if iscell(varargin{i}),
0036 for j=1:numel(varargin{i}),
0037 para = justify_paragraph(n,varargin{i}{j});
0038 out = {out{:},para{:}};
0039 end;
0040 else
0041 para = justify_paragraph(n,varargin{i});
0042 out = {out{:},para{:}};
0043 end;
0044 end;
0045
0046 function out = justify_paragraph(n,txt)
0047 if numel(txt)>1 && txt(1)=='%',
0048 txt = txt(2:end);
0049 end;
0050
0051 st1 = findstr(txt,'/*');
0052 en1 = findstr(txt,'*/');
0053 st = [];
0054 en = [];
0055 for i=1:numel(st1),
0056 en1 = en1(en1>st1(i));
0057 if ~isempty(en1),
0058 st = [st st1(i)];
0059 en = [en en1(1)];
0060 en1 = en1(2:end);
0061 end;
0062 end;
0063
0064 str = [];
0065 pen = 1;
0066 for i=1:numel(st),
0067 str = [str txt(pen:st(i)-1)];
0068 pen = en(i)+2;
0069 end;
0070 str = [str txt(pen:numel(txt))];
0071 txt = str;
0072
0073 off = find((txt'>='a' & txt'<='z') | (txt'>='A' & txt'<='Z'));
0074 off = off(off<n);
0075 if isempty(off),
0076 out{1} = txt;
0077 else
0078 off = off(1);
0079 para = justify_para(n-off+1,txt(off:end));
0080 if numel(para)>1,
0081 out{1} = [txt(1:(off-1)) para{1}];
0082 for j=2:numel(para),
0083 out{j} = [repmat(' ',1,off-1) para{j}];
0084 end;
0085 else
0086 out{1} = txt;
0087 end;
0088 end;
0089 return;
0090
0091 function out = justify_para(n,varargin)
0092
0093 str = varargin{1};
0094 for i=2:length(varargin),
0095 str = [str ' ' varargin{i}];
0096 end;
0097
0098 if isempty(str), out = {''}; return; end;
0099
0100
0101 sp = find(str==' ');
0102 rep = sp(diff(sp)==1);
0103 str(rep) = [];
0104 if str(1) ==' ', str(1) = ''; end;
0105 if str(end)==' ', str(end) = ''; end;
0106
0107 out = {};
0108 while length(str)>n,
0109
0110
0111 sp = find(str==' ');
0112 brk = sp(sp<=n);
0113 if isempty(brk),
0114 if isempty(sp),
0115 brk = length(str)+1;
0116 else
0117 brk = sp(1);
0118 end;
0119 else
0120 brk = brk(end);
0121 end;
0122
0123
0124 current = str(1:(brk-1));
0125
0126
0127 sp = find(current==' ');
0128 if ~isempty(sp),
0129
0130
0131 sp = [sp length(current)+1];
0132 words = {current(1:(sp(1)-1))};
0133 for i=1:(length(sp)-1),
0134 words = {words{:}, current((sp(i)+1):(sp(i+1)-1))};
0135 end;
0136
0137
0138 nsp = length(sp)-1;
0139 pad = (n-(length(current)-nsp))/nsp;
0140
0141
0142 sp = repmat(floor(pad),1,nsp);
0143
0144
0145 pad = round((pad-floor(pad))*nsp);
0146 [unused,ind] = sort(rand(pad,1));
0147 ind = ind(1:pad);
0148 sp(ind) = sp(ind)+1;
0149
0150
0151 current = words{1};
0152 for i=2:length(words),
0153 current = [current repmat(' ',1,sp(i-1)) words{i}];
0154 end;
0155 end;
0156
0157 out = {out{:},current};
0158 str = str((brk+1):end);
0159 end;
0160
0161 out = {out{:},str};