Модуль:Репрессия!

Материал из Кадровый состав НКВД 1935-1939
Перейти к навигации Перейти к поиску

Для документации этого модуля может быть создана страница Модуль:Репрессия!/doc

local repression = {}
local global = mw.ext.luaglobal;
local tools = require( 'Модуль:Tools' )

local ruLang = mw.language.new('ru')


local abbrAuth = {
	['ОО'] = { 'особый отдел', 'особого отдела' },
	['ДТО'] = { 'дорожно-транспортный отдел', 'дорожно-транспортного отдела' },
	['ПВС'] = { 'Президиум Верховного Совета', 'Президиума Верховного Совета' },
	['ВКВС'] = { 'Военная коллегия Верховного суда', 'Военной коллегии Верховного суда' },
	['ВТ'] = { 'военный трибунал', 'военного трибунала' },
	['ВТВ'] = { 'военный трибунал войск', 'военного трибунала войск' },
	['ОСО'] = { 'особое совещание', 'особого совещания' },
	['ГВП'] = { 'Главная военная прокуратура', 'Главной военной прокуратуры' },
	['УНКВД'] = { 'Управление НКВД', 'УНКВД' }, -- в середине бывает с предлогом «при»
	['УНКГБ'] = { 'Управление НКГБ', 'УНКГБ' },
	['ГУГБ'] = { 'ГУГБ', 'ГУГБ' },
	['Генеральная'] = { 'Генеральная', 'Генеральная' }, -- чтобы сохранить большую букву в начале слова
	['СЧ'] = { 'следственная часть', 'следственной части' }, -- чтобы сохранить большую букву в начале слова
	['НИИ'] = { 'НИИ', 'НИИ' },
}

local abbrVerdict = {
	['л/с'] = { 'лишение свободы', 'лишения свободы' },
	['л/с,'] = { 'лишение свободы,', 'лишения свободы,' },
	['л/с;'] = { 'лишение свободы;', 'лишения свободы;' },
	['ВМН'] = { 'ВМН', 'ВМН' },
}

local abbrAuthStriking = {
	['ПВС'] = { 'Президиум Верховного Совета', 'Президиума Верховного Совета' },
	['ВС'] = { 'военный совет', 'военного совета' },
	['ОСО'] = { 'особое совещание', 'особого совещания' },
}


local function deabbr( str, abbr )
	local arr = mw.text.split( str, '%s+' ) -- mw.text.split( string.gsub( str, '%.([^ %d%.])', '. %1' ), '%s+' ) -- это точно портит URL (
	local a = arr[1]
	if abbr[a] then
		a = abbr[a][1]
	elseif string.sub( a, 1, 1 ) == '_' then
		a = string.match( a, '^_%s*(.+)$' )
		if abbr[a] then
			a = abbr[a][1]
		end
	else
--		a = mw.ustring.lower( mw.ustring.sub( a, 1, 1 ) ) .. mw.ustring.sub( a, 2, -1 )
		a = ruLang:lcfirst( a )
	end
	arr[1] = a

	a = arr[#arr]
	local x = string.sub( a, -1, -1 )
	if x == '_' then
		a = string.match( a, '^(.-)%s*_$' )
	elseif x == '.' then
		if a ~= 'обл.' and a ~= 'д.' and a ~= 'ж.д.' then -- ж. д.
			a = string.sub( a, 1, -2 )
		end
	end
	arr[#arr] = a


	for i = 2, #arr do
		local word = arr[i]
		if abbr[word] then
			arr[i] = abbr[word][2]
		end
	end
	return table.concat( arr, ' ' )
end

local attr = {
	['дополнение'] = 'ext',
	['сноска'] = 'ref',
	['источник'] = 'src',
}

local function parseSubargs( str, params, fields ) -- { 'дата', 'орган' }  fields { 'дата' = 'date', 'орган' = 'auth' }
	local elems = mw.text.trim( ( string.gsub( ' ' .. str .. ' ', ' / ', '₪' ) ) )
	elems = mw.text.split( elems, '%s*₪%s*' )
	local list = {} -- здесь мы собираем найденные ключи параметров
	local values = {}
--	for _, field in pairs( fields ) do
--		values[field] = {}
--	end
	local wasCommon, wasSpec
	for _, elem in ipairs( elems ) do
		local k, v = string.match( elem, '^(.-)%s*=%s*(.+)$' )
		if not k then
--			local v = string.match( elem, '^/%s+(.*)$' )
--			if elem == '/' or v then
--				k = #list + 1
--				list[k] = true
--				elem = v or ''
--			end
			k = #list + 1
			list[k] = true
			if k > #params then
				return nil, 'лишний элемент № ' .. k
			end
			if elem ~= '' then
				local field = fields[params[k]]
				values[field] = values[field] or {}
				values[field].val = elem
			end
		elseif list[k] then
			return nil, 'дважды указан элемент «' .. k .. '»'
		else
			if attr[k] then
				list[k] = v -- условно осмысленные значения для неспецифицированных атрибутов
				wasCommon = k
			else
				local a, b = string.match( k, '^(.+)/(.+)' )
				if a and attr[a] and fields[b] then
					list[k] = v
					wasSpec = k
					local field = fields[b]
					values[field] = values[field] or {}
					values[field][attr[a]] = v
				else
					return nil, 'непредусмотренный элемент «' .. k .. '»'
				end
			end
		end
	end
	if wasCommon and wasSpec then
		return nil, 'содержатся одновременно специфицированные и неспецифицированные дополнения (сноски, источники)'
	end
	local lastval
	for _, param in pairs( params ) do
		local x = values[fields[param]]
		if x then
			if not x.val then
				return nil, 'элемент «' .. param .. '» отсутствует, но к нему заданы дополнения (сноски, источники)'
			else
				lastval = x
	--			x.val = deabbr( x.val )
				if x.ext then
					x.ext = deabbr( x.ext, abbrAuth ) -- не факт, что deabbr органов хорош для дополнений
				end
			end
		end
	end
	if wasCommon then
		if lastval then
			if list['дополнение'] ~= '' then
				lastval.ext = list['дополнение']
			end
			if list['сноска'] ~= '' then
				lastval.ref = list['сноска']
			end
			if list['источник'] ~= '' then
				lastval.src = list['источник']
			end
		else
			return nil, 'значения отсутствуют, но заданы дополнения (сноски, источники)'
		end
	end
	return values
end


local years = { ['лет'] = true, ['год'] = true, ['года'] = true, ['годам'] = true, ['году'] = true, }
local prepositions = { ['на'] = 1, ['к'] = 2, }

local function parseVerdict( str, preposition )
	str = deabbr( str, abbrVerdict )
	local x = string.sub( str, 1, 1 )
	local y, m, e
	if tonumber( x ) then
		local a, b, c, d

		a, d, c, e = string.match( str, '^(%d+) ([^ ]+) (%d+) месяц[^ ]*( .+)$' )
		if a then
			b = ':'
		else
			a, b, c, d, e = string.match( str, '^(%d+)([%.,:]?)(%d*) ([^ ]+)( .+)$' )
		end
		if a and years[d] then
			if b == '' then
				y = a
			elseif b == '.' or b == ',' then
				y = a
				if c ~= '5' then
					return nil, 'дробная часть в числе лет срока может быть только 0.5'
				end
				m = 6
			elseif b == ':' then
				y = a
				m = tonumber( c )
			end
		else
			return nil, 'не удалось разобрать срок'
		end
	elseif x == '?' then
		local a
		a, e = string.match( str, '^%? ([^ ]+)( .+)' )
		if not a or not years[a] then
			return nil, 'не удалось разобрать срок'
		else
			y = '?'
		end
	else
		return str, ( string.match( str, '^ВМН' ) ~= nil )
	end
	local form = prepositions[preposition or 'на']
	local word
	if y == '?' then
		x = 10
	else
		x = tonumber( y )
	end
	word = ' ' .. ruLang:convertPlural( x, ( { { 'год', 'года', 'лет' }, { 'году', 'годам', 'годам' } } )[form] )
	if m then
		m = ' ' .. m .. ' ' .. ruLang:convertPlural( tonumber( m ), ( { { 'месяц', 'месяца', 'месяцев' }, { 'месяцу', 'месяцам', 'месяцам' } } )[form] )
	end
	return y .. word .. ( m or '' ) .. e, true
end




local mainWords = {
	['отдел'] = 'отделом',
	['отделение'] = 'отделением',
	['управление'] = 'управлением',
	['президиум'] = 'президиумом',
	['председатель'] = 'председателем',
	['совет'] = 'советом',
	['пленум'] = 'пленумом',
	['трибунал'] = 'трибуналом',
	['прокуратура'] = 'прокуратурой',
	['прокурор'] = 'прокурором',
	['двойка'] = 'двойкой',
	['тройка'] = 'тройкой',
	['в'] = 'в', -- в особом порядке, в Норильлаге...
	['комиссия'] = 'комиссией',
	['коллегия'] = 'коллегией',
	['спецколлегия'] = 'спецколлегией',
	['совещание'] = 'совещанием',
	['присутствие'] = 'присутствием',
	['сессия'] = 'сессией',
	['инспекция'] = 'инспекцией',
	['часть'] = 'частью',
	['суд'] = 'судом',
	['облсуд'] = 'облсудом',
	['лагсуд'] = 'лагсудом',
	['приказ'] = 'приказом',
	['решение'] = 'решением',
	['постановление'] = 'постановлением',
	['определение'] = 'определением',
	['распоряжение'] = 'распоряжением',
	['указ'] = 'указом',
	['УНКВД'] = 'УНКВД',
	['ГУГБ'] = 'ГУГБ',
	['НИИ'] = 'НИИ',
}
local adjWords = {
	['ий'] = 'им', -- вроде двух букв достаточно — нет! «городскОЙ/областнОЙ» — «городскИМ/областнЫМ»
	['ой'] = 'им',
	['ый'] = 'ым',
	['ая'] = 'ой',
--	['ый'] = 'ым',
	['ое'] = 'ым',
	['-й'] = '-м',
--	['ное'] = 'ным',
}

local function tvori( str )
	local arr = mw.text.split( str, '%s+' )
	local wasMain
	for i, word in ipairs( arr ) do
		if mainWords[word] then
			arr[i] = mainWords[word]
			wasMain = true
			break
		elseif mainWords[mw.ustring.lower( word )] then
			local x = mainWords[mw.ustring.lower( word )]
			arr[i] = ruLang:ucfirst( x )
			wasMain = true
			break
		elseif tonumber( word ) then
			arr[i] = word
		else
			local x = mw.ustring.sub( word, -2, -1 )
			if adjWords[x] then
				arr[i] = mw.ustring.sub( word, 1, -3 ) .. adjWords[x]
			else
				arr[i] = '<span class=error>' .. arr[i] .. '[[Категория:Ошибка склонения]]</span>'
			end
		end
	end
	if not wasMain then
		return '<span class=error>' .. str .. '[[Категория:Ошибка склонения]]</span>'
	end
	return table.concat( arr, ' ' )
end

--[==[
repression table
	init { date ={ val, ext, ref, src }, auth={ val, ext, ref, src }, noArrest = bool} ,
	indictment = { val, ext, ref, src },
	process = { { date = { val, ext, ref, src } , auth={ val, ext, ref, src },  decision = { val, ext, ref, src } }.... }
	where = { val, ext, ref, src },
	after = { val, ext, ref, src },
	freedate = { val, ext, ref, src }
	striking = { date ={ val, ext, ref, src }, auth={ val, ext, ref, src } }


--]==]


repression[''] = function ( frame )
	local args, argErr = tools.checkargs( frame:getParent().args, {
			['арест'] = true, ['возбуждение'] = true,
			['должность'] = true,
			['обвинение'] = true,
			['рассмотрение'] = true,
			['отбывал'] = true,
			['освобожден'] = true,
			['после'] = true,
			['снятие'] = true,
			['дело'] = true,
		} )
    if not args then
		return tools.errorMsg( 'репрессия', 'Неизвестный параметр «' .. argErr .. '»' )
    end

	local repr = {}

	local errorDateAdvice = 'Используйте формат даты '
		.. '«<var>ЧЧ</var>.<var>ММ</var>.<var>ГГГГ</var>» или '
		.. '«<var>ММ</var>.<var>ГГГГ</var>» или «<var>ГГГГ</var>»'


	if args['арест'] and args['возбуждение'] then
		return tools.errorMsg( 'репрессия', 'Нельзя одновременно использовать параметры «арест» и «возбуждение»' )
	end
	local initArg = args['арест'] or args['возбуждение']
	local aORd
	if args['арест'] then
		aORd = 'арест'
	else
		aORd = 'возбуждение'
	end
	if initArg then
		local para, paraErr = parseSubargs( initArg, { 'дата', 'орган' }, { ['дата'] = 'date', ['орган']='auth' } )

		if not para then
			return tools.errorMsg( 'репрессия', 'В параметре «' .. aORd .. '» '  .. paraErr  )
		end

		if para.date then
			if para.date.val == 'да' then
				para.date.val = ''
			else
				local x = para.date.val
				para.date.val = tools.parseDate( para.date.val )
				if not para.date.val then
					return tools.errorMsg( 'репрессия', 'Параметр «' .. aORd .. '» содержит некорректную дату «' .. x .. '»', errorDateAdvice )
				end
			end
		end
		if para.auth then
			para.auth.val = deabbr( para.auth.val, abbrAuth )
		end

		repr.start = para
		repr.start.withoutArrest = aORd == 'возбуждение'
	end

	local position = args['должность']
	if position then
		local para, paraErr =  parseSubargs( position, { 'должность' }, { ['должность'] = 'position' } )
		if not para then
			return tools.errorMsg( 'репрессия', 'Параметр «должность» ' .. paraErr )
		end
		para.position.val = deabbr( para.position.val, {} )
		repr.position = para.position
	end

	local indictment = args['обвинение']
	if indictment then
		local para, paraErr =  parseSubargs( indictment, { 'обвинение' }, { ['обвинение'] = 'indictment' } )
		if not para then
			return tools.errorMsg( 'репрессия', 'Параметр «обвинение» ' .. paraErr )
		end
		para.indictment.val = deabbr( para.indictment.val, {} )
		repr.indictment = para.indictment
	end

	local process = args['рассмотрение']
	if process then
		if string.sub( process, 1, 1 ) == '*' then
			process = mw.text.trim( string.sub( process, 2, -1 ) )
		end
		local stages = mw.text.split( process, '%s*\n%s*%*%s*' )
		local stagesBase = {}
		for _, stage in ipairs( stages ) do
			if stage ~= '' then
				local para, paraErr = parseSubargs( stage, { 'дата', 'орган', 'решение' }, { ['дата'] = 'date',  ['орган'] = 'auth', ['решение'] = 'verdict' } )
				if not para then
					return tools.errorMsg( 'репрессия', 'В параметре «рассмотрение» '  .. paraErr  )
				end

				if para.date then
					local x = para.date.val
					para.date.val = tools.parseDate( para.date.val )
					if not para.date.val then
						return tools.errorMsg( 'репрессия', 'Параметр «рассмотрение» содержит некорректную дату «' .. x .. '»', errorDateAdvice )
					end
				end
				if para.auth then
					para.auth.val = deabbr( para.auth.val, abbrAuth )
				end
				if para.verdict then
					local verdi, err = parseVerdict( para.verdict.val )
					if not verdi then
						return tools.errorMsg( 'репрессия', 'Параметр «рассмотрение» содержит некорректный приговор «' .. para.verdict.val .. '»: ' .. err )
					end
					para.verdict.val = verdi
				end
				if not para.auth and not para.verdict then
					if para.date then
						return tools.errorMsg( 'репрессия', 'Параметр «рассмотрение» для одной из инстанций содержит только дату' )
					end
				else
					table.insert( stagesBase, para )
				end
			end
		end
		repr.stages = stagesBase
	end

	local where = args['отбывал']
	if where then
		local para, paraErr =  parseSubargs( where, { 'отбывал' }, { ['отбывал'] = 'where' } )
		if not para then
			return tools.errorMsg( 'репрессия', 'Параметр «отбывал» ' .. paraErr )
		end
		para.where.val = deabbr( para.where.val, {} )
		repr.where = para.where
	end

	local released = args['освобожден']
	if released then
		local para, paraErr =  parseSubargs( released, { 'освобожден' }, { ['освобожден'] = 'released' } )
		if not para then
			return tools.errorMsg( 'репрессия', 'Параметр «освобожден» ' .. paraErr )
		end
		para.released.val = tools.parseDate( para.released.val )
		if not para.released.val then
			return tools.errorMsg( 'репрессия', 'Параметр «освобожден» содержит некорректную дату', errorDateAdvice )
		end
		repr.released = para.released
	end

	local after = args['после']
	if after then
		local para, paraErr =  parseSubargs( after, { 'после' }, { ['после'] = 'after' } )
		if not para then
			return tools.errorMsg( 'репрессия', 'Параметр «после» ' .. paraErr )
		end
		para.after.val = deabbr( para.after.val, {} )
		repr.after = para.after
	end

	local striking = args['снятие']
	if striking then
		local para, paraErr = parseSubargs( striking, { 'дата', 'орган' }, { ['дата'] = 'date', ['орган']='auth' } )

		if not para then
			return tools.errorMsg( 'репрессия', 'В параметре «снятие» '  .. paraErr  )
		end

		if para.date then
			para.date.val = tools.parseDate( para.date.val )
			if not para.date.val then
				return tools.errorMsg( 'репрессия', 'Параметр «снятие» содержит некорректную дату', errorDateAdvice )
			end
		end
		if para.auth then
			para.auth.val = deabbr( para.auth.val, abbrAuthStriking )
		end
		if para.date or para.auth then
			repr.striking = para
		end
	end

	local archive = args['дело']
	if archive then
		local para, paraErr =  parseSubargs( archive, { 'дело' }, { ['дело'] = 'archive' } )
		if not para then
			return tools.errorMsg( 'репрессия', 'Параметр «дело» ' .. paraErr )
		end
		para.archive.val = deabbr( para.archive.val, {} )
		repr.archive = para.archive
	end

	global.add( 'repression!', repr )
	return '<i></i>'
end

function repression.Dump( frame )
	return repression.reprText( global.get( 'repression!' ), global.get( 'reabilitation!' ), false  )
end

function repression.reprText( descrArray, reab, isFem, archInfo )
	local out = {}
	local lastInline
	local phraseStart
	local function ins( text, footer )
		table.insert( out, text )
		if not footer then
			if not lastInline then
				phraseStart = #out
			end
			lastInline = #out
		end
	end
	local function attr( dsc )
		if dsc.ext then
			local x = string.sub( dsc.ext, 1, 1 )
			if x == ',' or x == ';' or x == ':' then
				x = ''
			else
				x = ' '
			end
			ins( x .. dsc.ext )
		end
		if dsc.ref then
			ins( require( 'Module:RefTools' ).makeRef( dsc.ref ), true )
		end
		if dsc.src then
			ins( require( 'Module:RefTools' ).makeRef( tools.formatIfUrl( 'what', dsc.src ), true ), true )
		end
	end
	local function txtDate( str )
		local p = tools.reparseDate( str )
		if #p ~= 10 then
--			p = 'в <b>' .. p .. '</b>'
			p = 'в ' .. p
--		else
--			p = '<b>' .. p .. '</b>'
		end
		return p
	end

	local function period()
		if phraseStart then
			local word, i = out[phraseStart], 1
			if string.sub( word, 1, 1 ) == ' ' then
				i = 2
			end
			out[phraseStart] = ruLang:ucfirst( string.sub( word, i ) )
		end
		if lastInline then
			local x = string.sub( out[lastInline], -1, -1 )
			if  x == '.' or x == '!' or x == '?' then
				x = ' &nbsp; '
			else
				x = '. &nbsp; '
			end
			ins( x )
			lastInline = nil
		end
	end



	local gender_0_a, gender_sya_as
	if isFem then
		gender_0_a = 'а'
		gender_sya_as = 'ась'
	else
		gender_0_a = ''
		gender_sya_as = 'ся'
	end
	local reprNum = 1 -- попытка отказаться от слов «следующее дело» и т. п. Пока все сохранил, но блокирую выставление репрессии № 2
	for reprN, dsc in ipairs( descrArray ) do
		if #descrArray ~= 1 then
			ins( '<br><b>(' .. reprN .. ')&nbsp;&nbsp;</b>', true )
		end
		if dsc.start then
			if dsc.start.withoutArrest then
				ins( ( { 'Дело возбуждено', 'Следующее дело возбуждено' } )[reprNum] )
			else
				ins( ( { 'Арестован', 'По следующему делу арестован' } )[reprNum] .. gender_0_a )
			end
			reprNum = 1
			if dsc.start.date then
				if dsc.start.date.val ~= '' then
					ins( ' ' .. txtDate( dsc.start.date.val ) )
				end
				attr( dsc.start.date )
			end
			if dsc.start.auth then
				ins( ' ' .. tvori( dsc.start.auth.val ) )
				attr( dsc.start.auth )
			end
			period()
		end

		if dsc.position then
			if not dsc.start or dsc.start.withoutArrest then
				ins( ( { 'До возбуждения дела', 'На момент возбуждения следующего дела' } )[reprNum] )
			else
				ins( ( { 'До ареста', 'На момент ареста по следующему делу' } )[reprNum] )
			end
			reprNum = 1
			ins( ' — ' .. dsc.position.val )
			attr( dsc.position )
			period()
		end

		if dsc.indictment then
			ins( ( { 'Обвинение', 'Обвинение по следующему делу' } )[reprNum] )
			reprNum = 1
			ins( ' — ' .. dsc.indictment.val )
			attr( dsc.indictment )
			period()
		end

		local stageNum = 1
		for _, stage in ipairs( dsc.stages or {} ) do
			if reprNum ~= 1 then
				ins( 'По следующему делу' )
				reprNum = 1
			end
--			if stage.date then
--				ins( ' ' .. txtDate( stage.date.val ) )
--				attr( stage.date )
--			end
			local auth
			if stage.auth then
				auth = tvori( stage.auth.val )
			end
			local verdict, verdictForm
			if stage.verdict then
				if stageNum == 1 then
					verdict, verdictForm = parseVerdict( stage.verdict.val, 'к' )
--					if verdictForm then
--						stageNum = 2
--					end
				else
					verdict, verdictForm = parseVerdict( stage.verdict.val, 'на' )
				end
			end
			if auth and verdict then
				ins( ' ' .. auth )
				attr( stage.auth )
			end
			if stage.date then
				ins( ' ' .. txtDate( stage.date.val ) )
				attr( stage.date )
			end
			if verdict then
				if verdictForm then
					if stageNum == 1  then
						ins( ' приговорен' .. gender_0_a .. ' к' )
					else
						ins( ' приговор изменен на' )
					end
					stageNum = 2
				end
				ins( ' ' .. verdict )
				attr( stage.verdict )
			else
				ins( ' дело рассматривалось ' .. auth )
				attr( stage.auth )
			end
			period()
		end


--[[
			reprNum	date	auth	stage	verdict	Phrase
			1		V		V		1		10		+25.01.1941 |судом| приговорен к 10 годам
			1		V		V		1		текст	+25.01.1941 |судом| дело прекращено, освобожден
			1		V		V		1		-		25.01.1941 дело рассматривалось |судом|
			1		V		V		2...	10		+25.01.1941 |судом| приговор изменен на 10 лет
			1		V		V		2...	текст	+25.01.1941 |судом| дело прекращено, освобожден
			1		V		V		2...	-		25.01.1941 дело рассматривалось |судом|
			1		V		-		1		10		+25.01.1941 приговорен к 10 годам
			1		V		-		1		текст	+25.01.1941 дело прекращено, освобожден
			1		V		-		1		-		25.01.1941 дело рассматривалось ERR
			1		V		-		2...	10		+25.01.1941 приговор изменен на 10 лет
			1		V		-		2...	текст	+25.01.1941 дело прекращено, освобожден
			1		V		-		2...	-		25.01.1941 дело рассматривалось ERR

			2		V		V		1		10		25.01.1941 приговорен |судом| к 10 годам
			2		V		V		1		текст	25.01.1941 |судом| дело прекращено, освобожден
			2		V		V		1		-		25.01.1941 дело рассматривалось |судом|
			2		V		V		2...	10		25.01.1941 |судом| приговор изменен на 10 лет
			2		V		V		2...	текст	25.01.1941 |судом| дело прекращено, освобожден
			2		V		V		2...	-		25.01.1941 дело рассматривалось |судом|
			2		V		-		1		10		25.01.1941 приговорен к 10 годам
			2		V		-		1		текст	25.01.1941 дело прекращено, освобожден
			2		V		-		1		-		25.01.1941 дело рассматривалось
			2		V		-		2...	10		25.01.1941 приговор изменен на 10 лет
			2		V		-		2...	текст	25.01.1941 дело прекращено, освобожден
			2		V		-		2...	-		25.01.1941 дело рассматривалось


--]]
		if dsc.where then
			ins( 'Наказание отбывал' .. gender_0_a .. ' ' .. dsc.where.val )
			attr( dsc.where )
			period()
		end

		if dsc.released then
--			ins( 'Освободил' .. gender_sya_as .. ' ' .. txtDate( dsc.released.val ) )
			ins( 'Освобожден' .. gender_0_a .. ' ' .. txtDate( dsc.released.val ) )
			attr( dsc.released )
			period()
		end

		if dsc.after then
			ins( dsc.after.val )
			attr( dsc.after )
			period()
		end

		if dsc.striking then
			ins( 'Судимость снята' )
			if dsc.striking.date then
				ins( ' ' .. txtDate( dsc.striking.date.val ) )
				attr( dsc.striking.date )
			end
			if dsc.striking.auth then
				ins( ' ' .. tvori( dsc.striking.auth.val ) )
				attr( dsc.striking.auth )
			end
			period()
		end

			-- archInfo (= data4person.repr_arch) — делалось под номера дел от Кокурина, но в работу так и не пошло, можно убить
		if dsc.archive and archInfo then
			ins( '[[Категория:Двойное дело]]' )
		end
		dsc.archive = dsc.archive or archInfo
		if dsc.archive then
			ins( '[<i></i>' .. ruLang:ucfirst( dsc.archive.val )  )
			attr( dsc.archive )
			ins( ']' )
			period()
		end
--		reprNum = 2
	end


	if reab then
		if #descrArray ~= 1 then
			ins( '<br>', true )
		end
		if reab.state == 1 then
			ins( 'Реабилитирован' .. gender_0_a .. ' ' )
		end
		local auth = reab.auth
		if auth then
			ins( tvori( auth ) )
		end
		local date = reab.date
		if date then
			ins( ' ' .. txtDate( date ) )
		end
		if reab.state == -1 then
			ins( ' в реабилитации отказано' )
		end
		attr( reab )
		period()
	end
	global.set( 'repression!' )
	global.set( 'reabilitation!' )

	return table.concat( out )
end

function  repression.Reabilitation( frame )
	local args, argErr = tools.checkargs( frame:getParent().args, {
			'да', ['дата'] = true,
			['орган'] = true,
            ['дополнение'] = true, ['сноска'] = true, ['источник'] = true
		} )
    if not args then
		return tools.errorMsg( 'реабилитация', 'Неизвестный параметр «' .. argErr .. '»' )
    end

	if global.get( 'reabilitation!' ) then
		return tools.errorMsg( 'реабилитация', 'Шаблон может использоваться только один раз' )
    end

	local reab = {}

	local x = args[1]
	if x == 'да' then
		reab.state = 1
	elseif x == 'нет' then
		reab.state = -1
--	elseif x == 'неизвестно' then
--		reab.state = 0
	else
		return  tools.errorMsg( 'реабилитация',
			'Первый параметр должен быть «да» или «нет»' )
	end

	x = args['дата']
	if x then
		reab.date = tools.parseDate( x )
		if not reab.date then
			return  tools.errorMsg( 'реабилитация', 'Ошибка в дате реабилитации' )
		end
	end

	reab.auth = args['орган']
	if reab.auth then
		reab.auth = deabbr( reab.auth, abbrAuth )
	end

	x = args['дополнение']
	if x then
		reab.ext = deabbr( x, {} )
	end
	reab.ref = args['сноска']
	reab.src = args['источник']
	global.set( 'reabilitation!', reab )
end


return repression