use strict;
use warnings;

use MediaWiki::API;
use Data::Dumper;
use Perlwikipedia;

my $user = "USER";
my $pass = "PASS";

my $mw = MediaWiki::API->new();
$mw->{config}->{api_url} = 'http://en.wikipedia.org/w/api.php';

#login the bot
my $editor=Perlwikipedia->new($user);
$editor->login($user, $pass);

$mw->list ( { action => 'query',
                list => 'categorymembers',
                cmtitle => 'Category:Single_articles_with_infobox_field_chart_position',
                cmnamespace => 0,
                cmlimit=>'500' },
            { max => 100, hook => \&articles } )
|| die $mw->{error}->{code} . ': ' . $mw->{error}->{details};

sub articles {
    my ($ref) = @_;
    foreach (@$ref) {
        my $article = $_->{title};
       
        my $text=$editor->get_text($article);
        if($text =~ /\n\| ?Chart position ?=/gsi and $text =~ /==+ *Charts *==/gsi) {
            $text =~ s/\n\| *Chart position *=.*?\n(\|.*?=)/$1/gsi;
            $text =~ s/^(.*?)\n==(.+)/$1/gsi;
            #$editor->edit($talk, $text, "THEBOTS SUMMARY");
            print $article . "\n\n$text";
            sleep 20;
        }
    }
}