# Simple script to replace addMultiCell(Widget|Layout|) with the correct Qt4 calls add(Widget|Layout|Item) with swapped parameters and with row/colspan instead of last row/col.
# CAUTION: This is NOT PRODUCTION QUALITY, use at your own risk (and commit all local changes before running this script!)
# I do not assert any rights on these few trivial lines of code, Reinhold Kainhofer

# multiCell.files is generated by "grep -l -e addMultiCell -r [ac-z]*"

for i in `cat multiCell.files`; do 
  # This doesn't work if the addMultiCell* call stretches over multiple lines... These cases are detected in the manual inspection (since "addMultiCell" is replaced by "add").
  # swap the third and fourth param and replace the last row/col with the row/colspan which is  lastrow/col-firstrow/col+1.
  sed 's/\(addMultiCell[^(]*\)(\([^,]*\),\([^,]*\),\([^,]*\),\([^,]*\),\([^,)]*\)/\1(\2,\3,\5,\4-\3+1,\6-\5+1/g' $i > $i.replaced; 
  # detect cases where the row/colspan equals 1 (i.e. first row/col==last row/col)
  sed 's/\(addMultiCell[^(]*\)(\([^,]*\),\([^,]*\),\([^,]*\), *\([^,-]*\) *- *\5 *+1,\([^,)]*\)/\1(\2,\3,\4, 1,\6/g' $i.replaced > $i.replaced1; 
  sed 's/\(addMultiCell[^(]*\)(\([^,]*\),\([^,]*\),\([^,]*\),\([^,)]*\), *\([^,-]*\) *- *\6 *+1/\1(\2,\3,\4,\5, 1/g' $i.replaced1 > $i.replaced2; 
  # play dump and simply replace all simple numerical expressions like 2+1 or -0 by the correct value. Check for the comma before the expression to avoid missing a minus sign before or similar problems.
  sed 's/- *0 *+/+/g' $i.replaced2 > $i.replaced4;
  sed 's/, *1 *+ *1)/, 2 )/g' $i.replaced4 > $i.replaced5;
  sed 's/, *1 *+ *1,/, 2,/g' $i.replaced5 > $i.replaced6;
  sed 's/- *1 *+ *1//g' $i.replaced6 > $i.replaced7;
  sed 's/, *2 *+ *1)/, 3 )/g' $i.replaced7 > $i.replaced8;
  sed 's/, *2 *+ *1,/, 3,/g' $i.replaced8 > $i.replaced9;
  sed 's/, *3 *+ *1,/, 4,/g' $i.replaced9 > $i.replaced10;
  sed 's/, *3 *+ *1)/, 4 )/g' $i.replaced10 > $i.replaced11;
  sed 's/, *4 *+ *1)/, 5 )/g' $i.replaced11 > $i.replaced12;
  sed 's/addMultiCell/add/g' $i.replaced12 > $i.replaced13;
done

# Now look at the diffs to check for manual intervention:
#   nr=13
#   for i in `cat multiCell.files`; do echo $i; diff $i $i.replaced$nr; done > diffs
#
# in the diffs file, look for:
#  -) numerical expressions that were not simplified, e.g. 19-16+1, or 5+1
#  -) addMultiCell* calls that stretch over multiple lines (i.e. addMultiCell* is replaced, but the params are not touched)
#  -) addMultiCell* calls where the first param contains commas or braces, e.g. 
#         grid->addMultiCellWidget(new KSeparator(Qt::Horizontal, tabYourSSLCert), 6, 6, 0, 5);
#     which is completely messed up by the first sed command. I'm just too lazy to treat this complicated case, rather do manual intervention
#  -) 

#finally, copy the new files to correct location
#  for i in `cat multiCell.files`; do mv $i.replaced$nr $i; done
