//
// C++ Implementation: rename
//
// Description: 
//
//
// Author: Spiros Georgaras <sng@hellug.gr>, (C) 2009
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include "filesdata.h"
#include "dirsdata.h"
#include "rename.h"
#include "iconload.h"
#include "exif.h"
#include "main.h"
// #include "settings.h"
#include <khelpmenu.h>
#include <kpushbutton.h>
#include <kmenu.h>
#include <kglobal.h>
#include  <kled.h>
#include <kicon.h>

#include <klocale.h>
#include <QtGui/QDialog>
#include <qlabel.h>
#include <QMouseEvent>
#include <QRect>
#include <QDesktopWidget>
#include <QCloseEvent>

#include <QList>
#include <QTreeWidget>
#include <QTreeWidgetItem>

#include  <QtDebug>



#define SHOW_ITEMS_TO_LIST_PROBLEM 5

struct config_data{
	QString group;
	QString Name;
	int prof;
	bool changed;
	bool deleted;
	bool renaming;
	//Name
	QString specName;
	int origModif;
	bool useOrigName;
	bool useNumeric;
	bool convSpaceToUnder;
	bool convSpaceToDash;
	bool convDashToSpace;
	bool convUnderToSpace;
	bool counterActive;
	//Counter
	int digits;
	int start;
	int step;
	bool sameNum;
	bool allow;
	bool shuffle;
	//Extension
	QString newExt;
	int extModif;
	bool useOrigExt;
	bool useCompoundExt;
	//Misc
	bool showAll;
	QString prefix;
	QString suffix;
	

};
struct all_data{
	//General
	bool useProf;
	int defProf;
	bool autoSave;
	bool prName;
	int numOfProfiles;
	int items;
	config_data *data;
	QString oldName;
	QString enteredName;
	int active;
	bool inRename;
};


// KPopupMenu* popM;
int historyIndex;
QString history[HISTORY_ITEMS * HISTORY_CONTROLS];
QString tFormatBefore;
QString tFormatDate;
QString tFormatAfter;




struct all_data pr;
extern filesData f;
extern dirsData g;
extern bool InitiatedRename;
extern QString tFormatBefore;
extern QString tFormatDate;
extern QString tFormatAfter;
extern bool noProfiles;
extern KAboutData * ab;
// namePart * nPB;


QString profName;
iconload ic;
int col0;
// KPopupMenu* popM;

//================================
// GwenRename::GwenRename(QDialog* )
GwenRename::GwenRename(QWidget* )
	:QWidget()
{
	ts=0;
	inMode=0;
	hiddenWidgetSets=0;
	firstSelectedItem=0L;
	smallScreen=false;
	setupUi(this);
/*	
	// Setup help menu	
	mHelpMenu = new KHelpMenu( buttonAbout, ab, false);
// 	mHelpMenu = new KHelpMenu(this, KGlobal::mainComponent().about(), false);
	buttonAbout->setMenu(mHelpMenu->menu());*/
	rDigits->setMinimum(1);
}


// GwenRename:: GwenRename(QDialog * , KAboutData* about){
GwenRename:: GwenRename(QWidget * , KAboutData* about)
	:QWidget()
{
	QDesktopWidget thisDesktop;
	QRect desktopResolution=thisDesktop.availableGeometry();

	ts=0;
	mS=0;
	inMode=0;
	hiddenWidgetSets=0;
	firstSelectedItem=0L;
	smallScreen=false;
	ab=about;
	setupUi(this);
	
	
	
// 	resize(100,100);
	////////////////////////////////////////////////
	//       Fix geometry and possition
	////////////////////////////////////////////////
	if(desktopResolution.height()<=800){
		resize(width(),718);
		smallScreen=true;
	}
	if(desktopResolution.height()>height())
		// center main window
		move((int)(desktopResolution.width()-width())/2,(int)(desktopResolution.height()-height())/2);
	else
		// center horizontally only
		move((int)(desktopResolution.width()-width())/2,y());
	
// 	firstSelectedItem=0L; FIX ME!!! Does it exist?
	tMult=0;
	filesSelectedType=-2;
	cmbExt->setDuplicatesEnabled(FALSE);
	activeExtension=0;
	
// 	// Setup help menu	
// 	mHelpMenu = new KHelpMenu( buttonAbout, about, false);
// // 	mHelpMenu = new KHelpMenu(this, KGlobal::mainComponent().about(), false);
// 	buttonAbout->setMenu(mHelpMenu->menu());
	
	lblLed1->hide();
	lblLed1->setText("<nobr>"+i18n("Show <b>Name / Prefix - Suffix</b> widgets")+"</nobr>");
	lblLed2->hide();
	lblLed2->setText("<nobr>"+i18n("Show <b>Miscellaneous / Counter</b> widgets")+"</nobr>");
	lblLed3->hide();
	lblLed3->setText("<nobr>"+i18n("Show <b>Extension / Profiles</b> widgets")+"</nobr>");
	
	loadIcons();
			
// setIcon(ic.Icon(9));

// rName->setSizeLimit(HISTORY_ITEMS+1); old impl
// nPref->setSizeLimit(HISTORY_ITEMS+1); old impl
// nSuf->setSizeLimit(HISTORY_ITEMS+1); old impl
// rExt->setSizeLimit(HISTORY_ITEMS+1); old impl
rName->setMaxVisibleItems(HISTORY_ITEMS+1);
nPref->setMaxVisibleItems(HISTORY_ITEMS+1);
nSuf->setMaxVisibleItems(HISTORY_ITEMS+1);
rExt->setMaxVisibleItems(HISTORY_ITEMS+1);
prDefault->setIcon(KIcon(ic.Icon(0)));
sTime->setIcon(KIcon(ic.Icon(2)));
pTime->setIcon(KIcon(ic.Icon(2)));
prLoad->setIcon(KIcon(ic.Icon(3)));
prNew->setIcon(KIcon(ic.Icon(4)));
prEdit->setIcon(KIcon(ic.Icon(5)));
prSave->setIcon(KIcon(ic.Icon(6)));
prDelete->setIcon(KIcon(ic.Icon(7)));
reRandomize->setIcon(KIcon(ic.Icon(8)));
partName->setIcon(KIcon(ic.Icon(10)));
pPartName->setIcon(KIcon(ic.Icon(10)));
sPartName->setIcon(KIcon(ic.Icon(10)));
btNewExt->setIcon(KIcon(ic.Icon(4)));
btSaveExt->setIcon(KIcon(ic.Icon(6)));
btDelExt->setIcon(KIcon(ic.Icon(7)));
buttonOk->setIcon(KIcon(ic.Icon(6)));
buttonCancel->setIcon(KIcon(ic.Icon(7)));
buttonAbout->setIcon(KIcon(ic.Icon(15)));

//Icon sets
// clearSuffix->setIcon(KIcon(ic.Icon(11)));
// clearPrefix->setIcon(KIcon(ic.Icon(11)));
// clearrName->setIcon(KIcon(ic.Icon(11)));
// clearNewExtension->setIcon(KIcon(ic.Icon(11)));


// FIX ME!!!
	
	QStringList hed;
	hed << "";
	hed<<i18n("Original name");
	hed<<i18n("New name");
	View->setHeaderLabels(hed);
	View->setColumnWidth ( 0, 24 );
	View->setColumnWidth ( 1, 300 );
	View->sortByColumn(1,Qt::AscendingOrder);
 View->setAlternatingRowColors(true);
	
	
	
// 	View->clear();
//  QList<QTreeWidgetItem *> items;
//  QStringList l;
// 	for (int i = 0; i < 30; ++i){
// 		hed.clear();
// 		hed<<QString("");
// 		hed<<QString("item: %1").arg(i);
// 		hed<<QString("item: %1-%2").arg(i).arg(i);
// 		items.append(new QTreeWidgetItem((QTreeWidget*)0, hed));
// 	}
// 	View->insertTopLevelItems(0, items);
// 	
// 	items[6]->setIcon(0,KIcon(ic.Icon(0)));
// 	items[3]->setIcon(0,KIcon(ic.Icon(1)));
// 	View->resizeColumnToContents(1);

// 	
// 	
// 	
// 	
//	View->addColumn( "",35);
// 	View->header()->setResizeEnabled( FALSE, View->header()->count() - 1 );
// 	View->addColumn( i18n( "Original name" ),300 );
// 	View->addColumn( i18n( "New name" ) );
// 	View->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)7, (QSizePolicy::SizeType)7, 0, 255, View->sizePolicy().hasHeightForWidth() ) );
// 	View->setMinimumSize( QSize( 0, 50 ) );
// 	View->setFocusPolicy( KListView::NoFocus );
// 	View->setResizeMode( KListView::LastColumn );
// 
// 
// 
// 
// // // 	col0=View->columnWidth(0);
// // // 	fixViewGeometry(0 );
// // // 	connect( View->header(), SIGNAL( clicked(int) ), this, SLOT( headerClicked(int) ) );
// // // 	QColor back=KGlobalSettings::alternateBackgroundColor();
// // // 	if(!back.isValid()) back=KGlobalSettings::calculateAlternateBackgroundColor(View->paletteBackgroundColor());
// // // 	View->setAlternateBackground(back);
	
	profName=i18n("New profile");
// 	setCaption("GwenRename"); old impl
	setWindowTitle("GwenRename");
	cmbProfile->setDuplicatesEnabled(FALSE);
	cmbProfile->insertItem( 0, "GwenRename" );
	pr.oldName=QString::null;
	
	readConfig();

	lSelected->setText(QString(i18n("%1/%2 items selected")).arg(f.items(),0,10).arg(g.numOfFiles,0,10));
	if(f.Type==2){
		rShuffle->setEnabled(TRUE);
	}else{
		rShuffle->setEnabled(FALSE);
		reRandomize->setEnabled(FALSE);
	}
// // // 	KListViewItem * item = new KListViewItem( View, 0 );
// // // 	for(int i=0;i<f.items();i++){
// // // 		if(i!=0)  item = new KListViewItem( View, item );
// // // 		item->setText( 0, f.files[i].fileName());
// // // 	}
	if(f.Type==2){
		if(rShuffle->isChecked()) reRandomize->setEnabled(TRUE);
		rSelExt->setEnabled(FALSE);
		rLExt->setEnabled(FALSE);
		rUExt->setEnabled(FALSE);
		extBox->setEnabled(FALSE);
	}
	rName->setFocus();
	updateNameView();
	updateExtView();
	InitiatedRename=TRUE;
	if(g.numOfFiles==g.numOfSlectedItems()){
		rShow->setChecked(TRUE);
		rShow->setEnabled(FALSE);
		rAllow->setEnabled(FALSE);
	}
	if(g.numOfSlectedItems()==1){
// 		rStep->setMaxValue( 1 ); old impl
		rStep->setMaximum( 1 );
// 		rStep->setMinValue( 0 ); old impl
		rStep->setMinimum( 0 );
		rWidth->setEnabled(FALSE);
		rAllow->setEnabled(FALSE);
		rShuffle->setEnabled(FALSE);
		reRandomize->setEnabled(FALSE);
		sort->setEnabled(FALSE);
	}
	updateViewEnabled=true;
	updateView();
	for(int k=0;k<g.numOfFiles;k++)
		if(g.ren[k].selected){
			filesSelectedType=g.whatType(k);
			break;
		}
// // // 	nPB=new namePart(&ic);
  AdjustExtension();

	if(smallScreen)
		// Turn off led2
		handleLed2();


// connect(buttonOk, SIGNAL( clicked() ), this, SLOT( buttonOkClicked() ) );


// Connections to View (deleted from ui)
//        QObject::connect(View, SIGNAL(doubleClicked(QListViewItem*)), GwenRename, SLOT(viewDoubleClicked(QListViewItem*)));
//         QObject::connect(View, SIGNAL(mouseButtonPressed(int,QListViewItem*,const QPoint&,int)), GwenRename, SLOT(ViewMouseButtonPressed(int,QListViewItem*,const QPoint&,int)));



	rDigits->setMinimum(1);
}



//================================
void GwenRename::readConfig(){
	readHistory();
	if(noProfiles){
		btngrpProfiles->setEnabled(FALSE);
		return;
	}
	KConfig config("gwenrenamerc");
// 	config.setGroup("General"); old impl
	KConfigGroup grp=config.group("General");
	pr.useProf=grp.readEntry("use profiles",FALSE);
	pr.defProf=grp.readEntry("default profile",0);
	pr.numOfProfiles=1;
	readProfiles(&config);
  //init Profile0
	pr.data[0].changed=FALSE;
	pr.data[0].deleted=FALSE;
// 	pr.data[0].prof=0; pr.data[0].Name=cmbProfile->text(0); old impl
	pr.data[0].prof=0; pr.data[0].Name=cmbProfile->itemText(0);
	pr.data[0].specName=""; pr.data[0].origModif=-1;
	pr.data[0].useOrigName=FALSE;
	pr.data[0].useNumeric=FALSE;
	pr.data[0].counterActive=TRUE;
	pr.data[0].digits=3; pr.data[0].start=1; pr.data[0].step=1;
	pr.data[0].sameNum=TRUE; pr.data[0].allow=FALSE;
	pr.data[0].shuffle=FALSE; pr.data[0].newExt="";
	pr.data[0].extModif=-1;  pr.data[0].useOrigExt=TRUE;
	pr.data[0].showAll=FALSE; pr.data[0].prefix=""; pr.data[0].suffix="";
	pr.data[0].convSpaceToUnder=FALSE; pr.data[0].convSpaceToDash=FALSE;
	pr.data[0].convUnderToSpace=FALSE; pr.data[0].convDashToSpace=FALSE;
	pr.data[0].useCompoundExt=FALSE;
	//
	pr.active=0;
	fill_cmbProfile();
	int i=getDefProfileIndex();
	if(pr.useProf) applyProfile(i);
// 	cmbProfile->setCurrentItem(i); old impl
	cmbProfile->setCurrentIndex(i);
	if(i!=0 && pr.useProf){
		prEdit->setEnabled(TRUE);
		prSave->setEnabled(TRUE);
		prDelete->setEnabled(TRUE);
	}
	chkProfile->setChecked(pr.useProf);
	prDefault->setEnabled(FALSE);
	prLoad->setEnabled(FALSE);
	// Known extensions
// 	config.setGroup("CompoundExtensions"); old impl
	grp=config.group("CompoundExtensions");
	QString tmp="1";
	QString group;
	i=0;
	while(!tmp.isEmpty()){
		group=QString("Ext%1").arg(i);
		tmp=grp.readEntry(group,"");
		if(tmp.isEmpty()) i-=2;
		else{
			if(historyItemExist(rExt,tmp)) continue;
			else cmbExt->insertItem(cmbExt->count(),tmp);
		}
		i++;
	}
	compoundExtensions=i+1;
	if(i==-1){
		cmbExt->insertItem(0,"tar.bz2");
		cmbExt->insertItem(0,"tar.gz");
		compoundExtensions=2;
	}
}
//================================
void GwenRename::writeConfig(){
	if(noProfiles) return;
	KConfig config("gwenrenamerc");
	clearDeletedProfiles( &config );
    // Name group
// 	config.setGroup("General"); old impl
	KConfigGroup grp=config.group("General");
	grp.writeEntry("use profiles",pr.useProf);
	grp.writeEntry("default profile",pr.defProf);
	int count=0;
	for(int i=1;i<pr.numOfProfiles;i++){
		if(!pr.data[i].deleted){
			count++;
			if(count!=pr.data[i].prof){
// 				config.deleteGroup(QString("Profile%1").arg(pr.data[i].prof),TRUE,FALSE); old impl
				grp.deleteGroup();
				if(pr.data[i].prof==pr.defProf) pr.defProf=count;
				pr.data[i].prof=count;
				pr.data[i].changed=TRUE;
			}
		}
	}
    //config.writeEntry("number of profiles",pr.numOfProfiles);
	for(int i=1;i<pr.numOfProfiles;i++){
		if(pr.data[i].changed && !pr.data[i].deleted){
			pr.data[i].changed=FALSE;
// 			config.setGroup(QString("Profile%1").arg(pr.data[i].prof)); old impl
			KConfigGroup grp=config.group(QString("Profile%1").arg(pr.data[i].prof));
			grp.writeEntry("profile name",pr.data[i].Name);
	    // name
			grp.writeEntry("specified name",pr.data[i].specName);
			grp.writeEntry("original modifier",pr.data[i].origModif);
			grp.writeEntry("use original name",pr.data[i].useOrigName);
			grp.writeEntry("use numeric sorting",pr.data[i].useNumeric);
			grp.writeEntry("use counter",pr.data[i].counterActive);
			grp.writeEntry("convert to underscore",pr.data[i].convSpaceToUnder);
			grp.writeEntry("convert to dash",pr.data[i].convSpaceToDash);
			grp.writeEntry("convert underscore to space",pr.data[i].convUnderToSpace);
			grp.writeEntry("convert dash to space",pr.data[i].convDashToSpace);
			
	    // counter
			grp.writeEntry("counter digits",pr.data[i].digits);
			grp.writeEntry("counter start",pr.data[i].start);
			grp.writeEntry("counter step",pr.data[i].step);
			grp.writeEntry("counter same number",pr.data[i].sameNum);
			grp.writeEntry("counter relaxed",pr.data[i].allow);
			grp.writeEntry("counter shuffle",pr.data[i].shuffle);
	    // extension
			grp.writeEntry("new extension",pr.data[i].newExt);
			grp.writeEntry("extension modifier",pr.data[i].extModif);
			grp.writeEntry("use original extension",pr.data[i].useOrigExt);
			grp.writeEntry("use compound extensions",pr.data[i].useCompoundExt);
	    //Misc
			grp.writeEntry("show all",pr.data[i].showAll);
			grp.writeEntry("prefix",pr.data[i].prefix);
			grp.writeEntry("suffix",pr.data[i].suffix);
		}
	}
	
	// Known extensions
	grp=config.group("CompoundExtensions");
	int i;
	for(i=0;i<cmbExt->count();i++)
// 		grp.writeEntry(QString("Ext%1").arg(i),cmbExt->text(i)); old impl
		grp.writeEntry(QString("Ext%1").arg(i),cmbExt->itemText(i));
	// delete extra extensions if any
	if(i<compoundExtensions){
		i--;
		for(int k=1;k+i<compoundExtensions;k++)
// 			config.deleteEntry(QString("Ext%1").arg(compoundExtensions-k)); old impl
			grp.deleteEntry(QString("Ext%1").arg(compoundExtensions-k));
	}
	config.sync();
}


/////////////////////////////////////////////////////////////
//
//
//	History
//
//
/////////////////////////////////////////////////////////////
//================================
void GwenRename::readHistory(){
	QString tmp;
	QString group;
	KConfig config("gwenrenamerc");
// 	config.setGroup("NameHistory"); old impl
	KConfigGroup grp=config.group("NameHistory");
	rName->clear();
	for(int i=0;i<HISTORY_ITEMS;i++){
		group=QString("Exp%1").arg(i);
		tmp=grp.readEntry(group,"");
		if(tmp.isEmpty()) break;
		else if(historyItemExist(rName,tmp)) continue;
		else rName->insertItem(rName->count(),tmp);
	}
// 	for(int i=0;i<rName->count();i++) history[i]=rName->text(i); old impl
	for(int i=0;i<rName->count();i++) history[i]=rName->itemText(i);
// 	rName->setCurrentText(""); old impl
	rName->setEditText("");
	grp=config.group("PrefixHistory");
	nPref->clear();
	for(int i=0;i<HISTORY_ITEMS;i++){
		group=QString("Exp%1").arg(i);
		tmp=grp.readEntry(group,"");
		if(tmp.isEmpty()) break;
		else if(historyItemExist(nPref,tmp)) continue;
// 		else nPref->insertItem(tmp); old impl
		else nPref->insertItem(nPref->count(),tmp);
	}
// 	for(int i=0;i<nPref->count();i++) history[P_H_INDEX+i]=nPref->text(i); old impl
	for(int i=0;i<nPref->count();i++) history[P_H_INDEX+i]=nPref->itemText(i);

// 	nPref->setCurrentText(""); old impl
	nPref->setEditText("");
	grp=config.group("SuffixHistory");
	nSuf->clear();
	for(int i=0;i<HISTORY_ITEMS;i++){
		group=QString("Exp%1").arg(i);
		tmp=grp.readEntry(group,"");
		if(tmp.isEmpty()) break;
		else if(historyItemExist(nSuf,tmp)) continue;
// 		else nSuf->insertItem(tmp); old impl
		else nSuf->insertItem(nSuf->count(),tmp);
	}
// 	for(int i=0;i<nSuf->count();i++) history[S_H_INDEX+i]=nSuf->text(i); old impl
	for(int i=0;i<nSuf->count();i++) history[S_H_INDEX+i]=nSuf->itemText(i);
// 	nSuf->setCurrentText(""); old impl
	nSuf->setEditText("");
	grp=config.group("ExtensionHistory");
	rExt->clear();
	for(int i=0;i<HISTORY_ITEMS;i++){
		group=QString("Exp%1").arg(i);
		tmp=grp.readEntry(group,"");
		if(tmp.isEmpty()) break;
		else if(historyItemExist(rExt,tmp)) continue;
// 		else rExt->insertItem(tmp); old impl
		else rExt->insertItem(rExt->count(),tmp);
	}
// 	for(int i=1;i<rExt->count();i++) history[E_H_INDEX+i]=rExt->text(i); old impl
	for(int i=1;i<rExt->count();i++) history[E_H_INDEX+i]=rExt->itemText(i);
// 	rExt->setCurrentText(""); old impl
	rExt->setEditText("");
}
//================================
void GwenRename::writeHistory(){
/*    rName->removeItem(0);
	nPref->removeItem(0);
	nSuf->removeItem(0);
	rExt->removeItem(0);*/
	QString cur;
	QString group;
	int index=0;
	KConfig config("gwenrenamerc");
	for(int j=0;j<4;j++){
		switch(j){
			case 0:
				if(rName->isEnabled()) cur=rName->currentText();
				else cur=QString::null;
				group="NameHistory";
				index=0;
				break;
			case 1:
				if(nPref->isEnabled()) cur=nPref->currentText();
				else cur=QString::null;
				group="PrefixHistory";
				index=HISTORY_ITEMS;
				break;
			case 2:
				if(nSuf->isEnabled()) cur=nSuf->currentText();
				else cur=QString::null;
				group="SuffixHistory";
				index=2*HISTORY_ITEMS;
				break;
			case 3:
				if(rExt->isEnabled()) cur=rExt->currentText();
				else cur=QString::null;
				group="ExtensionHistory";
				index=3*HISTORY_ITEMS;
				break;
		}
		if(!cur.isEmpty()){
			int i;
			int found=-1;
			for(int i=0;i<HISTORY_ITEMS;i++){
				if(cur==history[index+i]){
					found=i;
					break;
				}
			}
			if(found!=0){
				if(found==-1) for(i=HISTORY_ITEMS-2;i>=1;i--) history[index+i+1]=history[index+i];
				else for(i=found-1;i>=1;i--) history[index+i+1]=history[index+i];
			}
			history[index]=cur;
// 			config.group(group); old impl
			KConfigGroup grp=config.group(group);
			for(int i=0;i<HISTORY_ITEMS;i++){
				QString n;
				n=QString("Exp%1").arg(i);
				if(!history[index+i].isEmpty()) grp.writeEntry(n,history[index+i]);
				else break;
			}
		}
	}

/*    rName->insertItem("",0);
	nPref->insertItem("",0);
	nSuf->insertItem("",0);
	rExt->insertItem("",0);*/
}
/////////////////////////////////////////////////////////////
//
//
//	End of History
//
//
/////////////////////////////////////////////////////////////


//================================
void GwenRename::buttonOkClicked(){
// 	if(!ts) ts=new timeStamp(this,&ic);
// 	else ts->readConfig(SECOND_TIMESTAMP_HISTORY_INDEX);
// 	ts->exec();
	
	
// 	if(!inMode) inMode=new initaskMode(this,&ic,"/home/aaa");
// 	inMode->exec();
	
	if(!mS) mS=new multiSelect(this,&ic);
	mS->exec();
	
}
//================================
GwenRename::~GwenRename()
{
	if(ts) delete ts;
	if(inMode) delete inMode;
	if(mS) delete mS;
}




//================================
int GwenRename::getRandom(){
	QString t;
	t=QString("%1").arg(rand());
	QString b=t.mid(4,1);
	int c=b.toInt();
	b=t.right((uint)c);
	b.prepend("0.");
	float l=b.toFloat();
	int k=f.items();
	l*=(float)k;
	return (int) l;
}
//================================
bool GwenRename::randExist( int num ){
	for(int i=0;i<g.numOfFiles;i++){
		if(g.ren[g.getSorted(i)].selected && g.ren[g.getSorted(i)].randomNum==num) return TRUE;
	}
	return FALSE;
}
//================================
int GwenRename::calcDigits( void ){
	QString tmp;
	int k=rStart->value();
	bool init=false;
// 	int t=0;
// // 	if(rStep->value()>0) for(int i=1;i<f.items();i++) k+=rStep->value();
// // 	else for(int i=1;i<f.items();i++) k-=rStep->value();

	for(int i=1;i<g.numOfFiles;i++)
		if(g.ren[i].selected){
// 			t++;
			if(init)
				k+=rStep->value();
			else
				init=true;
			
		}
// qWarning("  t=%d, k=%d",t,k);
	tmp.setNum(k);
	while((int)tmp.length()<rDigits->value()) tmp.prepend("0");
	int digits=(int) tmp.length();
	g.numOfDigits=digits;
// 	qWarning("digits=%d tmp=%s",digits,tmp.toLocal8Bit().constData());
	return digits;
}
//================================
QString GwenRename::getNumber( int num ){
	QString s;
	s.setNum(num);
	while((int)s.length()<g.numOfDigits) s.prepend("0");
	return s;
}
//================================
QString GwenRename::getNumberByID( int num ){
	QString tmp;
	int k;
	if(num==0){
		k=rStart->value();
	}
	else{
		k=rStart->value();
		for(int i=1;i<=num;i++) k+=rStep->value();
	}
	tmp.setNum(k);
	if(rWidth->isChecked()) calcDigits();
	else g.numOfDigits=rDigits->value();
	while((int)tmp.length()<g.numOfDigits) tmp.prepend("0");
	return tmp;
}
//================================
bool GwenRename::canDoRelaxed( void ){
  //return FALSE;
	bool sel=false;
	for(int i=0;i<g.numOfFiles;i++)
		if(g.ren[i].selected){
			sel=true;
			break;
		}
	if(!sel)
		return false;
	int i=0;
	while(!g.ren[g.getSorted(i)].selected) i++;
	QString p=g.ren[g.getSorted(i)].Prefix;
	QString s=g.ren[g.getSorted(i)].Suffix;
	for(i=0;i<g.numOfFiles;i++){
		if(g.ren[g.getSorted(i)].selected){
//			qWarning("GwenRename::canDoRelaxed() Prefix = %s",g.ren[g.getSorted(i)].Prefix.toLocal8Bit().constData());
// 			qWarning("GwenRename::canDoRelaxed() Suffix = %s",g.ren[g.getSorted(i)].Suffix.toLocal8Bit().constData());
			if(p!=g.ren[g.getSorted(i)].Prefix) return FALSE;
			if(s!=g.ren[g.getSorted(i)].Suffix) return FALSE;
		}
	}
// 	qWarning("GwenRename::canDoRelaxed = True");
	return TRUE;
}
//================================
bool GwenRename::isRelaxed( int item ){
	int i;
	bool ret=TRUE;
	QString t=QString::null;
	QString tPref=g.fPart.pref;
	QString tSuf=QString::null;
	QString tExp=QString::null;
	QString old=g.ren[g.getSorted(item)].oldName;
// 	t=old;
// 	t.remove(g.fPart.pref);
// 	t.remove(g.fPart.suf);
// 	int thisFileNumOfDigits=t.length();
// 	t=QString::null;
	int oldLength=g.ren[g.getSorted(item)].oldName.length();
	if(!g.ren[g.getSorted(item)].oldExtension.isEmpty()){
		oldLength+=g.ren[g.getSorted(item)].oldExtension.length()+1;
		old+=".";
		old+=g.ren[g.getSorted(item)].oldExtension;
	}
	int regLength=g.fPart.pref.length()+g.fPart.digitNum+g.fPart.suf.length();
	for(i=0;i<g.fPart.digitNum;i++) t+="[0-9]";
// 	for(i=0;i<thisFileNumOfDigits;i++) t+="[0-9]";
	tSuf=g.fPart.suf;
	if(!g.fPart.ext.isEmpty()){
		regLength+=g.fPart.ext.length()+1;
		tSuf+=".";
		tExp+=g.fPart.ext;
	}
// 	t=QRegExp::escape(tPref)+t+QRegExp::escape(tSuf)+QRegExp::escape(tExp)+"$"; old impl
// 	qWarning("tPref = %s, t = %s, tSuf = %s, tExp = %s", tPref.toLocal8Bit().constData(), t.toLocal8Bit().constData(), tSuf.toLocal8Bit().constData(), tExp.toLocal8Bit().constData());
	t=tPref+t+tSuf+tExp;//+"$";
// 	qWarning("t = %s",t.toLocal8Bit().constData());
	if(regLength == oldLength){
// 		QRegExp l=QRegExp(t,FALSE,FALSE); old impl
// 		QRegExp l=QRegExp("*.txt", Qt::CaseInsensitive, QRegExp::Wildcard);
// 		QRegExp l=QRegExp(t, Qt::CaseInsensitive, QRegExp::Wildcard);
		QRegExp l=QRegExp(t, Qt::CaseInsensitive, QRegExp::Wildcard);
// 		int ans=old.find(l,0); old impl
// 		qWarning("old = %s, t = %s", old.toLocal8Bit().constData(),t.toLocal8Bit().constData());
		int ans=old.indexOf(l);
// 		qWarning("ans = %d",ans);
		if(ans!=0){
// 			qWarning("ans is FALSE");
			ret=FALSE;
		}
	}else{
// 		qWarning("giving FALSE");
		ret=FALSE;
	}
	return ret;
}
//================================
bool GwenRename::checkIt( const QString mName ){
	QString tName;
	for(int j=0;j<g.numOfFiles;j++){
		if(!g.ren[g.getSorted(j)].selected){
			tName=g.ren[g.getSorted(j)].oldFileName;
	    //if(mName.find(tName ,0,FALSE)==0) return FALSE;
			if(mName==tName) return FALSE;
		}
	}
	return TRUE;
}
//================================
QString GwenRename::increaseQString( QString tmp ){
	int length=tmp.length();
	bool ok=FALSE;
	int val=tmp.toInt(&ok);
	val++;
	QString ret=QString::number(val);
	while((int)ret.length()<length) ret.prepend("0");
	return ret;
}
//================================
void GwenRename::fixbuttonOk(){
	buttonOk->setEnabled(FALSE);
	for(int k=0;k<g.numOfFiles;k++)
		if(g.ren[k].selected && g.ren[k].iconID==7)
			return;
	if(getSameNewName()!=-1)
		return;
	for(int i=0;i<g.numOfFiles;i++){
		if(g.ren[g.getSorted(i)].selected){
			if(g.ren[g.getSorted(i)].oldFileName!=g.ren[g.getSorted(i)].newFileName){
// 				qWarning("GwenRename::fixbuttonOk() - oldFileName<>newFileName");
				buttonOk->setEnabled(TRUE);
				return;
			}
		}
	}
}
//================================
int GwenRename::getSameNewName(){
	for(int i=0;i<g.numOfFiles-1;i++){
		if(g.ren[g.getSorted(i)].selected){
			if(g.ren[g.getSorted(i)].newFileName==g.path() + "/" || g.ren[g.getSorted(i)].newFileName==g.path() + "/." + g.ren[g.getSorted(i)].newExtension){
// 				qWarning("GwenRename::getSameNewName - g.ren[g.getSorted(i)].newFileName = %s", g.ren[g.getSorted(i)].newFileName.toLocal8Bit().constData());
// 				qWarning("GwenRename::getSameNewName - g.path() = %s",g.path().toLocal8Bit().constData());
// 				qWarning("GwenRename::getSameNewName - g.ren[g.getSorted(i)].newExtension = %s",g.ren[g.getSorted(i)].newExtension.toLocal8Bit().constData());
// 				qWarning("GwenRename::getSameNewName - returning %d",i);
				return i;
			}
			for(int j=0;j<g.numOfFiles;j++) if(g.ren[g.getSorted(i)].newFileName==g.ren[g.getSorted(j)].newFileName && j!=i){
// 				qWarning("GwenRename::getSameNewName - g.ren[g.getSorted(i)].newFileName = %s ",g.ren[g.getSorted(i)].newFileName.toLocal8Bit().constData());
// 				qWarning("GwenRename::getSameNewName - g.ren[g.getSorted(j)].newFileName = %s ",g.ren[g.getSorted(j)].newFileName.toLocal8Bit().constData());
// 				qWarning("GwenRename::getSameNewName - i=%d j=%d",i,j);
// 				qWarning("GwenRename::getSameNewName - returning %d",i);
				return i;
			}
		}
	}
// 	qWarning("GwenRename::getSameNewName() - returning -1");
	return -1;
}






//================================
void GwenRename::updateView(){
	if(!updateViewEnabled)
		return;
	QString num;
// 	rAllow->setEnabled(rShow->isEnabled()); // why?
	int k,start=rStart->value();
	bool calculationDone=FALSE;
	if(!InitiatedRename) return;
	buttonOk->setEnabled(FALSE);
	for(int i=0;i<g.numOfFiles;i++) g.ren[g.getSorted(i)].inc=0;
	if(f.Type==2 && rShuffle->isChecked() && rShuffle->isEnabled()){
		for(int i=0;i<g.numOfFiles;i++){
			g.ren[g.getSorted(i)].Counter="";
			g.ren[g.getSorted(i)].randomNum=-1;
		}
	// randomize directories
		for(int i=0;i<g.numOfFiles;i++){
			if(g.ren[g.getSorted(i)].selected){
		// randomize
				int r=getRandom();
				while(randExist(r)) r=getRandom();
				g.ren[g.getSorted(i)].randomNum=r;
				g.ren[g.getSorted(i)].Counter=getNumberByID(r);
			}
		}
		buttonOk->setEnabled(TRUE);
	}else{
		if(rAllow->isChecked() && rAllow->isEnabled() && canDoRelaxed()){
			int j=0;
			while(!g.ren[g.getSorted(j)].selected) j++;
			if(rStep->value()!=0 && rStart->isEnabled()){
				g.fPart.pref=g.ren[g.getSorted(j)].Prefix;
				g.fPart.suf=g.ren[g.getSorted(j)].Suffix;
				g.fPart.ext=g.ren[g.getSorted(j)].newExtension;
				if(nSpecify->isChecked()){
		    // using user defined name
					g.fPart.pref+=rName->currentText();
					g.fPart.digitNum=rDigits->value();
					if(!g.fPart.pref.isEmpty() && !g.fPart.suf.isEmpty()) g.fPart.partType=3;
					else if(!g.fPart.pref.isEmpty()) g.fPart.partType=1;
					else if(!g.fPart.suf.isEmpty()) g.fPart.partType=2;
					else g.fPart.partType=0;
				}else{
		    // using original name
				}
				for(int i=0;i<g.numOfFiles;i++){
					if(!g.ren[g.getSorted(i)].selected){
						if(isRelaxed(i)){
							QString cNum;
							QString c1Num;
							bool cont=TRUE;
							for(int c=g.fPart.pref.length();cont && c<(int)g.ren[g.getSorted(i)].oldName.length();c++){
								c1Num=g.ren[g.getSorted(i)].oldName.mid(c,1);
								if(c1Num >="0" && c1Num<="9") cNum+=c1Num;
								else cont=FALSE;
							}
							start = cNum.toInt(&cont)+rStep->value();
							if(start<rStart->value()) start=rStart->value();
						}
					}
				}
			}
		}
		if(rStart->isEnabled()){
			if(rStep->value()>0){
	    //set init values
				for(int i=0,l=-1;i<g.numOfFiles;i++){
					if(g.ren[g.getSorted(i)].selected){
						l++;
						if(rWidth->isChecked()){
							calcDigits();
						}else{
							g.numOfDigits= rDigits->value();
						}
						k=start+l*rStep->value();
						num=getNumber(k);
						g.ren[g.getSorted(i)].Counter=num;
					}
				}//end set init values
				int cur=start-rStep->value();
				QString nName;
				QString tName;
				for(int i=0;i<g.numOfFiles;i++){
					if(g.ren[g.getSorted(i)].selected){
						calculationDone=FALSE;
						while(!calculationDone){
							cur+=rStep->value();
							g.ren[g.getSorted(i)].Counter=getNumber(cur);
							if(g.ren[g.getSorted(i)].newExtension.isEmpty()) nName=g.path() + "/" + g.ren[g.getSorted(i)].newName + g.ren[g.getSorted(i)].Counter + g.ren[g.getSorted(i)].Suffix;
							else nName=g.path() + "/" + g.ren[g.getSorted(i)].newName + g.ren[g.getSorted(i)].Counter + g.ren[g.getSorted(i)].Suffix + "." + g.ren[g.getSorted(i)].newExtension;
							calculationDone=checkIt(nName);
						}
					}
				}
			}else if(rStep->value()<0){
				bool conflict=TRUE;
				start=((-1)*rStep->value()*(f.numOfFiles-2))+rStart->value();
	    //set init values
				while(conflict){
					start-=rStep->value();
					for(int i=0,l=start-rStep->value();i<g.numOfFiles;i++){
						if(g.ren[g.getSorted(i)].selected){
							l+=rStep->value();
							if(rWidth->isChecked()){
								calcDigits();
							}else{
								g.numOfDigits= rDigits->value();
							}
							num=getNumber(l);
							g.ren[g.getSorted(i)].Counter=num;
						}
					}//end set init values
					conflict=FALSE;
					QString tName,nName;
					for(int i=g.numOfFiles-1;i>=0;i--){
						if(g.ren[g.getSorted(i)].selected){
// 							if(f.Type==2 || g.ren[g.getSorted(i)].newExtension.isEmpty()) tName=g.path() + "/" +g.ren[g.getSorted(i)].newName + g.ren[g.getSorted(i)].Counter+g.ren[g.getSorted(i)].Suffix; old impl
							if(f.Type==2 || g.ren[g.getSorted(i)].newExtension.isEmpty()) tName=g.path() + "/" +g.ren[g.getSorted(i)].newName + g.ren[g.getSorted(i)].Counter+g.ren[g.getSorted(i)].Suffix;
// 							else tName=g.path() + "/" +g.ren[g.getSorted(i)].newName + g.ren[g.getSorted(i)].Counter +  g.ren[g.getSorted(i)].Suffix+"." + g.ren[g.getSorted(i)].newExtension; old impl
							else tName=g.path() + "/" +g.ren[g.getSorted(i)].newName + g.ren[g.getSorted(i)].Counter +  g.ren[g.getSorted(i)].Suffix+"." + g.ren[g.getSorted(i)].newExtension;
							nName=tName;
						}
						for(int i=0;i<g.numOfFiles;i++){
							if(!g.ren[g.getSorted(i)].selected){
								QString mName;
								if(f.Type==2 || g.ren[g.getSorted(i)].newExtension.isEmpty()) mName=g.path() + "/" +g.ren[g.getSorted(i)].newName + g.ren[g.getSorted(i)].Counter+g.ren[g.getSorted(i)].Suffix;
								else mName=g.path() + "/" +g.ren[g.getSorted(i)].newName + g.ren[g.getSorted(i)].Counter +  g.ren[g.getSorted(i)].Suffix+"." + g.ren[g.getSorted(i)].newExtension;
								if(mName==tName){
									conflict=TRUE;
									break;
								}
							}
						}
						if(conflict) break;
					}
		    // Check for files not in series
					if(!conflict){
						int i;
						QString tmp,tFile,cFile;
						for(i=g.numOfFiles-1;i>=0;i--){
							if(g.ren[g.getSorted(i)].selected){
								tmp=increaseQString(g.ren[g.getSorted(i)].Counter);
								if(f.Type==2 || g.ren[g.getSorted(i)].newExtension.isEmpty()) tFile=g.path() + "/" +g.ren[g.getSorted(i)].Prefix  + tmp+g.ren[g.getSorted(i)].Suffix;
								else tFile=g.path() + "/" +g.ren[g.getSorted(i)].Prefix  + tmp +  g.ren[g.getSorted(i)].Suffix+"." + g.ren[g.getSorted(i)].newExtension;
								for(int m=0;m<g.numOfFiles;m++){
									if(g.ren[g.getSorted(m)].selected){
										if(f.Type==2 || g.ren[g.getSorted(i)].newExtension.isEmpty()) cFile=g.path() + "/" +g.ren[g.getSorted(m)].Prefix + g.ren[g.getSorted(m)].Counter+g.ren[g.getSorted(m)].Suffix;
										else cFile=g.path() + "/" +g.ren[g.getSorted(m)].Prefix + g.ren[g.getSorted(m)].Counter +  g.ren[g.getSorted(m)].Suffix+"." + g.ren[g.getSorted(m)].newExtension;
									}else{
										cFile=g.ren[g.getSorted(m)].oldFileName;
									}
									if(tFile==cFile && !g.ren[g.getSorted(m)].selected){
										conflict=TRUE;
										break;
									}
								}
								if(conflict) break;
							}
						}
					}
				}
			}else{
				for(int i=0;i<g.numOfFiles;i++) g.ren[g.getSorted(i)].Counter="";
			}
		}else
			for(int i=0;i<g.numOfFiles;i++) g.ren[g.getSorted(i)].Counter="";
	}
// Common part
	QString toConv="-";
	if(spaceToUnder->isChecked()) toConv="_";
	
	QString thePath=g.path();
// 	qWarning("thePath = %s",thePath.toLocal8Bit().constData());
	if(thePath.isEmpty() || thePath.startsWith(".")){
// 		qWarning("using calculated path");
// 		int tmpIndex=g.ren[0].oldFileName.findRev("/"); old impl
		int tmpIndex=g.ren[0].oldFileName.lastIndexOf("/");
		thePath=g.ren[0].oldFileName.left(tmpIndex);
// 		qWarning("thePath = %s",thePath.toLocal8Bit().constData());
	}
	for(int i=0;i<g.numOfFiles;i++){
		// In this block newName = Prefix + specified new Name
		if(g.ren[g.getSorted(i)].selected){
			if(f.Type==2 || g.ren[g.getSorted(i)].newExtension.isEmpty()){
				if(spaceToUnder->isChecked() || spaceToDash->isChecked() ||underToSpace->isChecked() ||dashToSpace->isChecked()){
// 					QString suf=g.ren[g.getSorted(i)].Suffix;
// 					suf.replace(" ",toConv);

					g.ren[g.getSorted(i)].newFileName=thePath + "/" +g.ren[g.getSorted(i)].newName + g.ren[g.getSorted(i)].Counter+g.ren[g.getSorted(i)].newSuffix;
					g.ren[g.getSorted(i)].newTmpFileName=thePath + "/" +g.ren[g.getSorted(i)].newTmpName + 	g.ren[g.getSorted(i)].Counter+g.ren[g.getSorted(i)].newSuffix;
				}else{
					g.ren[g.getSorted(i)].newFileName=thePath + "/" +g.ren[g.getSorted(i)].newName + g.ren[g.getSorted(i)].Counter+g.ren[g.getSorted(i)].Suffix;
					g.ren[g.getSorted(i)].newTmpFileName=thePath + "/" +g.ren[g.getSorted(i)].newTmpName + 	g.ren[g.getSorted(i)].Counter+g.ren[g.getSorted(i)].Suffix;
				}
			}else{
				if(spaceToUnder->isChecked() || spaceToDash->isChecked() ||underToSpace->isChecked() ||dashToSpace->isChecked()){
					g.ren[g.getSorted(i)].newFileName=thePath + "/" +g.ren[g.getSorted(i)].newName + g.ren[g.getSorted(i)].Counter +  g.ren[g.getSorted(i)].newSuffix +"." + g.ren[g.getSorted(i)].newExtension;
// 					qWarning("%s",toConv.toLocal8Bit().constData());
// 					qWarning("prefix = %s",g.ren[g.getSorted(i)].Prefix.toLocal8Bit().constData());
// 					qWarning("suffix = %s",g.ren[g.getSorted(i)].Suffix.toLocal8Bit().constData());
// 					qWarning("newsuffix = %s",g.ren[g.getSorted(i)].newSuffix.toLocal8Bit().constData());
// 					qWarning("newName = %s",g.ren[g.getSorted(i)].newName.toLocal8Bit().constData());
// 					qWarning("newFileName = %s",g.ren[g.getSorted(i)].newFileName.toLocal8Bit().constData());
					g.ren[g.getSorted(i)].newTmpFileName=thePath + "/" +g.ren[g.getSorted(i)].newTmpName + g.ren[g.getSorted(i)].Counter + g.ren[g.getSorted(i)].newSuffix + "." + g.ren[g.getSorted(i)].newExtension;
				}else{
					g.ren[g.getSorted(i)].newFileName=thePath + "/" +g.ren[g.getSorted(i)].newName + g.ren[g.getSorted(i)].Counter +  g.ren[g.getSorted(i)].Suffix+"." + g.ren[g.getSorted(i)].newExtension;
// 					qWarning("prefix = %s",g.ren[g.getSorted(i)].Prefix.toLocal8Bit().constData());
// 					qWarning("suffix = %s",g.ren[g.getSorted(i)].Suffix.toLocal8Bit().constData());
// 					qWarning("newName = %s",g.ren[g.getSorted(i)].newName.toLocal8Bit().constData());
// 					qWarning("newFileName = %s",g.ren[g.getSorted(i)].newFileName.toLocal8Bit().constData());				
					g.ren[g.getSorted(i)].newTmpFileName=thePath + "/" +g.ren[g.getSorted(i)].newTmpName + g.ren[g.getSorted(i)].Counter + g.ren[g.getSorted(i)].Suffix+ "." + g.ren[g.getSorted(i)].newExtension;
				}
			}
		}
// 		qWarning("newTmpFileName = %s",g.ren[g.getSorted(i)].newTmpFileName.toLocal8Bit().constData());
	}
// qWarning("oldNameFileName = %s",g.ren[0].oldFileName.toLocal8Bit().constData());
	if(g.numOfSlectedItems()==0){
		rShow->setChecked(true);
		lSelected->setText(QString(i18n("%1/%2 items selected")).arg(0).arg(g.numOfFiles,0,10));
		rShowClicked(1);
	}else{
		if(rShow->isChecked() && rShow->isEnabled())  rShowClicked(1);
		else rShowClicked(0);
	}
	fixbuttonOk();
}

//================================
void GwenRename::updateNameView(){
	QString a,b;
	updateViewEnabled=false;
	if(nPref->currentText().isEmpty()){
		for(int i=0;i<g.numOfFiles;i++){
			g.ren[g.getSorted(i)].Prefix="";
		}
	}else{
		tFormatDate=nPref->currentText();
	// Check fot date code
		timeStamp *bStamp=new timeStamp;
		if(bStamp->checkFormat(nPref->currentText())){
			useTimeStamp(0);
		}else{
			for(int i=0;i<g.numOfFiles;i++){
				g.ren[g.getSorted(i)].Prefix=nPref->currentText();
			}
		}
		delete bStamp;
	}
	QString toConv="-";
	if(spaceToUnder->isChecked()) toConv="_";
	for(int i=0;i<g.numOfFiles;i++){
		if(g.ren[g.getSorted(i)].selected){
			a=""; b="";
			if( nOriginal->isChecked()){
// 				if( nLCase->isChecked()) a=g.ren[g.getSorted(i)].oldName.lower(); old impl
				if( nLCase->isChecked()) a=g.ren[g.getSorted(i)].oldName.toLower();
// 				else if( nUCase->isChecked()) a=g.ren[g.getSorted(i)].oldName.upper(); old impl
				else if( nUCase->isChecked()) a=g.ren[g.getSorted(i)].oldName.toUpper();
				else a=g.ren[g.getSorted(i)].oldName;

				if( nFCap->isChecked() && nFCap->isEnabled()){
// 					a=g.ren[g.getSorted(i)].oldName.lower(); old impl
					a=g.ren[g.getSorted(i)].oldName.toLower();
					a=firstCapitalize(a);
				}else if( nSCap->isChecked() && nSCap->isEnabled()){
// 					a=g.ren[g.getSorted(i)].oldName.lower(); old impl
					a=g.ren[g.getSorted(i)].oldName.toLower();
					a=allCapitalize(a);
				}else if(a.isEmpty()) a=g.ren[g.getSorted(i)].oldName;
			}else{
				if(!rName->currentText().isEmpty()) a=rName->currentText();
			}
 			b=a;
			b.append(QString("_tmp"));
			g.ren[g.getSorted(i)].newName=g.ren[g.getSorted(i)].Prefix+a;
			g.ren[g.getSorted(i)].newTmpName=g.ren[g.getSorted(i)].Prefix+b;
			if(spaceToUnder->isChecked() || spaceToDash->isChecked()){
				g.ren[g.getSorted(i)].newName.replace(" ",toConv);
				g.ren[g.getSorted(i)].newTmpName.replace(" ",toConv);
				g.ren[g.getSorted(i)].newSuffix=g.ren[g.getSorted(i)].Suffix;
				g.ren[g.getSorted(i)].newSuffix.replace(" ",toConv);
			}else if(underToSpace->isChecked() && dashToSpace->isChecked()){
					g.ren[g.getSorted(i)].newName.replace("_"," ");
					g.ren[g.getSorted(i)].newTmpName.replace("_"," ");
					g.ren[g.getSorted(i)].newSuffix=g.ren[g.getSorted(i)].Suffix;
					g.ren[g.getSorted(i)].newSuffix.replace("_"," ");
					g.ren[g.getSorted(i)].newName.replace("-"," ");
					g.ren[g.getSorted(i)].newTmpName.replace("-"," ");
					g.ren[g.getSorted(i)].newSuffix.replace("-"," ");
			}else if(underToSpace->isChecked() || dashToSpace->isChecked()){
				if(underToSpace->isChecked()){
					g.ren[g.getSorted(i)].newName.replace("_"," ");
					g.ren[g.getSorted(i)].newTmpName.replace("_"," ");
					g.ren[g.getSorted(i)].newSuffix=g.ren[g.getSorted(i)].Suffix;
					g.ren[g.getSorted(i)].newSuffix.replace("_"," ");
				}
				if(dashToSpace->isChecked()){
					g.ren[g.getSorted(i)].newName.replace("-"," ");
					g.ren[g.getSorted(i)].newTmpName.replace("-"," ");
					g.ren[g.getSorted(i)].newSuffix=g.ren[g.getSorted(i)].Suffix;
					g.ren[g.getSorted(i)].newSuffix.replace("-"," ");
				}
			}else
				g.ren[g.getSorted(i)].newSuffix=g.ren[g.getSorted(i)].Suffix;
		}
	}
	updateViewEnabled=true;
	updateView();
}
//================================
void GwenRename::updateExtView(){
	updateViewEnabled=false;
	for(int i=0;i<g.numOfFiles;i++){
		if(g.ren[g.getSorted(i)].selected){
			QString a=QString("");
			if(f.Type!=2) {
				if( rSelExt->isChecked()){
// 					if( rLExt->isChecked()) a=g.ren[g.getSorted(i)].oldExtension.lower(); old impl
					if( rLExt->isChecked()) a=g.ren[g.getSorted(i)].oldExtension.toLower();
// 					else if( rUExt->isChecked()) a=g.ren[g.getSorted(i)].oldExtension.upper(); old impl
					else if( rUExt->isChecked()) a=g.ren[g.getSorted(i)].oldExtension.toUpper();
					else a=g.ren[g.getSorted(i)].oldExtension;
				}else{
					if( !rExt->currentText().isEmpty()) a=rExt->currentText();
				}
			}
			g.ren[g.getSorted(i)].newExtension=a;
		}
	}
	updateViewEnabled=true;
	updateView();
}

void GwenRename::updateCounterView(){
	int val=rStep->value();
	updateViewEnabled=false;
// 	if(lSelected->text().startsWith("0"))
// 		return;
	if(countEnable->isChecked() && val!=0){
		if(val>0)
			lStart->setText(i18n("Start:"));
		else
			lStart->setText(i18n("End:"));
		frmCounter->setEnabled(TRUE);
		lStart->setEnabled(TRUE);
		rStart->setEnabled(TRUE);
		lStep->setEnabled(TRUE);
		rStep->setEnabled(TRUE);
		lDigits->setEnabled(TRUE);
		rDigits->setEnabled(TRUE);
		rWidth->setEnabled(TRUE);
		rAllow->setEnabled(TRUE);
		if(f.items()>1){
			if(nSpecify->isChecked() && rStart->isEnabled()){
				rAllow->setEnabled(TRUE);
				//qWarning("GwenRename::rStepClicked( int val ) rAllow->setEnabled(TRUE)");
			}else
				rAllow->setEnabled(FALSE);
			rWidth->setEnabled(TRUE);
			if(f.Type==2 && f.items()==g.numOfFiles){
				rShuffle->setEnabled(TRUE);
				rAllow->setEnabled(FALSE);
				if(rShuffle->isChecked())
					reRandomize->setEnabled(TRUE);
			}
		}
	}else{
		lStart->setText(i18n("Start:"));
		lStart->setEnabled(FALSE);
		rStart->setEnabled(FALSE);
		if(rStep->value()!=0){
			lStep->setEnabled(FALSE);
			rStep->setEnabled(FALSE);
		}else{
			lStep->setEnabled(TRUE);
			rStep->setEnabled(TRUE);
		}
		lDigits->setEnabled(FALSE);
		rDigits->setEnabled(FALSE);
		rWidth->setEnabled(FALSE);
		rAllow->setEnabled(FALSE);
		if(rStep->value()!=0)
			frmCounter->setEnabled(FALSE);
		else
			frmCounter->setEnabled(TRUE);
	}
	if(rStart->isEnabled()){
		if(rShuffle->isChecked() && rShuffle->isEnabled() && f.items()>1){
			reRandomize->setEnabled(TRUE);
			rAllow->setEnabled(FALSE);
		}else{
			reRandomize->setEnabled(FALSE);
			if(rStart->isEnabled() && (f.items()>1 && rStep->value()!=0 && rStep->isEnabled() && nSpecify->isChecked())){
				//qWarning("GwenRename::updateCounterView() rAllow->setEnabled(TRUE)");
				rAllow->setEnabled(TRUE);
			}else
				rAllow->setEnabled(FALSE);
		}
		if(rStep->value()<0){
			rAllow->setEnabled(FALSE);
		//rStart->setValue((-1)*rStep->value()*(f.numOfFiles-1));
		}
	}
	updateViewEnabled=true;
	updateView();
}
//================================
void GwenRename::mousePressEvent( QMouseEvent * e ){
	if((kLed1->underMouse() || lblLed1->underMouse())&& e->button()==Qt::LeftButton){
		handleLed1();
		e->accept();
	}else if((kLed2->underMouse() || lblLed2->underMouse())&& e->button()==Qt::LeftButton){
		handleLed2();
		e->accept();
	}else if((kLed3->underMouse() || lblLed3->underMouse())&& e->button()==Qt::LeftButton){
		handleLed3();
		e->accept();
	}else
		e->ignore();
}


void GwenRename::resizeEvent( QResizeEvent * ){
groupBox4->setMinimumWidth((int) this->width()/2 -20);
countBox->setMinimumWidth((int) this->width()/2 -20);
btngrpProfiles->setMinimumWidth((int) this->width()/2 -20);
}

//================================
void GwenRename::loadIcons(){
	int errorExists=0;
	QStringList picture("16x16/apps/gwenrename.png");
	if(ic.loadIcon(picture,0)==-1) errorExists++;
	picture=QStringList("gwenrename/icons/hicolor/16x16/actions/gwenrename-gray.png"); // def
	picture+="16x16/actions/presence_offline.png";
	picture+="16x16/actions/bookmark.png";
	if(ic.loadIcon(picture,1)==-1) errorExists++;
	picture=QStringList("16x16/apps/kalarm.png");
	picture+="16x16/apps/ktimer.png";
	picture+="gwenrename/icons/hicolor/16x16/actions/ktimer.png"; //def
	if(ic.loadIcon(picture,2)==-1) errorExists++;
	picture=QStringList("16x16/actions/gohome.png");
 	picture+="16x16/actions/go-home.png";
 	picture+="16x16/places/folder-home.png";
	picture+="gwenrename/icons/hicolor/16x16/actions/gohome.png"; //def
	if(ic.loadIcon(picture,3)==-1) errorExists++;
	picture=QStringList("16x16/actions/filenew.png");
	picture+="gwenrename/icons/hicolor/16x16/actions/filenew.png"; //def
	if(ic.loadIcon(picture,4)==-1) errorExists++;
	picture=QStringList("16x16/actions/pencil.png");
	picture+="16x16/actions/color_line.png";
	picture+="gwenrename/icons/hicolor/16x16/actions/pencil.png"; //def
	if(ic.loadIcon(picture,5)==-1) errorExists++;
	picture=QStringList("16x16/actions/dialog-ok.png");
	picture+="16x16/actions/dialog-ok-apply.png";
	picture+="16x16/actions/ok.png";
	picture+="16x16/actions/apply.png";
	picture+="gwenrename/icons/hicolor/16x16/actions/button_ok.png"; //def
	if(ic.loadIcon(picture,6)==-1) errorExists++;
	picture=QStringList("16x16/actions/dialog-cancel.png");
	picture+="16x16/actions/no.png";
	picture+="16x16/actions/remove.png";
	picture+="gwenrename/icons/hicolor/16x16/actions/button_cancel.png"; //def
	if( ic.loadIcon(picture,7)==-1) errorExists++;
	picture=QStringList("16x16/actions/redo.png");
	picture+="16x16/actions/edit-redo.png";
	picture+="gwenrename/icons/hicolor/16x16/actions/redo.png"; //def
	if(ic.loadIcon(picture,8)==-1) errorExists++;
	picture=QStringList("48x48/apps/gwenrename.png"); //def
	if( ic.loadIcon(picture,9)==-1) errorExists++;
	picture=QStringList("16x16/actions/cut.png");
	picture+="16x16/actions/edit-cut.png";
	picture+="gwenrename/icons/hicolor/16x16/actions/cut.png"; //def
	if(ic.loadIcon(picture,10)==-1) errorExists++;
// 	picture=QStringList("16x16/actions/locationbar_erase.png");
// 	picture+="gwenrename/icons/hicolor/16x16/actions/locationbar_erase.png"; //def
// 	if(ic.loadIcon(picture,11)==-1) errorExists++;
	picture=QStringList("gwenrename/icons/hicolor/16x16/actions/all-type-items.png"); //def
	if(ic.loadIcon(picture,12)==-1) errorExists++;
	picture=QStringList("gwenrename/icons/hicolor/16x16/actions/all-items.png"); //def
	if( ic.loadIcon(picture,13)==-1) errorExists++;
	picture=QStringList("16x16/actions/stop.png");
	picture+="16x16/actions/no.png";
	picture+="16x16/actions/remove.png";
	picture+="gwenrename/icons/hicolor/16x16/actions/stop.png"; //def
	if( ic.loadIcon(picture,14)==-1) errorExists++;
	// help is for main windows about button
	picture=QStringList("16x16/actions/help.png");
	picture+="16x16/apps/khelpcenter.png";
	picture+="gwenrename/icons/hicolor/16x16/actions/help.png"; //def
	if( ic.loadIcon(picture,15)==-1) errorExists++;
	// khelpcenter is for all help buttons
	picture=QStringList("16x16/actions/help.png");
	picture+="16x16/apps/khelpcenter.png";
	picture+="gwenrename/icons/hicolor/16x16/actions/khelpcenter.png"; //def
	if( ic.loadIcon(picture,16)==-1) errorExists++;
	picture=QStringList("16x16/actions/undo.png");
	picture+="16x16/actions/edit-undo.png";
	picture+="gwenrename/icons/hicolor/16x16/actions/undo.png"; //def
	if( ic.loadIcon(picture,17)==-1) errorExists++;
	picture=QStringList("16x16/actions/filefind.png");
	picture+="gwenrename/icons/hicolor/16x16/actions/filefind.png"; //def
	if( ic.loadIcon(picture,18)==-1) errorExists++;
	
	if(errorExists==1) exitError(2);
	else if(errorExists>1) exitError(3);
}
//================================
void GwenRename::renameError( int index, int mode ){
	QString msg;
	if(index==-1 && mode==0) KMessageBox::error(0,i18n("Renaming process error\n\nNo files have been renamed"),0);
	else{
		QString line;
// 		QFile restore(g.path()+"/gwenrename.restore"); old impl
		QFile restore(g.path()+"/gwenrename.restore");
		restore.remove();
// 		restore.open(IO_WriteOnly); old impl
  	restore.open(QIODevice::WriteOnly);
		QTextStream ts( &restore );
		if(mode==0){
			ts << "# gwenrename restore script" << endl;
			ts << "# restore filenames with '. ./gwenrename.restore'" << endl;
			for(int i=0;i<index;i++){
				if(g.ren[g.getSorted(i)].selected){
					if(g.ren[g.getSorted(i)].oldFileName!=g.ren[g.getSorted(i)].newFileName){
						line=QString("mv \"%1\" \"%2\"\n").arg(g.ren[g.getSorted(i)].newTmpFileName).arg(g.ren[g.getSorted(i)].oldFileName);
						ts << line;
					}
				}
			}
			ts << "rm gwenrename.restore" << endl;
		}else{
			for(int i=0;i<index;i++){
				if(g.ren[g.getSorted(i)].selected){
					line=QString("mv \"%1\" \"%2\"\n").arg(g.ren[g.getSorted(i)].newFileName).arg(g.ren[g.getSorted(i)].newTmpFileName);
					ts << line;
				}
			}
			for(int i=0;i<g.numOfFiles;i++){
				if(g.ren[g.getSorted(i)].selected){
					if(g.ren[g.getSorted(i)].oldFileName!=g.ren[g.getSorted(i)].newFileName){
						line=QString("mv \"%1\" \"%2\"\n").arg(g.ren[g.getSorted(i)].newTmpFileName).arg(g.ren[g.getSorted(i)].oldFileName);
						ts << line;
					}
				}
			}
			ts << "rm gwenrename.restore" << endl;
		}
		restore.close();
		msg=QString(i18n("Error renaming file \"%1\"\n\nA restore script named \"gwenrename.restore\" has been written in the working directory")).arg(g.ren[g.getSorted(index)].oldFileName);
		KMessageBox::error(0,msg,0);
	}
// 	close(TRUE); old impl
	close();
}
//================================
bool GwenRename::historyItemExist( KComboBox *com, QString s ){
	for(int i=0;i<com->count();i++)
// 		if(com->text(i)==s) old impl
		if(com->itemText(i)==s)
			return TRUE;
	return FALSE;
}
//================================
void GwenRename::exitError(int errorMsg){
	if(errorMsg==1){
		KMessageBox::error(0,i18n("Memory allocation error\n\nThe program could not allocate memory needed for its execution. Close some applications and try again"),0);
	close(); //old impl close(TRUE);
// 	done(1);
		
	}else if(errorMsg==2)
		KMessageBox::error(0,i18n("Icon not found\n\nThe program could not find an icon that's necessary for its execution. Please check your installation"),0);
	else if(errorMsg==3)
		KMessageBox::error(0,i18n("Icons not found\n\nThe program could not find some icons that are necessary for its execution. Please check your installation"),0);
}

//================================
void GwenRename::getFormatParts( int mode ){
	int i=-1;
	int pos,l=0;
	QString a,b,c;
	if(mode==0) c=nPref->currentText();
	else c=nSuf->currentText();
// 	while((i=c.find(":",i+1,TRUE))!=-1) l++; old impl
	while((i=c.indexOf(":",i+1,Qt::CaseInsensitive))!=-1) l++;
	if(l==2){
// 		pos=c.find(":",0,TRUE); old impl
		pos=c.indexOf(":",0,Qt::CaseInsensitive);
		a=c.left(pos);
// 		pos=c.find(":",pos+1,TRUE); old impl
		pos=c.indexOf(":",pos+1,Qt::CaseInsensitive);
		b=c.right(c.length()-pos-1);
	}else{
		pos=nPref->cursorPosition();
		a=nPref->currentText().left(pos);
		b=nPref->currentText().right(nPref->currentText().length()-pos);
// 		if((i=a.find(":",0,TRUE))!=-1) a=a.left(i); old impl
		if((i=a.indexOf(":",0,Qt::CaseInsensitive))!=-1) a=a.left(i);
// 		if((i=b.find(":",0,TRUE))!=-1) b=b.right(b.length()-i-1); old impl
		if((i=b.indexOf(":",0,Qt::CaseInsensitive))!=-1) b=b.right(b.length()-i-1);
	}
	tFormatBefore=a;
	tFormatAfter=b;
}

//================================
void GwenRename::showAbout(){
	mHelpMenu = new KHelpMenu( buttonAbout, ab, false);
	mHelpMenu->menu()->exec( buttonAbout->mapToGlobal(QPoint(0, buttonAbout->height())) );
}
//================================
void GwenRename::CancelIt(){
	static bool cancelingIt=FALSE;
// 	if(cmbProfile->editable() || cancelingIt) return; old impl
	if(cmbProfile->isEditable() || cancelingIt) return;
// 	for(int k=0;k<g.numOfFiles;k++)
// 		qWarning("%s - %s",g.ren[g.getSorted(k)].oldFileName.toLocal8Bit().constData(),g.ren[g.getSorted(k)].newFileName.toLocal8Bit().constData());
// 	close(TRUE); old impl
	close();
}
//================================
void GwenRename::keyPressEvent( QKeyEvent *e ){
// 	if(e->key()==Qt::Key_Escape && e->modifiers()==Qt::NoButton){
// 		e->accept();
// 		CancelIt();
// 	}else if(e->key()==Qt::Key_F1 && e->modifiers()==Qt::NoButton){
// 		 showHelp();
// 	}else
// 		e->ignore();





	if(e->key()==Qt::Key_F1 && e->modifiers()==Qt::NoButton){
		e->accept();
// 		// show help based on focused component
// 		if(rName->hasFocus())// name
// 				 KRun::runCommand(QString("khelpcenter \"help:/gwenrename/time-stamping-window.html\""));
// 		if(nPref->hasFocus() || nSuf->hasFocus()) // prefix-suffix
// 				 KRun::runCommand(QString("khelpcenter \"help:/gwenrename/time-stamping-window.html\""));
// 		else if(rExt->hasFocus() || cmbExt->hasFocus()) // extension
// 				 KRun::runCommand(QString("khelpcenter \"help:/gwenrename/time-stamping-window.html\""));
// 		else if(rStart->hasFocus() || rStep->hasFocus() || rDigits->hasFocus()) // counter
// 				 KRun::runCommand(QString("khelpcenter \"help:/gwenrename/time-stamping-window.html\""));
// 		else if(cmbProfile->hasFocus()) // profile
// 				 KRun::runCommand(QString("khelpcenter \"help:/gwenrename/time-stamping-window.html\""));
// 		else
		
		
		
				KRun::runCommand(QString("khelpcenter \"help:/gwenrename/index.html\""),this);
				 
				 
// 		KURL url(QString("help:/gwenrename/main-window.html").arg(theErrorMessage));
// 		new KRun(url);
				 
	}else{
		if(cmbProfile->isEditable()){
			if(cmbProfile->hasFocus()){
				if(e->key()==Qt::Key_Escape && e->modifiers()==Qt::NoButton){
					e->accept();
					prDeleteClicked();
				}else if((e->key()==Qt::Key_Return && e->modifiers()==Qt::NoButton) || (e->key()==Qt::Key_Enter && e->modifiers()==Qt::KeypadModifier)){
					e->accept();
					prSaveClicked();
				}
			}//else e->ignore();
		}else if(cmbExt->isEditable()){
			if(cmbExt->hasFocus()){
				if(e->key()==Qt::Key_Escape && e->modifiers()==Qt::NoButton){
					e->accept();
					btDelExtClicked();
				}else if((e->key()==Qt::Key_Return && e->modifiers()==Qt::NoButton) || (e->key()==Qt::Key_Enter && e->modifiers()==Qt::KeypadModifier)){
					e->accept();
					btSaveExtClicked();
					for(int i=0;i<cmbExt->count();i++){
						if(cmbExt->itemText(i).isEmpty()){
							cmbExt->removeItem(i);
							activeExtension--;
							break;
						}
					}
				}
			}//else e->ignore();
		}else{
			if(e->key()==Qt::Key_Escape && e->modifiers()==Qt::NoButton){
				// escape pressed, exit the program
				e->accept();
				CancelIt();
			}else if((e->key()==Qt::Key_Return && e->modifiers()==Qt::NoButton) || (e->key()==Qt::Key_Enter && e->modifiers()==Qt::KeypadModifier)){
				// enter pressed, rename files
				e->accept();
				RenameIt();
			}else
				e->ignore();
		}
	}
}


//================================
//
//    Extensions slots
//
//================================
//================================
void GwenRename::btNewExtClicked(){
// 	cmbExt->setInsertionPolicy(QComboBox::AtBottom); old impl
	cmbExt->setInsertPolicy(QComboBox::InsertAtBottom);
	btNewExt->setEnabled(FALSE);
	btSaveExt->setEnabled(TRUE);
	btDelExt->setEnabled(TRUE);
	cmbExt->setEditable(TRUE);
// // 	cmbExt->insertItem(QString::null); old impl
// // 	cmbExt->insertItem(0,QString::null);
// 	cmbExt->insertItem(cmbExt->count(),QString::null);
// // 	cmbExt->setCurrentItem(cmbExt->count()-1); old impl
// 	cmbExt->setCurrentIndex(cmbExt->count()-1);
// 	cmbExt->setFocus();
// 	activeExtension=cmbExt->count()-1;
// 

	cmbExt->setFocus();
	cmbExt->setEditText("");
}
//================================
void GwenRename::btDelExtClicked(){
// 	if(cmbExt->editable()) old impl
	if(cmbExt->isEditable())
		cmbExt->setEditable(FALSE);
	cmbExt->removeItem(activeExtension);
	activeExtension--;
	compoundExtensions--;
	btNewExt->setEnabled(TRUE);
	btSaveExt->setEnabled(FALSE);
}
//================================
void GwenRename::cmbExtChanged(){
// 	if(cmbExt->editable()){ old impl
	if(cmbExt->isEditable()){
// 		if(cmbExt->text(activeExtension).isEmpty()){ old impl
		if(cmbExt->itemText(activeExtension).isEmpty()){
// 			cmbExt->setCurrentItem(cmbExt->count()-1); old impl
			cmbExt->setCurrentIndex(cmbExt->count()-1);
			return;
		}else{
// 			cmbExt->setCurrentItem(activeExtension); old impl
			cmbExt->setCurrentIndex(activeExtension);
			return;
		}
	}
// 	activeExtension=cmbExt->currentItem(); old impl
	activeExtension=cmbExt->currentIndex();
}
//================================
void GwenRename::btSaveExtClicked(){
	QLineEdit * lin=cmbExt->lineEdit();
	QString tmp=lin->text();
// qWarning("tmp = %s",tmp.toLocal8Bit().constData());
	if(tmp.startsWith("."))
		tmp=tmp.mid(1,tmp.length());
	if((!tmp.isEmpty() && !tmp.contains(".")) || tmp.length()==1)
		tmp=QString::null;
// qWarning("tmp = %s",tmp.toLocal8Bit().constData());
// 	cmbExt->setCurrentText(tmp); old impl
	cmbExt->setEditText(tmp);
	cmbExt->setEditable(FALSE);
	btNewExt->setEnabled(TRUE);
	btSaveExt->setEnabled(FALSE);
// 	if(tmp.isEmpty()){
// 		cmbExt->removeItem(activeExtension);
// 		activeExtension--;
// 	}
	if(!tmp.isEmpty()){
		cmbExt->insertItem(cmbExt->count(),tmp);
// 		qWarning("activeExtension was %d",activeExtension);
		activeExtension=cmbExt->count()-1;
// 		qWarning("activeExtension is %d",activeExtension);
		cmbExt->setCurrentIndex(activeExtension);
		compoundExtensions++;
	}
}
//================================
void GwenRename::AdjustExtension(){
	updateViewEnabled=false;
	QString fil,ext,knExt;
	if(extBox->isEnabled()){
		for(int i=0;i<cmbExt->count();i++){
			//qWarning("compound extension = %s",cmbExt->text(i).toLocal8Bit().constData());
			if(chkFullExt->isChecked()){
// 				knExt=cmbExt->text(i); old impl
				knExt=cmbExt->itemText(i);
				for(int k=0;k<g.numOfFiles;k++){
					if(g.ren[g.getSorted(k)].selected){
// 						int j=knExt.findRev("."); old impl
						int j=knExt.lastIndexOf(".");
						fil=knExt.left(j);
						ext=knExt.mid(j+1,knExt.length());
						if(g.ren[g.getSorted(k)].oldName.right(fil.length())==fil){
							//qWarning("  fil = %s\n  ext = %s",fil.toLocal8Bit().constData(),ext.toLocal8Bit().constData());
							//qWarning("  ondName = %s\n  oldExt = %s",g.ren[g.getSorted(k)].oldName.toLocal8Bit().constData(),g.ren[g.getSorted(k)].oldExtension.toLocal8Bit().constData());
							g.ren[g.getSorted(k)].oldExtension=knExt;
							j=g.ren[g.getSorted(k)].oldName.length()-fil.length()-1;
							//qWarning("  j = %d",j);
							g.ren[g.getSorted(k)].oldName=g.ren[g.getSorted(k)].oldName.left(j);
							//qWarning("  ondName = %s\n  oldExt = %s",g.ren[g.getSorted(k)].oldName.toLocal8Bit().constData(),g.ren[g.getSorted(k)].oldExtension.toLocal8Bit().constData());
							//qWarning("-----------");
						}
					}
				}
			}else{
// 				knExt=cmbExt->text(i); old impl
				knExt=cmbExt->itemText(i);
				//qWarning("knExt = %s",knExt.toLocal8Bit().constData());
				for(int k=0;k<g.numOfFiles;k++){
					if(g.ren[g.getSorted(k)].selected){
						//qWarning("ondName = %s\noldExt = %s",g.ren[g.getSorted(k)].oldName.toLocal8Bit().constData(),g.ren[g.getSorted(k)].oldExtension.toLocal8Bit().constData());
						if(g.ren[g.getSorted(k)].oldExtension==knExt){
// 							int j=knExt.findRev(".",knExt.length()); old impl
							int j=knExt.lastIndexOf(".",knExt.length());
							g.ren[g.getSorted(k)].oldExtension=knExt.mid(j+1,knExt.length());
							g.ren[g.getSorted(k)].oldName=g.ren[g.getSorted(k)].oldName+"."+knExt.left(j);
							//qWarning("ondName = %s\noldExt = %s",g.ren[g.getSorted(k)].oldName.toLocal8Bit().constData(),g.ren[g.getSorted(k)].oldExtension.toLocal8Bit().constData());
							
						}
					}
				}
			}
		}
		if(rSelExt->isChecked()) rSElExtClicked(1);
		else rSElExtClicked(0);
		updateNameView();
		updateViewEnabled=true;
		updateView();
	}
}


//================================
void GwenRename::useTimeStamp( int mode ){
	QString out;
	for(int j=0;j<g.numOfFiles;j++){
		if(g.ren[g.getSorted(j)].selected){
			QDateTime fTime;
			fTime=getTimeStampData(g.ren[g.getSorted(j)].oldFileName,tFormatDate.left(1));
			out=tFormatBefore+fTime.toString(fixFormat(tFormatDate))+tFormatAfter;
			if(mode==0) g.ren[g.getSorted(j)].Prefix=out;
			else g.ren[g.getSorted(j)].Suffix=out;
		}
	}
}
//================================
QDateTime GwenRename::getTimeStampData( QString fName, QString type ){
	QFileInfo f=QFileInfo(fName);
	if(type=="C") return f.created();
	else if(type=="M") return f.lastModified();
	else if(type=="R") return f.lastRead();
	else if(type=="E"){
		EXIF ex(fName);
		if(ex.isExif){
	    //read Exif data
			QString retDate=ex.getExifDate(1);
			if(isValidExifDate(retDate)){
				QDateTime dt;
				dt=exifToDate(retDate);
				if(!dt.isValid()) return f.created();
				return dt;
			}else return f.created();
		}else return f.created();
	}else if(type=="L"){
		EXIF ex(fName);
		if(ex.isExif){
	    //read Exif data
			QString retDate=ex.getExifDate(0);
			if(isValidExifDate(retDate)){
				QDateTime dt;
				dt=exifToDate(retDate);
				if(!dt.isValid()) return f.lastModified();
				return dt;
			}else return f.lastModified();
		}return f.lastModified();
	}
	return f.created();
}
//================================
bool GwenRename::isValidExifDate( QString s ){
	QString a("^[0-9][0-9][0-9][0-9]:[0-9][0-9]:[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]$");
	QRegExp reg(a);
// 	if(s.find(reg,0)==-1) return FALSE; old impl
	if(s.indexOf(reg,0)==-1) return FALSE;
	else return TRUE;
}
//================================
QDateTime GwenRename::exifToDate( QString x ){
	int y,m,d;
	bool ok;
	y=x.left(4).toInt(&ok);
	m=x.mid(5,2).toInt(&ok);
	d=x.mid(8,2).toInt(&ok);
	QDate ddDate(y,m,d);
	int h,s,ms;
	h=x.mid(11,2).toInt(&ok);
	s=x.mid(14,2).toInt(&ok);
	ms=x.mid(17,2).toInt(&ok);
	QTime ttTime(h,s,ms);
	QDateTime r(ddDate,ttTime);
	return r;
}
//================================
QString GwenRename::fixFormat( QString mFormat ){
	QString a=mFormat.right(mFormat.length()-1);
	QRegExp reg=QRegExp("D");a.replace(reg,"d");
	reg=QRegExp("Y");a.replace(reg,"y");
	reg=QRegExp("H");a.replace(reg,"h");
	reg=QRegExp("S");a.replace(reg,"s");
	reg=QRegExp("Z");a.replace(reg,"z");
	return a;
}
//================================
QString GwenRename::firstCapitalize( QString s ){
	QString tmp;
// 	tmp=s.left(1).upper(); old impl
	tmp=s.left(1).toUpper();
	tmp+=s.mid(1,s.length());
	return tmp;
}
//================================
QString GwenRename::allCapitalize( QString s ){
	int i;
	QString tmp=s;
	for(i=0;i<s.length();i++){
		if((s.mid(i,1))==QString(" ")){
// 			tmp=s.replace(i+1,1,s.mid(i+1,1).upper()); old impl
			tmp=s.replace(i+1,1,s.mid(i+1,1).toUpper());
		}
	}
	tmp=firstCapitalize(tmp);
	return tmp;
}
//================================
void GwenRename::rSElExtClicked( int state ){
	if(state==0){
		rLExt->setEnabled(FALSE);
		rUExt->setEnabled(FALSE);
		lExt->setEnabled(TRUE);
		rExt->setEnabled(TRUE);
// 		clearNewExtension->setEnabled(TRUE);
		rExt->setFocus();
		for(int i=0;i<g.numOfFiles;i++)
			if(g.ren[g.getSorted(i)].selected) g.ren[g.getSorted(i)].newExtension=rExt->currentText();
	}else{
		rLExt->setEnabled(TRUE);
		rUExt->setEnabled(TRUE);
		lExt->setEnabled(FALSE);
		rExt->setEnabled(FALSE);
// 		clearNewExtension->setEnabled(FALSE);
		if(rUExt->isChecked()) rUExt->setFocus();
		else rLExt->setFocus();
		for(int i=0;i<g.numOfFiles;i++){
			if(g.ren[g.getSorted(i)].selected){
				if(rLExt->isChecked())
// 					g.ren[g.getSorted(i)].newExtension=g.ren[g.getSorted(i)].oldExtension.lower(); old impl
					g.ren[g.getSorted(i)].newExtension=g.ren[g.getSorted(i)].oldExtension.toLower();
				else if(rUExt->isChecked())
// 					g.ren[g.getSorted(i)].newExtension=g.ren[g.getSorted(i)].oldExtension.upper(); old impl
					g.ren[g.getSorted(i)].newExtension=g.ren[g.getSorted(i)].oldExtension.toUpper();
				else g.ren[g.getSorted(i)].newExtension=g.ren[g.getSorted(i)].oldExtension;
			}
		}
	}
	updateExtView();
}



void GwenRename::AdjustPartName(){
//	qWarning("GwenRename::AdjustPartName");
//	KMessageBox::information(this,"Function not implemented yet!!!",QString::null,QString::null,KMessageBox::AllowLink);
	
// 	if(nPB->exec())
		KMessageBox::information(this,"Function not implemented yet!!!",QString::null,QString::null,KMessageBox::AllowLink);
	
}
//================================
void GwenRename::AdjustPartNameFromSufix(){
	qWarning("GwenRename::AdjustPartNameFromSufix");
	KMessageBox::information(this,"Function not implemented yet!!!",QString::null,QString::null,KMessageBox::AllowLink);
}
//================================
void GwenRename::AdjustPartNameFromPrefix(){
	qWarning("GwenRename::AdjustPartNameFromPrefix");
	KMessageBox::information(this,"Function not implemented yet!!!",QString::null,QString::null,KMessageBox::AllowLink);
}
//================================
void GwenRename::RenameIt(){
	static bool renamingIt=FALSE;
	bool renError=false;
	if(!buttonOk->isEnabled()) return;
// 	if(cmbProfile->editable() || renamingIt) return; old impl
	if(cmbProfile->isEditable() || renamingIt) return;
	renamingIt=TRUE;
	buttonOk->setEnabled(FALSE);
	writeHistory();
	hide();
	int it=-2;
	for(int i=0;i<g.numOfFiles;i++){
		if(g.ren[g.getSorted(i)].selected){
			it++;
			if(g.ren[g.getSorted(i)].oldFileName!=g.ren[g.getSorted(i)].newFileName){
				QDir fr=QDir(g.ren[g.getSorted(i)].oldFileName);
				if(!fr.rename(g.ren[g.getSorted(i)].oldFileName,g.ren[g.getSorted(i)].newTmpFileName)){
// 					qWarning("%s -> %s",g.ren[g.getSorted(i)].oldFileName.toLocal8Bit().constData(),g.ren[g.getSorted(i)].newTmpFileName.toLocal8Bit().constData());
// 					qWarning("renameError 1");
					if(it==-1) renameError(-1,0);
					else renameError(i,0);
					renError=true;
					break;
				}
			}
		}
	}
	if(!renError){
		for(int i=0;i<g.numOfFiles;i++){
			if(g.ren[g.getSorted(i)].selected){
				
				if(g.ren[g.getSorted(i)].oldFileName!=g.ren[g.getSorted(i)].newFileName){
					QDir fr=QDir(g.ren[g.getSorted(i)].newTmpFileName);
					if(!fr.rename(g.ren[g.getSorted(i)].newTmpFileName,g.ren[g.getSorted(i)].newFileName)){
	// 					qWarning("renameError 2");
						renameError(i,1);
						break;
					}
				}
			}
		}
	}
	 //writeHistory();
	close();
}
//================================
void GwenRename::chkProfileCahnged( int state ){
	if(state==0){
		prNew->setEnabled(FALSE);
		prSave->setEnabled(FALSE);
		prDelete->setEnabled(FALSE);
		cmbProfile->setEnabled(FALSE);
		prDefault->setEnabled(FALSE);
		prLoad->setEnabled(FALSE);
		prEdit->setEnabled(FALSE);
		applyProfile(0);
	}else{
		prNew->setEnabled(TRUE);
		cmbProfile->setEnabled(TRUE);
		cmbProfile->setFocus();
		prDefault->setEnabled(TRUE);
		prLoad->setEnabled(TRUE);
// 		if(cmbProfile->currentItem()==0){ old impl
		if(cmbProfile->currentIndex()==0){
			prSave->setEnabled(FALSE);
			prDelete->setEnabled(FALSE);
			prEdit->setEnabled(FALSE);
		}else{
			prSave->setEnabled(TRUE);
			prDelete->setEnabled(TRUE);
			prEdit->setEnabled(TRUE);
		}
// 		applyProfile(getProfileByIndex(cmbProfile->currentItem())); old impl
		applyProfile(getProfileByIndex(cmbProfile->currentIndex()));
	}
	pr.useProf=chkProfile->isChecked();
}
//================================
void GwenRename::applyProfile( int index ){
	updateViewEnabled=false;
	InitiatedRename=FALSE;
	int i=getProfileByIndex(index);
	pr.active=i;
	// Known extensions
	chkFullExt->setChecked(pr.data[i].useCompoundExt);
    // Name group
// 	rName->setCurrentText(pr.data[i].specName); old impl
	rName->setEditText(pr.data[i].specName);
	int modif=pr.data[i].origModif;
	nLCase->setChecked(FALSE);nUCase->setChecked(FALSE);
	nFCap->setChecked(FALSE);nSCap->setChecked(FALSE);
	if(modif==0) nLCase->setChecked(TRUE);
	else if(modif==1) nUCase->setChecked(TRUE);
	else if(modif==2) nFCap->setChecked(TRUE);
	else if(modif==3) nSCap->setChecked(TRUE);
	nOriginal->setChecked(FALSE);
	nSpecify->setChecked(FALSE);
	if(pr.data[i].useOrigName) nOriginal->setChecked(TRUE);
	else nSpecify->setChecked(TRUE);
	if(pr.data[i].useNumeric && sort->isEnabled()) sort->setChecked(TRUE);
	else sort->setChecked(FALSE);
	if(pr.data[i].convSpaceToUnder) spaceToUnder->setChecked(TRUE);
	else spaceToUnder->setChecked(FALSE);
	if(pr.data[i].convSpaceToDash) spaceToDash->setChecked(TRUE);
	else spaceToDash->setChecked(FALSE);
	
	if(pr.data[i].convUnderToSpace){
		spaceToDash->setChecked(FALSE);
		spaceToUnder->setChecked(FALSE);
		underToSpace->setChecked(TRUE);
	}else
		underToSpace->setChecked(FALSE);
	
	if(pr.data[i].convDashToSpace){
		spaceToDash->setChecked(FALSE);
		spaceToUnder->setChecked(FALSE);
		dashToSpace->setChecked(TRUE);
	}else
		dashToSpace->setChecked(FALSE);
	
    // Counter group
	rDigits->setValue(pr.data[i].digits);
	rStart->setValue(pr.data[i].start);
	rStep->setValue(pr.data[i].step);
    //if(f.items()==1)    rStep->setValue(pr.data[i].step);
    //else{
	if(f.items()==1){
    	//rStep->setValue(1);
		rWidth->setEnabled(FALSE);
		rAllow->setEnabled(FALSE);
		rShuffle->setEnabled(FALSE);
		reRandomize->setEnabled(FALSE);
	}
	rWidth->setChecked(pr.data[i].sameNum);
	rAllow->setChecked(pr.data[i].allow);
	rShuffle->setChecked(pr.data[i].shuffle);
    // Extension group
// 	rExt->setCurrentText(pr.data[i].newExt); old impl
	rExt->setEditText(pr.data[i].newExt);
	modif=pr.data[i].extModif;
	rLExt->setChecked(FALSE);rUExt->setChecked(FALSE);
	if(modif==0){
		rUExt->setChecked(FALSE);
		rLExt->setChecked(TRUE);
	}else if(modif==1){
		rLExt->setChecked(FALSE);
		rUExt->setChecked(TRUE);
	}
	rSelExt->setChecked(TRUE);
	rSelExt->setChecked(pr.data[i].useOrigExt);
	if(rSelExt->isChecked()){
		rUExt->setEnabled(TRUE);
		rLExt->setEnabled(TRUE);
		lExt->setEnabled(FALSE);
		rExt->setEnabled(FALSE);
	}else{
		rUExt->setEnabled(FALSE);
		rLExt->setEnabled(FALSE);
		lExt->setEnabled(TRUE);
		rExt->setEnabled(TRUE);
	}
    // Misc group
	rShow->setChecked(pr.data[i].showAll);
// 	nPref->setCurrentText(pr.data[i].prefix); old impl
	nPref->setEditText(pr.data[i].prefix);
// 	nSuf->setCurrentText(pr.data[i].suffix); old impl
	nSuf->setEditText(pr.data[i].suffix);
		// use counter
	countEnable->setChecked(pr.data[i].counterActive);
// 	if(countEnable->isChecked())
// 		rStepClicked(1);
// 	else
// 		rStepClicked(0);
	rStart->setEnabled(countEnable->isChecked());
	if(cmbProfile->isEnabled()) cmbProfile->setFocus();
	InitiatedRename=TRUE;
	updateCounterView();
	updateNameView();
	updateViewEnabled=true;
 	updateView();
}
//================================
int GwenRename::getProfileByIndex( int index ){
	int i;
	for(i=0;i<pr.numOfProfiles;i++)
// 		if(cmbProfile->text(index)==pr.data[i].Name && !pr.data[i].deleted) return i; old impl
		if(cmbProfile->itemText(index)==pr.data[i].Name && !pr.data[i].deleted) return i;
	return -1;
}
//================================
int GwenRename::getProfileByCurrentText(){
	int i;
	QString tmp=cmbProfile->currentText();
	for(i=0;i<pr.numOfProfiles;i++)
		if(tmp==pr.data[i].Name && !pr.data[i].deleted) return i;
	return -1;
}
//================================
int GwenRename::getProfileByText(QString txt){
	int i;
	for(i=0;i<pr.numOfProfiles;i++)
		if(txt==pr.data[i].Name && !pr.data[i].deleted) return i;
	return -1;
}
//================================
int GwenRename::getDefProfileIndex(){
	for(int i=0;i<pr.numOfProfiles;i++){
		if(!pr.data[i].deleted){
			if(pr.data[i].prof==pr.defProf) return i;
		}
	}
	return 0;
}
//================================
QString GwenRename::getNewProfileNumber(){
	int i;
	int max=0;
	QString txt;
	for(i=0;i<cmbProfile->count();i++){
// 		txt=cmbProfile->text(i); old impl
		txt=cmbProfile->itemText(i);
// 		if(txt.find(profName)==0){ old impl
		if(txt.indexOf(profName)==0){
			if(txt==profName) max=1;
			else{
				bool ok;
				QString tmp=profName + " ";
				txt.remove(tmp);
				int num=txt.toInt(&ok)+1;
				if(num>max) max=num;
			}
		}
	}
	if(max==0) return QString::null;
	else{
		QString tmp=" ";
		tmp.append(QString::number(max));
		return tmp;
	}
}
//================================
int GwenRename::readProfiles( KConfig *conf ){
	bool ok=FALSE;int num=0;
	QStringList gr=conf->groupList();
// 	QStringList profs=gr.grep(QRegExp("Profile[0-9][0-9]*")); old impl
	QStringList profs=gr.filter(QRegExp("Profile[0-9][0-9]*"));
// 	QStringList::iterator it=profs.begin(); old impl
	pr.numOfProfiles=profs.count()+1;
	pr.data=new config_data[pr.numOfProfiles];
// 	qWarning("pr.numOfProfiles = %d",pr.numOfProfiles);
	if(pr.data==NULL) exitError(1);
// 	for(;!(*it).isEmpty();++it){ old impl
// 	qWarning("GwenRename::readProfiles()  --  profs.count() = %d",profs.count());
	for(num=1;num<=profs.count();num++){
// 		num++; old impl
// 		conf->setGroup(*it); old impl
// 		qWarning("  -------- num = %d --------",num);
// 		qWarning("GwenRename::readProfiles()  --  profs[%d] = %s",num-1,profs[num-1].toLocal8Bit().constData());
// 		qWarning("GwenRename::readProfiles()  --  profs[%d] = %s",num,profs[num].toLocal8Bit().constData());
		KConfigGroup grp=conf->group(profs[num-1]);
		pr.data[num].deleted=FALSE;
		pr.data[num].changed=FALSE;
// 		pr.data[num].group=*it; old impl
		pr.data[num].group=profs[num-1];
// 		pr.data[num].Name=grp.readEntry("profile name",*it); old impl
		pr.data[num].Name=grp.readEntry("profile name",profs[num-1]);
// 		qWarning("GwenRename::readProfiles()  --  profile[%d] name = %s",num,pr.data[num].Name.toLocal8Bit().constData());
		pr.data[num].specName=grp.readEntry("specified name","");
		pr.data[num].origModif=grp.readEntry("original modifier",-1);
		pr.data[num].useOrigName=grp.readEntry("use original name",TRUE);
		pr.data[num].useNumeric=grp.readEntry("use numeric sorting",FALSE);
		pr.data[num].counterActive=grp.readEntry("use counter",TRUE);
// 		qWarning("pr.data[num].counterActive = %d -- false = %d",pr.data[num].counterActive,false);
		pr.data[num].digits=grp.readEntry("counter digits",3);
		pr.data[num].start=grp.readEntry("counter start",1);
		pr.data[num].step=grp.readEntry("counter step",1);
		pr.data[num].sameNum=grp.readEntry("counter same number",FALSE);
		pr.data[num].allow=grp.readEntry("counter relaxed",FALSE);
		pr.data[num].shuffle=grp.readEntry("counter shuffle",FALSE);
		pr.data[num].newExt=grp.readEntry("new extension","");
		pr.data[num].extModif=grp.readEntry("extension modifier",-1);
		pr.data[num].useOrigExt=grp.readEntry("use original extension",TRUE);
		pr.data[num].showAll=grp.readEntry("show all",FALSE);
		pr.data[num].prefix=grp.readEntry("prefix","");
		pr.data[num].suffix=grp.readEntry("suffix","");
// 		pr.data[num].prof=(*it).remove("Profile").toInt(&ok); old impl
		pr.data[num].prof=(profs[num-1]).remove("Profile").toInt(&ok); // get 1 from Profile1, 2 from Profile2 etc.
		pr.data[num].useCompoundExt=grp.readEntry("use compound extensions",FALSE);
		pr.data[num].convSpaceToUnder=grp.readEntry("convert to underscore",FALSE);
		pr.data[num].convSpaceToDash=grp.readEntry("convert to dash",FALSE);
		pr.data[num].convUnderToSpace=grp.readEntry("convert underscore to space",FALSE);
		pr.data[num].convDashToSpace=grp.readEntry("convert dash to space",FALSE);
// 		pr.data[num].specName=conf->readEntry("specified name",QString::null);
// 		pr.data[num].origModif=conf->readNumEntry("original modifier",-1);
// 		pr.data[num].useOrigName=conf->readBoolEntry("use original name",TRUE);
// 		pr.data[num].useNumeric=conf->readBoolEntry("use numeric sorting",FALSE);
// 		pr.data[num].counterActive=conf->readBoolEntry("use counter",TRUE);
// 		pr.data[num].digits=conf->readNumEntry("counter digits",3);
// 		pr.data[num].start=conf->readNumEntry("counter start",1);
// 		pr.data[num].step=conf->readNumEntry("counter step",1);
// 		pr.data[num].sameNum=conf->readBoolEntry("counter same number",FALSE);
// 		pr.data[num].allow=conf->readBoolEntry("counter relaxed",FALSE);
// 		pr.data[num].shuffle=conf->readBoolEntry("counter shuffle",FALSE);
// 		pr.data[num].newExt=conf->readEntry("new extension",QString::null);
// 		pr.data[num].extModif=conf->readNumEntry("extension modifier",-1);
// 		pr.data[num].useOrigExt=conf->readBoolEntry("use original extension",TRUE);
// 		pr.data[num].showAll=conf->readBoolEntry("show all",FALSE);
// 		pr.data[num].prefix=conf->readEntry("prefix",QString::null);
// 		pr.data[num].suffix=conf->readEntry("suffix",QString::null);
// 		pr.data[num].prof=(*it).remove("Profile").toInt(&ok);
// 		pr.data[num].useCompoundExt=conf->readBoolEntry("use compound extensions",FALSE);
// 		pr.data[num].convSpaceToUnder=conf->readBoolEntry("convert to underscore",FALSE);
// 		pr.data[num].convSpaceToDash=conf->readBoolEntry("convert to dash",FALSE);
// 		pr.data[num].convUnderToSpace=conf->readBoolEntry("convert underscore to space",FALSE);
// 		pr.data[num].convDashToSpace=conf->readBoolEntry("convert dash to space",FALSE);
	}
// 	qWarning("  --  done  --  ");
	return pr.numOfProfiles;
}
//================================
void GwenRename::clearDeletedProfiles( KConfig *conf ){
	for(int i=1;i<pr.numOfProfiles;i++){
		KConfigGroup grp=conf->group(QString("Profile%1").arg(pr.data[i].prof));
// 		if(pr.data[i].deleted) conf->deleteGroup(QString("Profile%1").arg(pr.data[i].prof),TRUE,FALSE); old impl
		if(pr.data[i].deleted) grp.deleteGroup();
	}
}
//================================
int GwenRename::getDeletedProfile(){
	for(int i=1;i<pr.numOfProfiles;i++) if(pr.data[i].deleted) return i;
	return -1;
}
//================================
int GwenRename::getFreeProfileNum(){
	int max=0;
	for(int i=1;i<pr.numOfProfiles-1;i++) if(pr.data[i].prof>max) max=pr.data[i].prof;
	max++;
	return max;
}
//================================
bool GwenRename::dublicateElement( QString tmp ){
	int i;
	int limit;
	if(pr.inRename) limit=cmbProfile->count();
	else limit=cmbProfile->count()-1;
	for(i=0;i<pr.numOfProfiles;i++){
		if(!pr.data[i].deleted){
			if(tmp==pr.data[i].Name && !pr.data[i].renaming) return TRUE;
		}
	}
	return FALSE;
}
//================================
int GwenRename::getActiveProfileIndex(){
	QString a="GwenRename";
	for(int i=0;i<pr.numOfProfiles;i++){
		if(pr.active==pr.data[i].prof){
			a=pr.data[i].Name;
			break;
		}
	}
	int id=0;
	for(int i=0;i<cmbProfile->count();i++){
// 		if(a==cmbProfile->text(i)){ old impl
		if(a==cmbProfile->itemText(i)){
			id=i;
			break;
		}
	}
	return id;
}
//================================
bool GwenRename::notRevised( int id ){
	for(int i=1;i<pr.numOfProfiles;i++)
		if(pr.data[i].prof==id && !pr.data[i].deleted) return FALSE;
	return TRUE;
}
//================================
void GwenRename::cmbProfileEnter( const QString &txt ){
	pr.enteredName=txt;
}
//================================
void GwenRename::cmbProfileEnterPressed(){
}
//================================
void GwenRename::cmbProfileChanged( int ind ){
// 	if(cmbProfile->editable()){ old impl
	if(cmbProfile->isEditable()){
		if(pr.oldName.isEmpty()){
// 			cmbProfile->setCurrentItem(cmbProfile->count()-1); old impl
			cmbProfile->setCurrentIndex(cmbProfile->count()-1);
			return;
		}else{
			int i=getProfileByText(pr.oldName);
// 			cmbProfile->setCurrentItem(i); old impl
			cmbProfile->setCurrentIndex(i);
			return;
		}
	}/*else if(!chkProfile->isChecked()){
		qWarning("setting defProf (%d)",pr.defProf);
			cmbProfile->setCurrentItem(pr.defProf);
	}*/
// 	if(pr.defProf==pr.data[cmbProfile->currentItem()].prof){ old impl
	if(pr.defProf==pr.data[cmbProfile->currentIndex()].prof){
		prDefault->setEnabled(FALSE);
		prLoad->setEnabled(FALSE);
	}else{
		prDefault->setEnabled(TRUE);
		prLoad->setEnabled(TRUE);
	}
	prNew->setEnabled(TRUE);
	if(ind==0){
		prSave->setEnabled(FALSE);
		prDelete->setEnabled(FALSE);
		prEdit->setEnabled(FALSE);
	}else{
		prSave->setEnabled(TRUE);
		prDelete->setEnabled(TRUE);
		prEdit->setEnabled(TRUE);
	}
	applyProfile(ind);
}
//================================
void GwenRename::prDefaultClicked(){
	prDefault->setEnabled(FALSE);
	prLoad->setEnabled(FALSE);
	if(cmbProfile->count()==1){
		pr.defProf=0;
// 		QPixmap *pix=(QPixmap *)prDefault->pixmap(); old impl
// 		cmbProfile->changeItem(*pix,cmbProfile->text(0),0); old impl
		cmbProfile->setItemIcon(0,KIcon(ic.Icon(0)));
	}else{
		int i=getDefProfileIndex();
		cmbProfile->setItemIcon(i,KIcon());
// 		cmbProfile->changeItem(cmbProfile->text(i),i); old impl
// 		QPixmap *pix=(QPixmap *)prDefault->pixmap(); old impl
// 		i=cmbProfile->currentItem(); old impl
		i=cmbProfile->currentIndex();
// 		cmbProfile->changeItem(*pix,cmbProfile->text(i),i); old impl
		cmbProfile->setItemIcon(i,KIcon(ic.Icon(0)));
		i=getProfileByIndex(i);
		pr.defProf=pr.data[i].prof;
	}
}
//================================
void GwenRename::prDeleteClicked(){
// 	if(cmbProfile->editable()){ //renaming item old impl
	if(cmbProfile->isEditable()){ //renaming item
		for(int i=0;i<pr.numOfProfiles;i++) pr.data[i].renaming=FALSE;
		cmbProfile->setEditable(FALSE);
		fill_cmbProfile();
// 		if(pr.oldName.isEmpty()) cmbProfile->setCurrentItem(getActiveProfileIndex()); old impl
		if(pr.oldName.isEmpty()) cmbProfile->setCurrentIndex(getActiveProfileIndex());
	}else{ //new item
// 		int prevID=cmbProfile->currentItem(); old impl
		int prevID=cmbProfile->currentIndex();
		int i=getProfileByIndex(prevID);
		int def=getDefProfileIndex();
		if(i==def) pr.defProf=0;
		pr.data[i].deleted=TRUE;
		fill_cmbProfile();
// 		cmbProfile->setCurrentItem(prevID-1); old impl
		cmbProfile->setCurrentIndex(prevID-1);
	}
// 	cmbProfileChanged(cmbProfile->currentItem()); old impl
	cmbProfileChanged(cmbProfile->currentIndex());
	cmbProfile->setFocus();
}
//================================
void GwenRename::fill_cmbProfile(){
	cmbProfile->clear();
// 	QPixmap *pix=(QPixmap *)prDefault->pixmap(); old impl
	for(int i=0;i<pr.numOfProfiles;i++){
		if(!pr.data[i].deleted){
// 			qWarning("GwenRename::fill_cmbProfile() -- i=%d -- pr.numOfProfiles=%d",i,pr.numOfProfiles);
// 			if(pr.data[i].prof==pr.defProf) cmbProfile->insertItem(*pix,pr.data[i].Name); old impl
// 			else cmbProfile->insertItem(pr.data[i].Name); old impl
			
			if(pr.data[i].prof==pr.defProf) cmbProfile->insertItem(cmbProfile->count(),KIcon(ic.Icon(0)),pr.data[i].Name);
			else cmbProfile->insertItem(cmbProfile->count(),pr.data[i].Name);
			if(pr.active==pr.data[i].prof){
// 				cmbProfile->setCurrentItem(i); old impl
				cmbProfile->setCurrentIndex(i);
				applyProfile(i);
			}
		}
	}
}
//================================
void GwenRename::prEditClicked(){
	pr.inRename=TRUE;
//	cmbProfile->setInsertionPolicy(QComboBox::AfterCurrent);
// 	cmbProfile->setInsertionPolicy(QComboBox::AtBottom); old impl
	cmbProfile->setInsertPolicy(QComboBox::InsertAtBottom);
	prNew->setEnabled(FALSE);
	prEdit->setEnabled(FALSE);
	prDelete->setEnabled(FALSE);
	prDefault->setEnabled(FALSE);
	prLoad->setEnabled(FALSE);
	cmbProfile->setEditable(TRUE);
	QLineEdit * lin=cmbProfile->lineEdit();
	lin->home(FALSE); lin->end(TRUE);
// 	pr.data[getProfileByIndex(cmbProfile->currentItem())].renaming=TRUE; old impl
	pr.data[getProfileByIndex(cmbProfile->currentIndex())].renaming=TRUE;
	pr.oldName=cmbProfile->currentText();
	cmbProfile->setFocus();
}
//================================
void GwenRename::prLoadClicked(){
// 	if(pr.defProf==pr.data[getProfileByIndex(cmbProfile->currentItem())].prof) return; old impl
	if(pr.defProf==pr.data[getProfileByIndex(cmbProfile->currentIndex())].prof) return;
	int i=getDefProfileIndex();
	applyProfile(i);
// 	cmbProfile->setCurrentItem(i); old impl
	cmbProfile->setCurrentIndex(i);
// 	cmbProfileChanged(cmbProfile->currentItem()); old impl
	cmbProfileChanged(cmbProfile->currentIndex());
	cmbProfile->setFocus();
}
void GwenRename::prNewClicked(){
//	pr.oldIndex=cmbProfile->currentItem();
// 	cmbProfile->setInsertionPolicy(QComboBox::AtBottom); old impl
	cmbProfile->setInsertPolicy(QComboBox::InsertAtBottom);
	prNew->setEnabled(FALSE);
	prDefault->setEnabled(FALSE);
	prEdit->setEnabled(FALSE);
	prDelete->setEnabled(TRUE);
	prSave->setEnabled(TRUE);
	cmbProfile->setEditable(TRUE);
// 	cmbProfile->insertItem(profName+getNewProfileNumber()); old impl
	cmbProfile->insertItem(cmbProfile->count(),profName+getNewProfileNumber());
// 	cmbProfile->setCurrentItem(cmbProfile->count()-1); old impl
	cmbProfile->setCurrentIndex(cmbProfile->count()-1);
	cmbProfile->setFocus();
	QLineEdit * lin=cmbProfile->lineEdit();
	lin->home(FALSE); lin->end(TRUE);
}
//================================
void GwenRename::prSaveClicked(){
// 	if(cmbProfile->editable()){ old impl
	if(cmbProfile->isEditable()){
		QString tmp;
		if(pr.enteredName.isEmpty()) tmp=cmbProfile->currentText();
		else tmp=pr.enteredName;
		pr.enteredName="";
		if(tmp.isEmpty()) return;
		int ind;
		if(dublicateElement(tmp)){
			QString m;
			m=QString(i18n("A profile named \"%1\" already exists.\nPlease select a different name for this profile")).arg(tmp);
			QLineEdit *ed=cmbProfile->lineEdit();
			ed->setText(tmp);
			KMessageBox::error(0,m,QString::null,KMessageBox::AllowLink);
			return;
		}else{
			if(pr.oldName.isEmpty()){ // new item
				int idProf;
				if((idProf=getDeletedProfile())==-1){
					idProf=pr.numOfProfiles;
					pr.numOfProfiles++;
					reAllocateConfigData(pr.numOfProfiles);
				}
		//check if reallocation was succes
				fillProfile(idProf);
				pr.data[idProf].prof=getFreeProfileNum();
				pr.active=pr.data[idProf].prof;
				pr.data[idProf].deleted=FALSE;
				pr.data[idProf].renaming=FALSE;
				pr.data[idProf].changed=TRUE;
			}else{ // renaming
				ind=getProfileByText(pr.oldName);
				pr.data[ind].deleted=FALSE;
				pr.data[ind].renaming=FALSE;
				if(pr.oldName==tmp) pr.data[ind].changed=FALSE;
				else{
					pr.data[ind].changed=TRUE;
					pr.data[ind].Name=tmp;
				}
				pr.oldName=QString::null;
			}
			fill_cmbProfile();
		}
		cmbProfile->setEditable(FALSE);
	}else{
// 		if(cmbProfile->currentItem()==0) return; old impl
		if(cmbProfile->currentIndex()==0) return;
// 		int prof=getProfileByIndex( cmbProfile->currentItem()); old impl
		int prof=getProfileByIndex( cmbProfile->currentIndex());
		fillProfile(pr.data[prof].prof);
		pr.data[prof].changed=TRUE;
		pr.data[prof].deleted=FALSE;
		pr.data[prof].renaming=FALSE;
	}
// 	cmbProfileChanged( cmbProfile->currentItem() ); old impl
	cmbProfileChanged( cmbProfile->currentIndex() );
	cmbProfile->setFocus();
}
//================================
bool GwenRename::reAllocateConfigData( int items ){
	if(items<=pr.items) return TRUE;
	config_data *tmp;
	tmp=new config_data[items];
	if(tmp==NULL) exitError(1);
	for(int i=0;i<pr.numOfProfiles-1;i++){
		tmp[i].group=pr.data[i].group;
		tmp[i].Name=pr.data[i].Name;
		tmp[i].prof=pr.data[i].prof;
		tmp[i].changed=pr.data[i].changed;
		tmp[i].deleted=pr.data[i].deleted;
		tmp[i].renaming=pr.data[i].renaming;
		tmp[i].specName=pr.data[i].specName;
		tmp[i].origModif=pr.data[i].origModif;
		tmp[i].useOrigName=pr.data[i].useOrigName;
		tmp[i].digits=pr.data[i].digits;
		tmp[i].start=pr.data[i].start;
		tmp[i].step=pr.data[i].step;
		tmp[i].sameNum=pr.data[i].sameNum;
		tmp[i].allow=pr.data[i].allow;
		tmp[i].shuffle=pr.data[i].shuffle;
		tmp[i].newExt=pr.data[i].newExt;
		tmp[i].extModif=pr.data[i].extModif;
		tmp[i].useOrigExt=pr.data[i].useOrigExt;
		tmp[i].showAll=pr.data[i].showAll;
		tmp[i].prefix=pr.data[i].prefix;
		tmp[i].suffix=pr.data[i].suffix;
		tmp[i].counterActive=pr.data[i].counterActive;
		tmp[i].convSpaceToUnder=pr.data[i].convSpaceToUnder;
	}
	delete [] pr.data;
	pr.data=tmp;
	return TRUE;
}
//================================
void GwenRename::fillProfile( int item ){
	pr.data[item].Name=cmbProfile->currentText();
	pr.data[item].changed=FALSE;
	pr.data[item].deleted=FALSE;
	pr.data[item].renaming=FALSE;
    // Name group
	pr.data[item].specName=rName->currentText();
	pr.data[item].useOrigName=nOriginal->isChecked();
	int modif=-1;
	if(nLCase->isChecked()) modif=0;
	else if(nUCase->isChecked()) modif=1;
	else if(nFCap->isChecked()) modif=2;
	else if(nSCap->isChecked()) modif=3;
	pr.data[item].origModif=modif;
	pr.data[item].useOrigName=nOriginal->isChecked();
	pr.data[item].useNumeric=sort->isChecked();
	pr.data[item].counterActive=countEnable->isChecked();
	pr.data[item].convSpaceToUnder=spaceToUnder->isChecked();
	pr.data[item].convSpaceToDash=spaceToDash->isChecked();
	pr.data[item].convUnderToSpace=underToSpace->isChecked();
	pr.data[item].convDashToSpace=dashToSpace->isChecked();
    // Counter group
	pr.data[item].digits=rDigits->value();
	pr.data[item].start=rStart->value();
	pr.data[item].step=rStep->value();
	pr.data[item].sameNum=rWidth->isChecked();
	pr.data[item].allow=rAllow->isChecked();
	pr.data[item].shuffle=rShuffle->isChecked();
    // Extension group
	pr.data[item].newExt=rExt->currentText();
	modif=-1;
	if(rLExt->isChecked()) modif=0;
	else if(rUExt->isChecked()) modif=1;
	pr.data[item].extModif=modif;
	pr.data[item].useOrigExt=rSelExt->isChecked();
	pr.data[item].useCompoundExt=chkFullExt->isChecked();
    // Misc group
	pr.data[item].showAll=rShow->isChecked();
	pr.data[item].prefix=nPref->currentText();
	pr.data[item].suffix=nSuf->currentText();
}
/////////////////////////////////////////////////////////////
//
//
//	End of Profiles
//
//
/////////////////////////////////////////////////////////////


//================================
void GwenRename::pTimeClicked(){
// 	historyIndex=TS1_H_INDEX; old impl
	historyIndex=FIRST_TIMESTAMP_HISTORY_INDEX;
	tFormatDate=nPref->currentText();
	getFormatParts(0);
	timeStamp *tS=new timeStamp(this,&ic);
// 	if(tS->exec()) nPref->setCurrentText(tFormatBefore+tFormatDate+tFormatAfter); old impl
// 	qWarning("nPref->currentIndex() = %s", nPref->currentIndex());
	if(tS->exec()){
		if(nPref->count()>0)
			nPref->setItemText(nPref->currentIndex(),tFormatBefore+tFormatDate+tFormatAfter);
		else
			nPref->insertItem(0,tFormatBefore+tFormatDate+tFormatAfter);
	}
	delete tS;
	nPref->setFocus();
}
//================================
void GwenRename::sTimeClicked(){
// 	historyIndex=TS2_H_INDEX; old impl
	historyIndex=SECOND_TIMESTAMP_HISTORY_INDEX;
	tFormatDate=nSuf->currentText();
	getFormatParts(1);
	timeStamp *tS=new timeStamp(this,&ic);
// 	if(tS->exec()) nSuf->setCurrentText(tFormatBefore+tFormatDate+tFormatAfter); old impl
	if(tS->exec()){
		if(nSuf->count()>0)
			nSuf->setItemText(nPref->currentIndex(),tFormatBefore+tFormatDate+tFormatAfter);
		else
			nSuf->insertItem(0,tFormatBefore+tFormatDate+tFormatAfter);
	}
	delete tS;	
	nSuf->setFocus();
}

/////////////////////////////////////////////////////////////
//
//
//	Space manipulation
//
//
/////////////////////////////////////////////////////////////
void GwenRename::underToSpaceClicked(){
	updateViewEnabled=false;
	spaceToUnder->setChecked(FALSE);
	spaceToDash->setChecked(FALSE);
	updateNameView();
	updateViewEnabled=true;
	updateView();
}


void GwenRename::dashToSpaceClicked(){
	updateViewEnabled=false;
	spaceToUnder->setChecked(FALSE);
	spaceToDash->setChecked(FALSE);
	updateNameView();
	updateViewEnabled=true;
	updateView();
}


void GwenRename::spaceToUnderClicked(){
	updateViewEnabled=false;
    if(spaceToUnder->isChecked())
			spaceToDash->setChecked(FALSE);
		underToSpace->setChecked(FALSE);
		dashToSpace->setChecked(FALSE);
		updateNameView();
		updateViewEnabled=true;
		updateView();
}


void GwenRename::spaceToDashClicked(){
		updateViewEnabled=false;
    if(spaceToDash->isChecked())
			spaceToUnder->setChecked(FALSE);
		underToSpace->setChecked(FALSE);
		dashToSpace->setChecked(FALSE);
		updateNameView();
		updateViewEnabled=true;
		updateView();
}

/////////////////////////////////////////////////////////////
//
//
//	End of Space manipulation
//
//
/////////////////////////////////////////////////////////////









//================================
// void GwenRename::nLCaseClicked( int state ){ old impl
void GwenRename::nLCaseClicked( bool state ){
// 	if(state!=0){ old impl
	if(state){
		nUCase->setChecked(FALSE);
		nSCap->setChecked(FALSE);
		nFCap->setChecked(FALSE);
	}
}
//================================
// void GwenRename::nUCaseClicked( int state ){ old impl
void GwenRename::nUCaseClicked( bool state ){
// 	if(state!=0){ old impl
	if(state){
		nLCase->setChecked(FALSE);
		nFCap->setChecked(FALSE);
		nSCap->setChecked(FALSE);
	}
}
//================================
// void GwenRename::nSCapClicked( int state ){ old impl
void GwenRename::nSCapClicked( bool state ){
// 	if(state!=0){ old impl
	if(state){
		nFCap->setChecked(FALSE);
		nLCase->setChecked(FALSE);
		nUCase->setChecked(FALSE);
	}
}
//================================
// void GwenRename::nFCapClicked( int state ){ old impl
void GwenRename::nFCapClicked( bool state ){
// 	if(state!=0){ old impl
	if(state){
		nSCap->setChecked(FALSE);
		nLCase->setChecked(FALSE);
		nUCase->setChecked(FALSE);
	}
}
//================================
void GwenRename::nOriginalClicked(int state){
	if(state==0){
		nLCase->setEnabled(FALSE);
		nUCase->setEnabled(FALSE);
		nFCap->setEnabled(FALSE);
		nSCap->setEnabled(FALSE);
		nSpecify->setChecked(TRUE);
		if((rStep->value()!=0 && rStep->isEnabled() && nSpecify->isChecked()) && rStart->isEnabled()){
			rAllow->setEnabled(TRUE);
			//qWarning("GwenRename::nOriginalClicked(int state) rAllow->setEnabled(TRUE)");
		}else rAllow->setEnabled(FALSE);
	}
	else{
		nLCase->setEnabled(TRUE);
		nUCase->setEnabled(TRUE);
		nFCap->setEnabled(TRUE);
		nSCap->setEnabled(TRUE);
		nSpecify->setChecked(FALSE);
		rAllow->setEnabled(FALSE);
		nOriginal->setFocus();
	}
}
//================================
void GwenRename::nSpecifyClicked(int state){
	if(state==0){
		rName->setEnabled(FALSE);
// 		clearrName->setEnabled(FALSE);
		nOriginal->setChecked(TRUE);
		rAllow->setEnabled(FALSE);
		partName->setEnabled(FALSE);
	}else{
		rName->setEnabled(TRUE);
// 		clearrName->setEnabled(TRUE);
		nOriginal->setChecked(FALSE);
		partName->setEnabled(TRUE);
		if((rStep->value()!=0 && rStep->isEnabled()) && rStart->isEnabled()){
			rAllow->setEnabled(TRUE);
			//qWarning("GwenRename::nSpecifyClicked(int state) rAllow->setEnabled(TRUE)");
		}else rAllow->setEnabled(FALSE);
		rName->setFocus();
	}
	updateNameView();
}
//================================
void GwenRename::nSufChanged(){
	updateViewEnabled=false;
	if(!nSuf->currentText().isEmpty()){
		tFormatDate=nSuf->currentText();
		// Check fot date code
		timeStamp *bStamp=new timeStamp;
		if(bStamp->checkFormat(nSuf->currentText())){
			useTimeStamp(1);
		}else{
			for(int i=0;i<g.numOfFiles;i++){
				g.ren[g.getSorted(i)].Suffix=nSuf->currentText();
			}
		}
		delete bStamp;
	}else{
		for(int i=0;i<g.numOfFiles;i++) g.ren[g.getSorted(i)].Suffix="";
	}
	updateNameView();
	updateViewEnabled=true;
	updateView();
}

//================================
// void GwenRename::rLExtClicked( int state ){ old impl
void GwenRename::rLExtClicked( bool state ){
// 	if(state!=0) rUExt->setChecked(FALSE); old impl
	if(state) rUExt->setChecked(FALSE);
	updateExtView();
	rLExt->setFocus();
}

//================================
void GwenRename::rShowClicked( int val ){
	int pix_valid=0,pix_invalid=1;
// // This code will make all selected icons to turn to "invalid" in case of conflict
// // Otherwise only the conflicting item will have an "invalid" icon
// // 	if(getSameNewName()!=-1){
// // 		pix_valid=7;
// // 		pix_invalid=7;
// // 	}
	bool VisibleItemSet=FALSE;
	View->clear();
 QList<QTreeWidgetItem *> items;
// 	KListViewItem * itemVisible=0; old impl
	QTreeWidgetItem* itemVisible=0;
// 	KListViewItem * item = new KListViewItem( View, 0 ); old impl
		QTreeWidgetItem * item = new QTreeWidgetItem( View, 0 );
	if(rStep->value()<0 || (sort->isChecked() && sort->isEnabled()))
// 		View->setSorting(2); old impl
	View->sortByColumn(2,Qt::AscendingOrder);
	else
// 		View->setSorting(1); old impl
	View->sortByColumn(2,Qt::AscendingOrder);
	for(int i=0,k=0;i<g.numOfFiles;i++){
		if(g.ren[g.getSorted(i)].selected){
			QString firstColumn, secondColumn;
// 			if(k!=0) item = new KListViewItem( View, item ); old impl
			if(k!=0) item = new QTreeWidgetItem(View , item);
			k++;
			if(g.ren[g.getSorted(i)].isDir){
					firstColumn="/"+g.ren[g.getSorted(i)].oldName;
					secondColumn="/"+g.ren[g.getSorted(i)].newName+g.ren[g.getSorted(i)].Counter+g.ren[g.getSorted(i)].newSuffix;
			}else{
				firstColumn=g.files[g.getSorted(i)].fileName();
				if(!g.ren[g.getSorted(i)].newExtension.isEmpty())
					secondColumn=g.ren[g.getSorted(i)].newName+g.ren[g.getSorted(i)].Counter+g.ren[g.getSorted(i)].newSuffix+"."+g.ren[g.getSorted(i)].newExtension;
				else
					secondColumn=g.ren[g.getSorted(i)].newName+g.ren[g.getSorted(i)].Counter+g.ren[g.getSorted(i)].newSuffix;
			}
// 
// 		// fix icon
			if(g.ren[g.getSorted(i)].newName+g.ren[g.getSorted(i)].Counter+g.ren[g.getSorted(i)].newSuffix+"."+g.ren[g.getSorted(i)].newExtension==g.ren[g.getSorted(i)].oldName+"."+g.ren[g.getSorted(i)].oldExtension){
// 				qWarning("setting pix_invalid for %d",i);
				g.ren[g.getSorted(i)].iconID=pix_invalid;
			}
// 			else if(g.ren[g.getSorted(i)].newFileName==g.path() + "/" || g.ren[g.getSorted(i)].newFileName==g.path() + "/." + g.ren[g.getSorted(i)].newExtension){
			else if(g.ren[g.getSorted(i)].newFileName==g.path() + "/" || g.ren[g.getSorted(i)].newFileName==g.path() + "/." + g.ren[g.getSorted(i)].newExtension){
// 				qWarning("setting pix 7  for %d",i);
				g.ren[g.getSorted(i)].iconID=7;
			}
			else
				g.ren[g.getSorted(i)].iconID=pix_valid;
			noDoubleNewName();
		// load them to the list
			item->setText( 1, firstColumn);
			item->setText( 2, secondColumn);
			if(g.ren[g.getSorted(i)].iconID!=-1){
// 				g.ren[g.getSorted(i)].iconID=icon;
// 				item->setPixmap(0,ic.Icon(g.ren[g.getSorted(i)].iconID)); old impl
				item->setIcon(0,KIcon(ic.Icon(g.ren[g.getSorted(i)].iconID)));
				item->setText( 0," ");
	
//  				qWarning("  --  i = %d, g.getSorted(i) = %d, iconID: %d", i, g.getSorted(i), g.ren[g.getSorted(i)].iconID);
			}/*else{
				item->setPixmap(0,null);
				item->setText( 0," ");
 				qWarning("  --  i = %d, g.getSorted(i) = %d, iconID: %d", i, g.getSorted(i), g.ren[g.getSorted(i)].iconID);
			}*/
			if(!VisibleItemSet){
				itemVisible=item;
				VisibleItemSet=TRUE;
			}
		}else{
			if(val!=0){
// 				if(k!=0) item = new KListViewItem( View, item ); old impl 
 				if(k!=0) item = new QTreeWidgetItem( View, item );
				k++;
				QString toItem1;
				toItem1=g.files[g.getSorted(i)].fileName();
				if(g.ren[g.getSorted(i)].isDir)
					toItem1.prepend("/");
 				item->setText( 1, toItem1);
 				item->setText( 2, toItem1);
			}
		}
	}
// 	View->resizeColumnToContents(1);
	
	
// 	fixViewGeometry(1); old impl  FIX ME!!!
// 	View->ensureItemVisible(itemVisible); old impl  FIX ME!!!
	View->scrollToItem(itemVisible);
}

//================================
int GwenRename::noDoubleNewName(){
	QString thisItem;
	int res=-1;
	for (int i=0;i<g.numOfFiles;i++)
		if(g.ren[i].selected){ // item is selected for remaming
// 				firstColumn=g.files[g.getSorted(i)].fileName();
				if(!g.ren[i].newExtension.isEmpty())
					thisItem=g.ren[i].newName+g.ren[i].Counter+g.ren[i].newSuffix+"."+g.ren[i].newExtension;
				else
					thisItem=g.ren[g.getSorted(i)].newName+g.ren[i].Counter+g.ren[i].newSuffix;
				for(int k=0;k<g.numOfFiles;k++){
					if(!g.ren[k].selected){ // item is NOT selected for remaming
						if(thisItem==g.files[k].fileName()){
// 								qWarning("---------------");
// 								qWarning("%s  -  %s",thisItem.toLocal8Bit().constData(),g.files[k].fileName().toLocal8Bit().constData());
// 								qWarning("setting 7 for i = %d, with k = %d",i,k);
								g.ren[i].iconID=7;
								res=1;
								break;
						}
					}
				}
		}
	return res;
}

//================================
void GwenRename::fixViewGeometry( int mode ){
// 	for(int i=0;i<View->header()->count();i++) View->header()->setClickEnabled( TRUE, i);
// 	View->setAllColumnsShowFocus( TRUE );
// 	View->setShowSortIndicator(TRUE);
// 	View->setResizeMode( KListView::LastColumn );
// 	if(mode==0){
// 	}else{
// 	}
// 	View->setColumnWidth(0,col0);
// 	View->setColumnWidth(1,300);
}

//================================
// void GwenRename::rUExtClicked( int state ){ old impl
void GwenRename::rUExtClicked( bool state ){
// 	if(state!=0) rLExt->setChecked(FALSE); old impl
	if(state) rLExt->setChecked(FALSE);
	updateExtView();
	rUExt->setFocus();
}

//================================
void GwenRename::sortToggled( bool state ){
	updateViewEnabled=false;
	if(g.setSortValue(state)==-1) exitError(1);
	updateViewEnabled=true;
	updateView();
}
//================================
//       LED manipulation
//================================
void GwenRename::handleLed1(){
	if(kLed1->state()==KLed::On){
		hiddenWidgetSets++;
		spL1->changeSize(21,1,QSizePolicy::Fixed,QSizePolicy::Minimum);
		kLed1->setState(KLed::Off);
		kLed1->setLook(KLed::Sunken);
		groupBox3->hide();
		groupBox4->hide();
		lblLed1->show();
		spL1->invalidate();
	}else{
		if(smallScreen && hiddenWidgetSets==1) handleLed2();
		hiddenWidgetSets--;
		spL1->changeSize(21,1,QSizePolicy::Fixed,QSizePolicy::MinimumExpanding);
		kLed1->setState(KLed::On);
		kLed1->setLook(KLed::Raised);
		lblLed1->hide();
		groupBox3->show();
		groupBox4->show();
		spL1->invalidate();
		nOriginal->setFocus();
	}
}
//================================
void GwenRename::handleLed2(){
	if(kLed2->state()==KLed::On){
		hiddenWidgetSets++;
		spL2->changeSize(21,1,QSizePolicy::Fixed,QSizePolicy::Minimum);
		kLed2->setState(KLed::Off);
		kLed2->setLook(KLed::Sunken);
		groupBox5->hide();
		groupBox6->hide();
		countBox->hide();
		lblLed2->show();
		spL2->invalidate();
	}else{
		if(smallScreen && hiddenWidgetSets==1) handleLed3();
		hiddenWidgetSets--;
		spL2->changeSize(21,1,QSizePolicy::Fixed,QSizePolicy::MinimumExpanding);
		kLed2->setState(KLed::On);
		kLed2->setLook(KLed::Raised);
		lblLed2->hide();
		groupBox5->show();
		groupBox6->show();
		countBox->show();
		spL2->invalidate();
		sort->setFocus();
	}
}
//================================
void GwenRename::handleLed3(){
	if(kLed3->state()==KLed::On){
		hiddenWidgetSets++;
		spL3->changeSize(21,1,QSizePolicy::Fixed,QSizePolicy::Minimum);
		kLed3->setState(KLed::Off);
		kLed3->setLook(KLed::Sunken);
		extBox->hide();
		btngrpProfiles->hide();
		lblLed3->show();
		spL3->invalidate();
	}else{
		if(smallScreen && hiddenWidgetSets==1) handleLed1();
		hiddenWidgetSets--;
		kLed3->setState(KLed::On);
		spL3->changeSize(21,1,QSizePolicy::Fixed,QSizePolicy::MinimumExpanding);
		kLed3->setLook(KLed::Raised);
		lblLed3->hide();
		extBox->show();
		btngrpProfiles->show();
		spL3->invalidate();
		if(rSelExt->isEnabled()) rSelExt->setFocus();
		else if(chkProfile->isEnabled()) chkProfile->setFocus();
	}
}
//================================
//    End of LED manipulation
//================================



void GwenRename::viewDoubleClicked( QTreeWidgetItem * item , int column ){
	if(item){
		if(item->text(1).isNull()) return;
// 		if(item->pixmap(0)) old impl
// 		if(item->icon(0).isNull()){ old impl
		if(item->text(0).isEmpty()) // not selected items have ' ' as text in column 0
			AddToList();
		else
			RemoveFromList();
	}
}


void GwenRename::AddToList(){
	theErrorMessage=2;
	reFixList(true,true);
}


void GwenRename::RemoveFromList(){
	theErrorMessage=3;
	reFixList(false,true);
}


void GwenRename::reFixList(bool mode, bool calculateType){
	int i=0,found=-1;
	bool noNeedToManipulate;
	QString readName,onlyReadName,fullReadName,msg;
// 	QListViewItemIterator it( View ); old impl
	QTreeWidgetItemIterator it( View );
	int itemsToManipulate=0;
	int itemsSkipped=0;
	if(calculateType){
		// Find first selected file and get its type
		filesSelectedType=-2;
		for(int k=0;k<g.numOfFiles;k++)
			if(g.ren[k].selected){
				filesSelectedType=g.whatType(k);
				break;
			}
		//qWarning("filesSelectedType = %d",filesSelectedType);
	}
		// if no file is selected, make type=isFile
	 //if(filesSelectedType==-2) filesSelectedType=1;
// 	qWarning("filesSelectedType = %d",filesSelectedType);
// 	for ( ; it.current(); ++it ){ old impl
	while(*it){
		noNeedToManipulate=false;
// 		readName=it.current()->text(1); old impl
		readName=(*it)->text(1);
// 		qWarning("GwenRename::reFixList  --  readName = %s",readName.toLocal8Bit().constData());
		onlyReadName=readName;
		if(onlyReadName.endsWith("/"))
			onlyReadName=onlyReadName.left(onlyReadName.length()-1);
		fullReadName=g.path()+'/'+onlyReadName;
		fullReadName.replace("//","/");
// 		if(it.current()->isSelected()){ old impl
		if((*it)->isSelected()){
			itemsToManipulate++;
//  			qWarning("GwenRename::reFixList %d. %s (%s - %s)",i,readName.toLocal8Bit().constData(),onlyReadName.toLocal8Bit().constData(),fullReadName.toLocal8Bit().constData());
			i++;
			for(int k=0;k<g.numOfFiles;k++){
//  				qWarning("--------\n%s\n%s - %s",fullReadName.toLocal8Bit().constData(),g.ren[k].oldFileName.toLocal8Bit().constData(),g.ren[k].oldName.toLocal8Bit().constData());
				if(fullReadName==g.ren[k].oldFileName){
					found=k;
// 					qWarning(" --> Item %s found as %d ",fullReadName.toLocal8Bit().constData(),k);
					if(g.ren[k].selected==mode){
//  						qWarning(" --> Item %s is selected ok...",onlyReadName.toLocal8Bit().constData());
						noNeedToManipulate=true;
//						itemsSkipped++;
					}
					break;
				}
			}
			itemsSkipped=checkItemToList(readName, found, noNeedToManipulate, mode, itemsSkipped, &msg);
		}
		++it;
	}
//  	qWarning("filesSelectedType = %d",filesSelectedType);
	filesSelectedType=-2;
	for(int k=0;k<g.numOfFiles;k++)
		if(g.ren[k].selected){
			filesSelectedType=g.whatType(k);
			break;
		}
// 		qWarning("GwenRename::reFixList  --  itemsSkipped = %d,itemsToManipulate = %d",itemsSkipped,itemsToManipulate);
		updateAfterSelection(itemsSkipped, itemsToManipulate, &msg);
}


int GwenRename::checkItemToList(QString readName, int found, bool noNeedToManipulate, bool mode, int itemsSkipped, QString * msg){
	if(found!=-1){ // normal execution
		if(!noNeedToManipulate){
			// Does item still exist?
			if(g.files[found].exists()){
				// Item still exists
				// Can I rename it?
				if(g.files[found].isWritable()){
					// Yes I can rename it...
					// Is it of wright type?
					if(g.whatType(found)==filesSelectedType || filesSelectedType==-2){
						// It is the right type
						// mark it as mode
						setNewFileData(found,mode);
						if(filesSelectedType==-2) filesSelectedType=g.whatType(found);
					}else{
						itemsSkipped++;
						if(itemsSkipped<=SHOW_ITEMS_TO_LIST_PROBLEM)
						// It cannot be renamed; inform the user
							msg->append("<li>"+QString(i18n("Item <b>%1</b> is of wrong type").arg(readName))+"</li>");
						//qWarning("Item %s is of wrong type: %d",readName.toLocal8Bit().constData(),g.whatType(found));
						setNewFileData(found,false);
					}
				}else{
					itemsSkipped++;
					if(itemsSkipped<=SHOW_ITEMS_TO_LIST_PROBLEM)
					// It cannot be renamed; inform the user
					msg->append("<li>"+QString(i18n("Item <b>%1</b> is not writable").arg(readName))+"</li>");
					//qWarning("Item %s is not writable",readName.toLocal8Bit().constData());
					setNewFileData(found,false);
				}
			}else{
					itemsSkipped++;
					if(itemsSkipped<=SHOW_ITEMS_TO_LIST_PROBLEM)
					// Item does not exist; inform the user
					msg->append("<li>"+QString(i18n("Item <b>%1</b> no longer exists").arg(readName))+"</li>");
					//qWarning("Item %s no longer exists",readName.toLocal8Bit().constData());
					setNewFileData(found,false);
			}
		}
	}else{
		KUrl url(QString("mailto:sng@hellug.gr?subject=GwenRename Selection list error&body=I have just stumbled to this error\n\nError Code = %1").arg(theErrorMessage));
// 		new KRun(url); old impl
		*msg="<p>A programming error has occurred!!!<br>This is a known error, and I'm working on it<br><br><b>GwenRename</b> will exit now so that there's no chance to loose data!!!<br><br>An email message describing this error has been prepared for you. Please send this bug report; it will help me <b>fix</b> this error.<br><br>Thank you</p>";
		KMessageBox::error(this,*msg,QString::null,KMessageBox::AllowLink);
		CancelIt();
	}
// 	qWarning("GwenRename::checkItemToList - itemsSkipped = %d",itemsSkipped);
	return itemsSkipped;
}

void GwenRename::setNewFileData( int id, bool state ){
	g.ren[id].selected=state;
	if(state)
		g.ren[id].iconID=0;
	else{
		// reset this item
		g.ren[id].newFileName=QString::null;
		g.ren[id].newTmpFileName=QString::null;
		g.ren[id].newName=QString::null;
		g.ren[id].newTmpName=QString::null;
		g.ren[id].newExtension=QString::null;
		g.ren[id].iconID=-1;
	}
}

void GwenRename::updateAfterSelection( int itemsSkipped, int itemsToManipulate, QString * msg ){
	int allSelected=0;

	if(!msg->isEmpty()){
// 		qWarning("GwenRename::updateAfterSelection - itemsSkippede = %d", itemsSkipped);
		if(itemsSkipped>=SHOW_ITEMS_TO_LIST_PROBLEM){
			msg->prepend("<p>"+i18n("The following problems occurred:")+"</p><ul>");
			msg->append("</ul><p>"+QString(i18n("(not displaying %1 more problems)").arg(itemsSkipped-SHOW_ITEMS_TO_LIST_PROBLEM))+"<br><br>"+i18n("Items present in this list will not be available for renaming!!!")+"</p>");
		}else{
			msg->prepend("<p>"+i18n("The following problems occurred:")+"</p><ol>");
			msg->append("</ol><p>"+i18n("Items present in this list will not be available for renaming!!!")+"</p>");
		}
		KMessageBox::information(this,*msg,QString::null,QString::null,KMessageBox::AllowLink);
// 			msg="<p>"+i18n("The following problems occurred:")+"</p><ul>"+msg+"</ul><p>"+QString(i18n("(not displaying %1 more problems)").arg(itemsToManipulate-10))+"<br><br>"+i18n("Items present in this list will not be available for renaming!!!")+"</p>";
// 		else
// 			msg="<p>"+i18n("The following problems occurred:")+"</p><ol>"+msg+"</ol><p>"+i18n("Items present in this list will not be available for renaming!!!")+"</p>";
// 		KMessageBox::information(this,msg,QString::null,QString::null,KMessageBox::AllowLink);

	}
	
	if(filesSelectedType==2){
		if(rStart->isEnabled()){
			rShuffle->setEnabled(TRUE);
			if(rShuffle->isChecked()){
				reRandomize->setEnabled(TRUE);
			}
		}else{
			rShuffle->setEnabled(FALSE);
			reRandomize->setEnabled(FALSE);
		}
		rSelExt->setEnabled(FALSE);
		rLExt->setEnabled(FALSE);
		rUExt->setEnabled(FALSE);
		extBox->setEnabled(FALSE);
	}else{
		rShuffle->setEnabled(FALSE);
		reRandomize->setEnabled(FALSE);
		rSelExt->setEnabled(TRUE);
		rLExt->setEnabled(TRUE);
		rUExt->setEnabled(TRUE);
		extBox->setEnabled(TRUE);
	}
	for(int k=0;k<g.numOfFiles;k++)
		if(g.ren[k].selected)
			g.resetFileName(k);
	//
	//
	// Do I need that check?
	//
// 	qWarning("itemsSkipped=%d , itemsToManipulate=%d",itemsSkipped,itemsToManipulate);
	
	if(itemsSkipped<itemsToManipulate || ( itemsSkipped+itemsToManipulate==0 )){
		updateViewEnabled=false;
		g.resetHasbeenSorted();
		sortToggled(sort->isChecked());
		for(int k=0;k<g.numOfFiles;k++)
			if(g.ren[k].selected) allSelected++;
		lSelected->setText(QString(i18n("%1/%2 items selected")).arg(allSelected).arg(g.numOfFiles));
		if(allSelected==0) filesSelectedType=-2;
		if(allSelected==g.numOfFiles) rShow->setEnabled(false);
		else rShow->setEnabled(true);
		AdjustExtension();
		updateNameView();
		updateExtView();
		updateCounterView();
		updateViewEnabled=true;
		updateView();
	}
}

void GwenRename::contextMenuRequested(QPoint point){
	QTreeWidgetItem * it;
	if((it=View->itemAt(point))){
		QAction* act;
		popM= new KMenu();

// 	popM->addTitle(KIcon(ic.Icon(0)),"aa aaaa");
// 	popM->addAction("1. Try this");
// 	popM->addSeparator();
// 	popM->addTitle(KIcon(ic.Icon(1)),"bb bbbb");
	
	
	if(lSelected->text().startsWith("0") && !rShow->isChecked()){
		popM->addTitle(i18n("Help"));
// 		popM->addItem(ic.Icon(15),i18n("Show help"),this,SLOT(showHelp())); old impl
		act=popM->addAction(ic.Icon(15),i18n("Show help"));
		connect(act,SIGNAL(triggered()), this, SLOT(showHelp()));
	}else{
		popM->addTitle(i18n("List management"));
//		if (rShow->isChecked())
// 			addToListID=popM->addItem(ic.Icon(6),i18n("Add to list"),this,SLOT(AddToList())); old impl
		act=popM->addAction(ic.Icon(6),i18n("Add to list"));
		connect(act,SIGNAL(triggered()), this, SLOT(AddToList()));
// 		popM->addItem(ic.Icon(7),i18n("Remove from list"),this,SLOT(RemoveFromList())); old impl
		act=popM->addAction(ic.Icon(7),i18n("Remove from list"));
		connect(act,SIGNAL(triggered()), this, SLOT(RemoveFromList()));
		popM->addSeparator();
		//if (rShow->isChecked())
// 			popM->addItem(ic.Icon(17),i18n("Invert list"),this,SLOT(InvertList())); old impl
		act=popM->addAction(ic.Icon(17),i18n("Invert list"));
		connect(act,SIGNAL(triggered()), this, SLOT(InvertList()));
// 		popM->addItem(ic.Icon(8),i18n("Create list from selection"),this,SLOT(ListFromSelection())); old impl
		act=popM->addAction(ic.Icon(8),i18n("Create list from selection"));
		connect(act,SIGNAL(triggered()), this, SLOT(ListFromSelection()));
		if (rShow->isChecked()){
			act=popM->addTitle(i18n("Selection management"));
// 			popM->addItem(ic.Icon(13),i18n("All items"),this,SLOT(mnuSelectAll())); old impl
			act=popM->addAction(ic.Icon(13),i18n("All items"));
			connect(act,SIGNAL(triggered()), this, SLOT(mnuSelectAll()));
// 			itemsOfSelectedType=popM->addItem(ic.Icon(12),i18n("All items of selected type"),this,SLOT(mnuSelectByType())); old impl
			act=popM->addAction(ic.Icon(12),i18n("All items of selected type"));
			connect(act,SIGNAL(triggered()), this, SLOT(mnuSelectByType()));
// 			popM->addItem(ic.Icon(17),i18n("Invert current selection"),this,SLOT(mnuInvertSelection())); old impl
			act=popM->addAction(ic.Icon(17),i18n("Invert current selection"));
			connect(act,SIGNAL(triggered()), this, SLOT(mnuInvertSelection()));
// 			popM->addItem(ic.Icon(8),i18n("Create selection from list"),this,SLOT(SelectionFromList())); old impl
			act=popM->addAction(ic.Icon(8),i18n("Create selection from list"));
			connect(act,SIGNAL(triggered()), this, SLOT(SelectionFromList()));
// 			popM->addItem(ic.Icon(18),i18n("Items containing a string"),this,SLOT(mnuShowSelectionDialog())); old impl
			act=popM->addAction(ic.Icon(18),i18n("Items containing a string"));
			connect(act,SIGNAL(triggered()), this, SLOT(mnuShowSelectionDialog()));
		}
		popM->addTitle(i18n("Help"));
// 		popM->addItem(ic.Icon(15),i18n("Show help"),this,SLOT(showHelp())); old impl
		act=popM->addAction(ic.Icon(15),i18n("Show help"));
		connect(act,SIGNAL(triggered()), this, SLOT(showHelp()));
	}
	
	popM->exec(View->mapToGlobal(point));
	delete popM;
	}
}

void GwenRename::showHelp(){
	KRun::runCommand(QString("khelpcenter \"help:/gwenrename/main-window.html#context-menu\""),this);
}

void GwenRename::ListFromSelection(){
	setList(false);
	View->setEnabled(false);
	filesSelectedType=-2;
	theErrorMessage=4;
	reFixList(true,false);
	View->setEnabled(true);
}

void GwenRename::SelectionFromList(){
// 	QListViewItemIterator it( View ); old impl
	QTreeWidgetItemIterator it( View );
// 	for ( ; it.current(); ++it ){ old impl
		while(*it){
// 		if(it.current()->pixmap(0)) old impl
			
			
		if((*it)->text(0).isEmpty()) // not selected items have ' ' as text in column 0
// 			it.current()->setSelected(true); old impl
			(*it)->setSelected(false);
		else
// 			it.current()->setSelected(false); old impl
			(*it)->setSelected(true);
// 		View->repaintItem(it); FIX ME!!!
		++it;
	}
}

void GwenRename::InvertList(){
	int itemsToManipulate=0;
	int itemsSkipped=0;
	int filesFound=0;
	int filesSelected=0;
	int dirsFound=0;
	int dirsSelected=0;
	QString readName, msg;
	for(int k=0;k<g.numOfFiles;k++){
		if(g.whatType(k)==1)
			filesFound++;
		else
			dirsFound++;
		if(!g.ren[k].selected)
			itemsToManipulate++;
		else
			if(g.whatType(k)==1)
				filesSelected++;
			else
				dirsSelected++;
	}
// 	qWarning("filesFound = %d\ndirsFound = %d\nitemsToManipulate = %d\nfilesSelected = %d\ndirsSelected = %d",filesFound,dirsFound,itemsToManipulate,filesSelected,dirsSelected);
	if(filesSelected>0){
		if(filesFound==filesSelected){
			if(dirsFound>0)
				filesSelectedType=2;
			else
				filesSelectedType=1;
		}else
			filesSelectedType=1;
// 			return;
	}else if(dirsSelected>0){
		if(dirsFound==dirsSelected){
			if(filesFound>0)
				filesSelectedType=1;
			else
				filesSelectedType=2;
		}else
			filesSelectedType=2;
// 			return;
	}
// 	if((filesFound==filesSelected && dirsFound>0) || dirsSelected!=0)
// 		filesSelectedType=2;
// 	else if((dirsFound==dirsSelected && filesFound>0) || filesSelected!=0)
// 		filesSelectedType=1;
// 	else
// 		if(filesFound>dirsFound)
// 			filesSelectedType=1;
// 		else if(filesFound<dirsFound)
// 			filesSelectedType=2;
	for(int k=0;k<g.numOfFiles;k++){
		g.ren[k].selected=!g.ren[k].selected;
		if(g.ren[k].selected){
			readName=g.ren[k].oldFileName;
			readName.remove(QRegExp("^.*/"));
			if(g.whatType(k)==2)
				readName.prepend("/");
			theErrorMessage=1;
			itemsSkipped=checkItemToList(readName, k, false, true, itemsSkipped, &msg);
		}else
			g.ren[k].newFileName=QString::null;
	}
	updateAfterSelection(itemsSkipped, itemsToManipulate, &msg);
}

void GwenRename::setList( bool state ){
	for(int k=0;k<g.numOfFiles;k++){
		g.ren[k].selected=state;
		g.ren[k].newFileName=QString::null;
	}
}

void GwenRename::mnuSelectAll( void ){
	View->setUpdatesEnabled( false );
// 	QListViewItemIterator it( View ); old impl
	QTreeWidgetItemIterator it( View );
// 	for ( ; it.current(); ++it ){ old impl
	while(*it){
// 		it.current()->setSelected(true); old impl
		(*it)->setSelected(true);
		++it;
// 		View->repaintItem(it.current()); old impl
}
	View->setUpdatesEnabled( true );
	View->update();
}

void GwenRename::mnuSelectByType( void ){
	View->setUpdatesEnabled( false );
// 	QListViewItemIterator it( View ); old impl
	QTreeWidgetItemIterator it( View );
// 	for ( ; it.current(); ++it ){ old impl
	while(*it){
		if(filesSelectedType==1){
// 			if(it.current()->text(1).startsWith("/")) it.current()->setSelected(false); old impl
			if((*it)->text(1).startsWith("/")) (*it)->setSelected(false);
// 			else it.current()->setSelected(true); old impl
			else (*it)->setSelected(true);
		}else if(filesSelectedType==2){
// 			if(it.current()->text(1).startsWith("/")) it.current()->setSelected(true); old impl
			if((*it)->text(1).startsWith("/")) (*it)->setSelected(true);
// 			else it.current()->setSelected(false); old impl
			else (*it)->setSelected(false);
		}else{
		
		}
// 		View->repaintItem(it.current()); old impl FIX ME!!!
// 		if(it.current()->isSelected()) old impl
		if((*it)->isSelected())
// 			firstSelectedItem=it.current();old impl
			firstSelectedItem=(*it);
		++it;
	}
	View->setUpdatesEnabled( true );
	if(firstSelectedItem)
// 		View->ensureItemVisible(firstSelectedItem); old impl
		View->scrollToItem(firstSelectedItem);
	View->update();
}

void GwenRename::mnuInvertSelection( void ){
	View->setUpdatesEnabled( false );
// 	QListViewItemIterator it( View ); old impl
	QTreeWidgetItemIterator it( View );
// 	for ( ; it.current(); ++it ){ old impl
	while(*it){
// 		it.current()->setSelected(!it.current()->isSelected()); old impl
		(*it)->setSelected(!(*it)->isSelected());
// 		View->repaintItem(it.current()); old impl FIX ME!!!
// 		if(it.current()->isSelected()) old impl
		if((*it)->isSelected())
// 			firstSelectedItem=it.current(); old impl
			firstSelectedItem=(*it);
		++it;
	}
	View->setUpdatesEnabled( true );
	if(firstSelectedItem)
// 		View->ensureItemVisible(firstSelectedItem); old impl
		View->scrollToItem(firstSelectedItem);
	View->update();
}

void GwenRename::mnuShowSelectionDialog( void ){
	View->setUpdatesEnabled( false );
	//multiSelTool *tMult=new multiSelTool;
	if(! tMult){
		tMult=new multiSelect(this,&ic);
// 		tMult->lblIcon->setPixmap(ic.Icon(9));
// 		 old impltMult->eraseLocBar->setPixmap(ic.Icon(11));
		// insert current items in listbox txtSelect
// 		QListViewItemIterator it( View ); old impl
		QTreeWidgetItemIterator it( View );
// 		for ( ; it.current(); ++it ) old impl
		QStringList l;
		while(*it){
			l<<(*it)->text(1);
// 			tMult->txtSelect->insertItem(it.current()->text(1)); old impl
			++it;
		}
		tMult->txtSelect->insertItems(0,l);
// 		tMult->txtSelect->setCurrentText(""); old impl
		tMult->txtSelect->setEditText("");
	}
	if(tMult->exec()){
		makeSelectionFromString( tMult->txtSelect->currentText(), tMult->chkCaseSensitive->isChecked(), tMult->chkInvert->isChecked(), tMult->chkAdd->isChecked(), tMult->regexpContentCb->isChecked() );
		View->setUpdatesEnabled( true );
		if(firstSelectedItem)
// 			View->ensureItemVisible(firstSelectedItem); old impl
		View->scrollToItem(firstSelectedItem);
		View->update();
	}
}


void GwenRename::makeSelectionFromString( QString str, bool useCase, bool invertSelection, bool addToCurrentSelection, bool useRegExp ){
	bool found;
	Qt::CaseSensitivity cs;
	
	if(useCase) cs=Qt::CaseSensitive;
	else cs=Qt::CaseInsensitive;
	
// 	QListViewItemIterator it( View ); old impl
	QTreeWidgetItemIterator it( View );
// 	for ( ; it.current(); ++it ){ old impl
	while(*it){
		found=false;
// 		QString thisText=it.current()->text(1); old impl
		QString thisText=(*it)->text(1);
		if(useRegExp){
// 			QRegExp reg(str,useCase); old impl
			QRegExp reg(str,cs);
// 			if(reg.search(thisText)!=-1) found=true; old impl
			if(reg.indexIn(thisText)!=-1) found=true;
		}else{
// 			if(thisText.find(str,0,useCase)!=-1) found=true; old impl
			if(thisText.indexOf(str,0,cs)!=-1) found=true;
		}
			
		if(invertSelection){
			// Invert selection
			if(addToCurrentSelection){
				// remove from selection, only if found
				if(found){
// 					it.current()->setSelected(false); old impl
					(*it)->setSelected(false);
// 					View->repaintItem(it.current()); old impl
				}
			}else{
				// set inverted selection
// 				it.current()->setSelected(!found); old impl
				(*it)->setSelected(!found);
// 				View->repaintItem(it.current()); old impl
			}
		}else{
			// Don't invert selection
			if(addToCurrentSelection){
				// add to selection, only if found
				if(found){
// 					it.current()->setSelected(true); old impl
					(*it)->setSelected(true);
// 					View->repaintItem(it.current()); old impl
				}
			}else{
				// set selection
// 				it.current()->setSelected(found); old impl
				(*it)->setSelected(found);
// // 					View->repaintItem(it.current());
				(*it)->setSelected(found);
// 				View->repaintItem(it.current());
			}
		}
		++it;
	}
}

#include "rename.moc"
