#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

template <class T>
class Matrica
{
public:
	Matrica()
		{}
		
	Matrica( unsigned s, unsigned v )
		: _Podaci(s)
		{
		for( unsigned i=0; i<s; i++ )
			_Podaci[i].resize(v);
		}
		
	const vector<T>& operator[] ( unsigned i ) const
		{ return _Podaci[i]; }
		
	vector<T>& operator[] ( unsigned i )
		{ return _Podaci[i]; }
		
	unsigned Sirina() const
		{ return _Podaci.size(); }
		
	unsigned Visina() const
		{ return _Podaci.size() ? _Podaci[0].size() : 0; }
		
private:
	vector< vector<T> > _Podaci;
};

class IgraLife
{
public:
	IgraLife()
		{}
		
	int BrojSuseda( int x, int y )
		{
		int bs = 0;
		int sirina = _Tabla.Sirina();
		int visina = _Tabla.Visina();
		for( int i=-1; i<=1; i++ )
			for( int j=-1; j<=1; j++ )
				if( i || j ){
					int xx = (x+i+sirina) % sirina;
					int yy = (y+j+visina) % visina;
					if( _Tabla[xx][yy] )
						bs++;
				}
		return bs;
		}

	void Iteracija()
		{
		int sirina = _Tabla.Sirina();
		int visina = _Tabla.Visina();
		Matrica<bool> novaTabla( sirina, visina );
		for( int i=0; i<sirina; i++ )
			for( int j=0; j<visina; j++ ){
				int bs = BrojSuseda( i, j );
				novaTabla[i][j] = 
					_Tabla[i][j] ? (bs>=2 && bs<=3) : (bs==3);
			}
		_Tabla = novaTabla;
		}
		
	void Ucitaj( istream& istr )
		{
		int sirina, visina;
		istr >> sirina >> visina;
		// Matrica<bool> a( sirina, visina );
		// _Tabla = a;
		_Tabla = Matrica<bool>( sirina, visina );
		for( int i=0; i<visina; i++ )
			for( int j=0; j<sirina; j++ ){
				char c;
				istr >> c;
				_Tabla[j][i] = (c=='x');
			}
		}
		
	void Zapisi( ostream& ostr ) const
		{
		int sirina = _Tabla.Sirina();
		int visina = _Tabla.Visina();
				
		ostr << sirina << ' ' << visina << endl;
		for( int i=0; i<visina; i++ ){
			for( int j=0; j<sirina; j++ )
				ostr << (_Tabla[j][i] ? 'x' : '.');
			ostr << endl;
			}
		}
	
private:
	Matrica<bool> _Tabla;
};


istream& operator >> ( istream& istr, IgraLife& igra )
{
	igra.Ucitaj( istr );
	return istr;
}

ostream& operator << ( ostream& ostr, const IgraLife& igra )
{
	igra.Zapisi( ostr );
	return ostr;
}


main()
{
	IgraLife igra;
	ifstream f( "life.dat");
	f >> igra;
	cout << igra;
	while(1){
		char c = cin.get();
		if( c=='k')
			break;
		igra.Iteracija();
		cout << igra;
	}
	return 0;	
}

