Index: /extensions/pLoader/trunk/locale/fr_FR/pLoader.po
===================================================================
--- /extensions/pLoader/trunk/locale/fr_FR/pLoader.po	(revision 4466)
+++ /extensions/pLoader/trunk/locale/fr_FR/pLoader.po	(revision 4467)
@@ -41,4 +41,10 @@
 msgstr "Transfert haute définition ( taille originale )"
 
+msgid "Upload high definition  :"
+msgstr "Transfert haute définition :"
+
+msgid "High definition"
+msgstr "Haute définition"
+
 msgid "Yes"
 msgstr "Oui"
@@ -491,4 +497,13 @@
 msgstr "Erreur de communication avec"
 
+msgid "Thumbnail image done for"
+msgstr "Miniature de l'image terminée pour"
+
+msgid "HD image done for"
+msgstr "Image haute définition terminée pour"
+
+msgid "Resized image done for"
+msgstr "Image réduite terminée pour"
+
 msgid "Uploaded"
 msgstr "Transféré"
@@ -532,2 +547,32 @@
 msgid "HD image interlace :"
 msgstr "Entrelacement de l'image HD :"
+
+msgid "nothing"
+msgstr "ne rien faire"
+
+msgid "replace"
+msgstr "remplacer"
+
+msgid "fill if empty (only replace properties currently empty in Piwigo)"
+msgstr "remplir si non renseigné (ne remplacer que les propriétés vides dans Piwigo)"
+
+msgid "append (keep existing and add new)"
+msgstr "cumuler (garder l'existant et ajouter)"
+
+msgid "Do not ask me again"
+msgstr "Ne plus me demander"
+
+msgid "A least one photo has already been added in the past."
+msgstr "Au moins une photo a déjà été ajoutée dans le passé."
+
+msgid "What shall we do with files? (thumbnail, resized, high resolution)"
+msgstr "Que faire pour les fichiers ? (miniature, taille web, haute définition)"
+
+msgid "What shall we do with single value properties?(caption, comment, author, create date)"
+msgstr "Que faire pour les propriétés simples ? (titre, commentaire, auteur, date de création)"
+
+msgid "What shall we do with multiple values properties? (categories, tags)"
+msgstr "Que faire pour les propriétés à valeurs multiples ? (catégories, tags)"
+
+msgid "Photo update management"
+msgstr "Gestion de la mise à jour des photos"
Index: /extensions/pLoader/trunk/res/reupload_wdr.pl
===================================================================
--- /extensions/pLoader/trunk/res/reupload_wdr.pl	(revision 4467)
+++ /extensions/pLoader/trunk/res/reupload_wdr.pl	(revision 4467)
@@ -0,0 +1,77 @@
+#-----------------------------------------------------------------------------
+# Perl source generated by wxDesigner from file: reupload.wdr
+# Do not modify this file, all changes will be lost!
+#-----------------------------------------------------------------------------
+
+use Wx;
+use Wx::Calendar;
+use Wx::DateTime;
+use Wx::Grid;
+use strict;
+
+use Wx qw( wxDefaultSize wxDefaultPosition wxNullAnimation wxNullFont wxBLACK );
+use Wx qw( wxID_OK wxID_APPLY wxID_SAVE wxID_SAVEAS wxID_CANCEL wxID_YES wxID_NO wxID_EXIT wxID_ABOUT wxID_HELP );
+use Wx qw( wxVERTICAL wxHORIZONTAL wxALL wxLEFT wxRIGHT wxTOP wxBOTTOM wxCENTRE wxGROW );
+use Wx qw( wxALIGN_RIGHT wxALIGN_BOTTOM wxALIGN_CENTER wxALIGN_CENTER_VERTICAL wxALIGN_CENTER_HORIZONTAL );
+use Wx qw( wxRA_SPECIFY_COLS );
+
+# Bitmap functions
+
+use Wx qw( wxNullBitmap wxBITMAP_TYPE_PNG );
+
+# Window functions
+
+use vars qw($ID_REUPLOAD_TEXT); $ID_REUPLOAD_TEXT = 10000;
+use vars qw($ID_REUPLOAD_ACTION_FILES); $ID_REUPLOAD_ACTION_FILES = 10001;
+use vars qw($ID_REUPLOAD_ACTION_PROPERTIES); $ID_REUPLOAD_ACTION_PROPERTIES = 10002;
+use vars qw($ID_REUPLOAD_ACTION_PROPERTIES_M); $ID_REUPLOAD_ACTION_PROPERTIES_M = 10003;
+use vars qw($ID_REUPLOAD_NOT_ASK); $ID_REUPLOAD_NOT_ASK = 10004;
+use vars qw($ID_REUPLOAD_OK); $ID_REUPLOAD_OK = 10005;
+
+sub Reupload {
+    my( $parent ) = $_[0];
+    my( $item0 ) = Wx::BoxSizer->new( wxVERTICAL );
+    
+    my( $item1 ) = Wx::StaticText->new( $parent, $main::ID_REUPLOAD_TEXT, "Some photos in the selection have already been uploaded. What do you want to do ?", wxDefaultPosition, wxDefaultSize, 0 );
+    $item0->AddWindow( $item1, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
+
+    my( $item2 ) = Wx::RadioBox->new( $parent, $main::ID_REUPLOAD_ACTION_FILES, "Thumbnail, web size, high definition files", wxDefaultPosition, [450,-1], 
+        ["nothing","replace"] , 1, wxRA_SPECIFY_COLS );
+    $item0->AddWindow( $item2, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
+
+    my( $item3 ) = Wx::RadioBox->new( $parent, $main::ID_REUPLOAD_ACTION_PROPERTIES, "Title, description, author, created date )", wxDefaultPosition, [450,-1], 
+        ["nothing","append ( keep existing and set if not defined in Piwigo )","replace"] , 1, wxRA_SPECIFY_COLS );
+    $item0->AddWindow( $item3, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
+
+    my( $item4 ) = Wx::RadioBox->new( $parent, $main::ID_REUPLOAD_ACTION_PROPERTIES_M, "Categories, tags", wxDefaultPosition, [450,-1], 
+        ["nothing","append ( keep existing and add new )","replace"] , 1, wxRA_SPECIFY_COLS );
+    $item0->AddWindow( $item4, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
+
+    my( $item5 ) = Wx::CheckBox->new( $parent, $main::ID_REUPLOAD_NOT_ASK, "Do not ask me again", wxDefaultPosition, wxDefaultSize, 0 );
+    $item0->AddWindow( $item5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
+
+    my( $item6 ) = Wx::Button->new( $parent, $main::ID_REUPLOAD_OK, "OK", wxDefaultPosition, wxDefaultSize, 0 );
+    $item0->AddWindow( $item6, 0, wxALIGN_CENTER|wxALL, 5 );
+
+    my( $set_size ) = @_ >= 3 ? $_[2] : 1;
+    my( $call_fit ) = @_ >= 2 ? $_[1] : 1;
+    if( $set_size == 1 ) {
+         $_[0]->SetSizer( $item0 );
+         
+         if( $call_fit == 1 ) {
+             $item0->SetSizeHints( $_[0] );
+         }
+    }
+    
+    $item0;
+}
+
+# Menu bar functions
+
+
+# Toolbar functions
+
+use Wx qw( wxITEM_NORMAL wxITEM_RADIO wxITEM_CHECK );
+
+
+# End of generated file
Index: /extensions/pLoader/trunk/src/Uploader/GUI/DlgCommon.pm
===================================================================
--- /extensions/pLoader/trunk/src/Uploader/GUI/DlgCommon.pm	(revision 4467)
+++ /extensions/pLoader/trunk/src/Uploader/GUI/DlgCommon.pm	(revision 4467)
@@ -0,0 +1,57 @@
+package Uploader::GUI::DlgCommon;
+use strict;
+
+sub SetProperties {
+    my ($dlg, $properties ) = @_;
+	
+	map {
+        my $ctrl =$dlg->FindWindow($_);
+        #printf("ctrl %s : %s\n", $_, $ctrl);		
+        if(defined $ctrl){
+		# checkbox, static text
+		$ctrl->SetLabel(
+           $dlg->properties->{$_}->{label}
+		) if exists$dlg->properties->{$_}->{label};
+
+        $ctrl->SetValue(
+           $dlg->properties->{$_}->{value}->()
+		) if exists$dlg->properties->{$_}->{value};
+
+        # radiobox
+        my $labels =$dlg->properties->{$_}->{labels};
+		$labels||=[];
+		for(my $i=0; $i < scalar @$labels ; $i++){
+		    $ctrl->SetItemLabel($i, $labels->[$i]);
+		}
+		# only works for control with items
+		$ctrl->SetSelection(
+		    $dlg->properties->{$_}->{selection}->()			
+		) if exists $dlg->properties->{$_}->{selection};
+		
+		}
+    }
+	keys %$properties;
+}
+
+sub GetProperties {
+    my ($dlg, $properties ) = @_;
+
+	map {
+        my $ctrl =$dlg->FindWindow($_);
+        #printf("ctrl %s : %s\n", $_, $ctrl);		
+        if(defined $ctrl){
+		# checkbox, static text
+
+        $dlg->properties->{$_}->{value}->(
+            $ctrl->GetValue()
+		) if exists$dlg->properties->{$_}->{value};
+
+        $dlg->properties->{$_}->{selection}->(
+		    $ctrl->GetSelection()			
+		) if exists $dlg->properties->{$_}->{selection};
+		
+		}
+    }
+	keys %$properties;
+}
+1;
Index: /extensions/pLoader/trunk/src/Uploader/GUI/wxApp.pm
===================================================================
--- /extensions/pLoader/trunk/src/Uploader/GUI/wxApp.pm	(revision 4466)
+++ /extensions/pLoader/trunk/src/Uploader/GUI/wxApp.pm	(revision 4467)
@@ -519,4 +519,7 @@
         watermark_x => 10,
         watermark_color => 'White',
+		reupload_action_files => 1,
+		reupload_action_properties => 2,
+		reupload_action_properties_m => 1,
     };
 
Index: /extensions/pLoader/trunk/src/Uploader/GUI/wxFrameAUI.pm
===================================================================
--- /extensions/pLoader/trunk/src/Uploader/GUI/wxFrameAUI.pm	(revision 4466)
+++ /extensions/pLoader/trunk/src/Uploader/GUI/wxFrameAUI.pm	(revision 4467)
@@ -148,4 +148,5 @@
 use Uploader::GUI::wxImageProcessingProgressDlg;
 use Uploader::GUI::wxChoiceFilteredPanel;
+use Uploader::GUI::wxImageReuploadDlg;
 use Wx::Html;
 use Uploader::GUI::wxImagePreview;
@@ -155,4 +156,5 @@
 use Storable;
 use Uploader::GUI::wxPropertyGridPanel;
+use Uploader::GUI::wxPhotoProperties;
 use utf8;
 $|=1;
@@ -206,4 +208,49 @@
         sub { $self->UploadImagesViewerRefresh(@_) }
     );
+	
+	$self->imagelist->ReuploadCallback(
+	    sub {
+		    Uploader::GUI::wxImageReuploadDlg->new(
+            { 
+				title      => gettext("Photo update management"),
+                properties => {
+                    		        $main::ID_REUPLOAD_ACTION_FILES        => { 
+									                                            selection=>sub {$self->imagelist->reupload_action_files(@_)},
+																				label=>gettext("What shall we do with files? (thumbnail, resized, high resolution)"),
+                                                                                labels=>[
+																				           gettext("nothing"),
+																				           gettext("replace"),
+																				       ],																				
+								                                            },
+								    $main::ID_REUPLOAD_ACTION_PROPERTIES   => { 
+									                                            selection=>sub{$self->imagelist->reupload_action_properties(@_)},
+																				label=>gettext("What shall we do with single value properties?(caption, comment, author, create date)"),
+                                                                                labels=>[
+																				           gettext("nothing"),
+																				           gettext("fill if empty (only replace properties currently empty in Piwigo)"),
+																				           gettext("replace"),
+																				       ],																				
+									                                          },
+									$main::ID_REUPLOAD_ACTION_PROPERTIES_M => { 
+									                                            selection=>sub{$self->imagelist->reupload_action_properties_m(@_)},
+																				label=>gettext("What shall we do with multiple values properties? (categories, tags)"),
+                                                                                labels=>[
+																				           gettext("nothing"),
+																				           gettext("append (keep existing and add new)"),
+																				           gettext("replace"),
+																				       ],																				
+									                                          },
+									$main::ID_REUPLOAD_NOT_ASK             => { 
+									                                            value=>sub{$self->imagelist->reupload_not_ask(@_)}, 
+                                                                                label=>gettext("Do not ask me again"),																				
+									                                          },
+									$main::ID_REUPLOAD_TEXT                => { 
+                                                                                label=>gettext("A least one photo has already been added in the past."),																				
+									                                          },
+				                },
+            }
+			)->ShowModal();
+		}
+	);
 
 
@@ -277,4 +324,5 @@
 sub _set_setting_properties {
     my ( $self ) = @_;
+	
 
     $self->piwigo_properties(
@@ -607,5 +655,5 @@
     }
     (
-        $self->image_prop_piwigo,
+    	$self->image_prop_piwigo,
         $self->image_prop_exif,
         $self->image_prop_tags,
@@ -663,5 +711,5 @@
 sub _refresh_settings_panels_properties {
     my ( $self ) = @_;	
-
+	
     $self->image_prop_piwigo->properties(
         $self->piwigo_properties
@@ -701,4 +749,5 @@
 sub _init_settings_panels {
     my ( $self ) = @_;	
+
 
     $self->image_prop_piwigo(
@@ -868,4 +917,5 @@
         ->CenterPane->Resizable->CloseButton(0) );
 
+		
     $self->manager->AddPane( 
         $self->create_tree, 
@@ -1079,5 +1129,5 @@
         [
             $self->hd_settings_panel, 
-            gettext("HD"),
+            gettext("High definition"),
         ],
         [
@@ -1745,5 +1795,13 @@
     my ( $self ) = @_;	
 
+
     $self->imageviewer->Refresh;
+
+    $self->image_preview->image(
+        0
+    ) if !$self->imageviewer->GetItemCount;
+
+
+    $self->image_preview->Refresh;
     Wx::Yield();
 }
@@ -1841,5 +1899,5 @@
 
     my $wximagelist = $self->imagelist->wx_thumb_imglist;
-print Dumper "SetNewFilesViewerRefresh", $self->imagelist->current_image;
+    #print Dumper "SetNewFilesViewerRefresh", $self->imagelist->current_image;
     my $indx = $wximagelist->Add(
         Wx::Bitmap->new( 
Index: /extensions/pLoader/trunk/src/Uploader/GUI/wxImageReuploadDlg.pm
===================================================================
--- /extensions/pLoader/trunk/src/Uploader/GUI/wxImageReuploadDlg.pm	(revision 4467)
+++ /extensions/pLoader/trunk/src/Uploader/GUI/wxImageReuploadDlg.pm	(revision 4467)
@@ -0,0 +1,102 @@
+# +-----------------------------------------------------------------------+
+# | pLoader - a Perl photo uploader for Piwigo                            |
+# +-----------------------------------------------------------------------+
+# | Copyright(C) 2008      Piwigo Team                  http://piwigo.org |
+# +-----------------------------------------------------------------------+
+# | This program is free software; you can redistribute it and/or modify  |
+# | it under the terms of the GNU General Public License as published by  |
+# | the Free Software Foundation                                          |
+# |                                                                       |
+# | This program is distributed in the hope that it will be useful, but   |
+# | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+# | General Public License for more details.                              |
+# |                                                                       |
+# | You should have received a copy of the GNU General Public License     |
+# | along with this program; if not, write to the Free Software           |
+# | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+# | USA.                                                                  |
+# +-----------------------------------------------------------------------+
+package Uploader::GUI::wxImageReuploadDlg;
+use strict;
+use Wx qw/
+             wxDefaultSize
+             wxDefaultPosition
+             wxID_CANCEL
+             wxID_OK
+             wxGREEN
+         /;
+use base qw/Wx::Dialog Class::Accessor::Fast/;
+use Wx::Event qw/
+                    EVT_UPDATE_UI
+                    EVT_BUTTON
+					EVT_CLOSE
+                /;
+
+__PACKAGE__->mk_accessors( 
+    qw/
+        properties
+      / 
+);
+use Carp;
+use Uploader::GUI::DlgCommon;
+
+sub new {
+    my ($this, $params) = @_;
+    #on recupere le nom de la classe en fonction du type d'appel de la méthode.
+    my $class = ref($this) || $this;
+
+
+    my $self = $class->SUPER::new( undef, -1, $params->{title}, wxDefaultPosition, wxDefaultSize);
+    # load controls
+    eval {
+      &main::Reupload($self, 1);
+
+	    $self->properties(
+    	    $params->{properties}
+        );
+
+        Uploader::GUI::DlgCommon::SetProperties($self, $self->properties);
+        $self->_initEventHandlers();
+
+		if($@){
+			Wx::LogMessage("Error during dialogbox initialization");
+		}
+	};
+
+    $self;    
+}
+
+
+
+sub _initEventHandlers {
+    my ( $self ) = @_;
+    
+    EVT_BUTTON( $self, $main::ID_REUPLOAD_OK, \&OnOK );
+    EVT_CLOSE( $self, \&OnClose );
+    
+	
+}
+
+
+sub OnOK {
+    my ( $self, $event ) = @_;
+    
+    $self->_close;
+}
+
+sub OnClose {
+    my ( $self, $event ) = @_;
+	
+	$self->_close;
+}
+
+sub _close {
+    my ( $self ) = @_;
+
+    Uploader::GUI::DlgCommon::GetProperties($self, $self->properties);
+		
+    $self->Destroy;
+}
+
+1;
Index: /extensions/pLoader/trunk/src/Uploader/ImageList.pm
===================================================================
--- /extensions/pLoader/trunk/src/Uploader/ImageList.pm	(revision 4466)
+++ /extensions/pLoader/trunk/src/Uploader/ImageList.pm	(revision 4467)
@@ -95,4 +95,5 @@
                 use_exif_preview
                 image_sums
+				upload_image_sums
                 sums
                 version
@@ -120,4 +121,9 @@
                 upload_file
                 upload_name
+				ReuploadCallback
+				reupload_action_files
+				reupload_action_properties
+				reupload_action_properties_m
+				reupload_not_ask
      /
 );
@@ -253,5 +259,5 @@
             # ok
             if(!$@){
-                $self->progress_msg("Selection thumbnail created for %s");
+                $self->progress_msg(gettext("Selection thumbnail created for %s"));
             }
             else {
@@ -554,5 +560,5 @@
     
     my $rval = 1 ;
-    return $rval if( -e $self->current_image->site_resized_file );
+    #return $rval if( -e $self->current_image->site_resized_file );
 
     printf(
@@ -634,5 +640,5 @@
     my ( $self ) = @_;
     
-    return 1 if( -e $self->current_image->site_thumb_file );
+    #return 1 if( -e $self->current_image->site_thumb_file );
     
     my $rval = 1;
@@ -765,4 +771,7 @@
                 watermark_x
                 watermark_color
+				reupload_action_files
+				reupload_action_properties
+				reupload_action_properties_m
             /
         ] 
@@ -797,11 +806,29 @@
     $self->upload_begin_time(time);
     $self->upload_selection_count(scalar @{$self->image_selection});
+	# for re-upload management
+    $self->upload_image_sums( [
+	        map { $self->GetImage($_)->file_sum }
+		    @{$self->image_selection}
+	    ] 
+	);
+
+	# check if already exist on server
+	my $uploaded = $self->pwg->IsAlreadyUploaded($self->upload_image_sums);
+	my @already_uploaded = grep { $_ } values %$uploaded ; 
+	$self->ReuploadCallback->() if ( scalar @already_uploaded and !$self->reupload_not_ask );
+
+	
     foreach(@{$self->image_selection}) {
-        # current image object    	
+	# current image object    	
     	$self->current_image(
     	    $self->GetImage($_)
-    	);
+    	); 
         # prepare resized, high, thumbnail
-        $self->_upload_selection_prepare();
+		# if not already uploaded
+        $self->_set_site_resized_file();
+        $self-> _set_site_high_file ();
+        # photo metadata
+        $self->_prepare_upload_properties();    	
+        $self->_upload_selection_prepare() if (!$uploaded->{$self->current_image->file_sum} or $self->reupload_action_files);
 
         # transfert resized, high, thumbnail to site
@@ -827,5 +854,4 @@
     $self->progress_thumbnail_refresh->();
     # PREPARE
-    $self->_set_site_resized_file();
     $self->_set_upload_msg(gettext("Preparing resized image for"));
     $self->_upload_progress();
@@ -848,5 +874,5 @@
 	    'Yes, use a copy of the original photo' => 'ORIGINAL',
     };	
-
+printf("upload HD %s\n", $self->upload_hd);
 	$self->upload_high(
 	    $decode->{$self->upload_hd}
@@ -866,6 +892,4 @@
     $self->_upload_progress();
 
-    # photo metadata
-    $self->_prepare_upload_properties();    	
 
 }
@@ -923,4 +947,5 @@
             highdef_msg=>gettext("Uploading high definition"),
             checksum_msg=>gettext("Checksum for"),
+            original_sum=>$self->current_image->file_sum,
         } 
     );
@@ -1102,5 +1127,4 @@
 
     if($bModifyOriginal){
-        $self-> _set_site_high_file ();
 
         my $image = Image::Magick->new();
@@ -1238,4 +1262,15 @@
 sub _prepare_upload_properties {
     my ( $self ) = @_;
+
+	$self->pwg->reupload_action_files(
+	    $self->reupload_action_files||1
+	);
+	$self->pwg->reupload_action_properties(
+	    $self->reupload_action_properties||2
+	);
+
+	$self->pwg->reupload_action_properties_m(
+	    $self->reupload_action_properties_m||1
+	);
     
     $self->pwg->upload_high(
@@ -1285,4 +1320,5 @@
         join(',', @{$self->current_image->site_tags})
     );
+
 	
 }
Index: /extensions/pLoader/trunk/src/Uploader/PWG/WebServices.pm
===================================================================
--- /extensions/pLoader/trunk/src/Uploader/PWG/WebServices.pm	(revision 4466)
+++ /extensions/pLoader/trunk/src/Uploader/PWG/WebServices.pm	(revision 4467)
@@ -61,8 +61,12 @@
            upload_high
            chunk_size
-           sum_high_file
-           sum_resized_file
-           sum_thumb_file
-           sum_original_file
+           sum
+           image_id
+           typecode
+		   reupload_action_files
+		   reupload_action_properties
+		   reupload_action_properties_m
+		   single_value_mode
+		   multiple_value_mode
       / 
 );
@@ -72,5 +76,28 @@
 sub Init {
     my ( $self, $version ) = @_ ;
- 
+
+    # to transform a type_code into a typename
+    $self->typecode(
+        {
+             file => 'file',
+             thumbnail => 'thumb',
+             high => 'high',	
+        }
+    );
+	
+	$self->single_value_mode(
+	    {
+		    1 => 'fill_if_empty',
+			2 => 'replace',
+		}
+	);
+
+	$self->multiple_value_mode(
+	    {
+		    1 => 'append',
+			2 => 'replace',
+		}
+	);
+	
     $self->uagent(
         LWP::UserAgent->new(
@@ -125,40 +152,50 @@
     };
  
-    $self->uagent_response(
-        $self->uagent->post(
-            $self->urlbase.'/ws.php?format=json',
-            $form
-        )
-    );
-    
+    $self->_execute_post(
+        $form
+    );    
+
+    $self->login_result(
+        $self->_json_response_content
+    );
+
+}
+
+sub _json_response_content {
+    my ( $self ) = @_;
+
     my $hresult = {} ;
 
     if($self->uagent_response->is_success){
+        # when server response has warnings, the content response is not a valid json string
+		# find the json response
+		#printf("%s\n", $self->uagent_response->content);
+        $self->uagent_response->content =~ /(\{.+\})/;
+		#printf("json response %s\n", $1);
         eval {
             $hresult = from_json(
-                $self->uagent_response->content
+                $1
             );
         };
+		
     }
     else{
-        $hresult = {
+	$hresult = {
             'message' => $self->uagent_response->message,
             'stat'    => 'fail',
         };
     }
-
-    $self->login_result(
-        $hresult
-    );
-
-}
-
-sub GetCategories {
-    my ( $self ) = @_;
-
-    my $result;
+	
+	$hresult;
+}
+
+sub _execute_get {
+    my ( $self, $query ) = @_;
+
     eval {
-        $result = $self->uagent->get(
-            $self->qry_list_categories
+        $self->uagent_response(
+            $self->uagent->get(
+                $query
+		    )
         );
     };
@@ -166,50 +203,49 @@
     if($@){
         printf("An error occured in query execution %s\n%s",
-            $self->qry_list_categories,
+            $query,
             $@,
         );	
     }
-    my $hresult;
-    
-    eval {
-    	$hresult = from_json(
-            $result->content
-        );
-    };
-    
-    $hresult ||= {};
-
-    my $categories = $hresult->{result}{categories};
-
-    $categories;	
-}
-
-sub GetTags {
-    my ( $self ) = @_;
+}
+
+sub _execute_post {
+    my ( $self, $form ) = @_;
 
     my $result;
     eval {
-        $result = $self->uagent->get(
-            $self->qry_list_tags
+        $result = $self->uagent_response(
+            $self->uagent->post(
+                $self->urlbase.'/ws.php?format=json',
+                $form
+            )
         );
-    };
+	};
 
     if($@){
-        printf("An error occured in query execution %s\n%s",
-            $self->qry_list_tags,
+        printf("An error occured in post execution %s\n%s",
+            $form->{method},
             $@,
         );	
     }
-    my $hresult;
-    
-    eval {
-    	$hresult = from_json(
-            $result->content
-        );
-    };
-    
-    $hresult ||= {};
-
-    $hresult->{result}{tags};
+	
+	return ( $result->is_success, $result->status_line );
+}
+sub GetCategories {
+    my ( $self ) = @_;
+
+ 
+    $self->_execute_get(
+	    $self->qry_list_categories
+	);
+    $self->_json_response_content->{result}{categories};
+}
+
+sub GetTags {
+    my ( $self ) = @_;
+
+    $self->_execute_get(
+        $self->qry_list_tags	
+	);
+    $self->_json_response_content->{result}{tags};
 }
 
@@ -223,18 +259,5 @@
     };
 
-    my $result = $self->uagent->post(
-        $self->urlbase.'/ws.php?format=json',
-        $form
-    );
-
-    my $content = {};
-        eval {
-            $content = from_json(
-                $result->content
-            );
-        };
-
-    return ( $result->is_success, $result->status_line, $content );
-	
+    return ( $self->_execute_post($form), $self->_json_response_content );
 } 
 
@@ -243,57 +266,34 @@
     my ( $self, $progress ) = @_;
 
-    $self->sum_resized_file(
-        $self->_checksum(
-            $self->site_resized_file,
-            $progress
-        )
-    );
-
-    $self->sum_thumb_file(
-        $self->_checksum(
-            $self->site_thumb_file,
-            $progress
-        )
-    );
- 
-    $self->sum_high_file(
-        $self->_checksum(
-            $self->site_high_file,
-            $progress
-        )
-    );
-    # is the same in pLoader but may be different 
-    $self->sum_original_file(
-        $self->sum_high_file
-    );
-
-
-    my $site_image_name = $self->site_image_name; 
-
-    my $image_id = $self->_exists($self->sum_original_file);;
-    my $status = 0;
-    my $status_line = "An error has occured during upload.";
+    $self->image_id(
+        $self->_exists($progress->{original_sum})
+    );
+
+    my $status = 1;
+    my $status_line ="OK";
     my $content = {};
     my $doubleCheck;
     my $form;
-    while(1){
-        if(!defined($image_id)){
-        	
-            my $resized_params = $self->_send_chunks('file', $progress);
-            $status_line = $resized_params->{message};
-            last if !$resized_params->{ok};
+    UPLOAD: while(1){
+        # first upload
+        if(!defined($self->image_id)){ 
+            $doubleCheck = 1;
+            $self->_checksum_files($progress);
+            my @types = ('file', 'thumb');
+            push @types, 'high' if $self->upload_high;
+            map{
+                my $rval = $self->_send_chunks($_, $progress);
+                $status_line = $rval->{message};
+                last UPLOAD if !$rval->{ok};
+            } @types;
           
-            my $thumb_params = $self->_send_chunks('thumb', $progress);
-            $status_line = $thumb_params->{message};
-            last if !$thumb_params->{ok};
        	
             $form = {
                 method            => 'pwg.images.add',
-                original_sum      => $self->sum_original_file,
-                file_sum          => $self->sum_resized_file,
-                thumbnail_sum     => $self->sum_thumb_file,
+                original_sum      => $self->sum->{original},
+                file_sum          => $self->sum->{file},
+                thumbnail_sum     => $self->sum->{thumb},
                 categories        => $self->categories,
-                name              => $site_image_name,
-                rank              => $self->rank,
+                name              => $self->site_image_name,
                 author            => $self->site_author,
                 comment           => $self->site_comment,
@@ -302,28 +302,45 @@
                 
             };
-    
-            if($self->upload_high){
-                my $high_params = $self->_send_chunks('high', $progress);
-                $status_line = $high_params->{message};
-                last if !$high_params->{ok};
-				# high is a HD resized copy of original
-				$form->{high_sum} = $self->sum_high_file;
+
+           $form->{high_sum} = $self->sum->{high} if $self->upload_high;
+		   
+           $progress->{yield}->();
+           ( $status, $status_line ) = $self->_execute_post($form); 
+		}
+        # re-upload
+        else{
+		    #printf("reupload, files %s, properties %s\n", $self->reupload_action_files, $self->reupload_action_properties);
+            # need to check if files have changed
+            # and update image info
+            if($self->reupload_action_files){
+                $self->_checksum_files($progress);
+                my $files = $self->_check_files();
+                if(defined($files)){
+                    $self->_add_files($files, $progress);	
+                }
             }
-            $doubleCheck = 1;
-        }
-        else {
+
             $form = {
-                method            => 'pwg.images.setInfo',
-                image_id          => $image_id,
-                categories        => $self->categories,
-                name              => $site_image_name,
-                rank              => $self->rank,
-                author            => $self->site_author,
-                comment           => $self->site_comment,
-                date_creation     => $self->site_img_date_creation,
-                tag_ids           => $self->site_tags,
+                    method        => 'pwg.images.setInfo',
+                    image_id      => $self->image_id,
+		    };
+            # update metadata info
+            if($self->reupload_action_properties){  	
+			    #printf("reupload_action_properties %s\n", $self->reupload_action_properties);
+                $form->{name} = $self->site_image_name;
+                $form->{author}        = $self->site_author;
+                $form->{comment}       = $self->site_comment;
+                $form->{date_creation} = $self->site_img_date_creation;
+				$form->{single_value_mode}  = $self->single_value_mode->{$self->reupload_action_properties};
+		    }
+            if($self->reupload_action_properties_m){  	
+			    #printf("reupload_action_properties_m %s\n", $self->reupload_action_properties_m);
+                $form->{tag_ids} = $self->site_tags if $self->site_tags;
+                $form->{categories} = $self->categories;
+				$form->{multiple_value_mode} = $self->multiple_value_mode->{$self->reupload_action_properties_m};
             };
             $progress->{yield}->();
-        }
+            ( $status, $status_line ) = $self->_execute_post($form); 
+	    }
 
         delete $form->{tag_ids} unless defined $self->site_tags;
@@ -331,26 +348,118 @@
 
         $progress->{yield}->();
-        my $result = $self->uagent->post(
-            $self->urlbase.'/ws.php?format=json',
-            $form
-        );
-        eval {
-            $content = from_json(
-                $result->content
-            );
-        };
-
-    
-        $status = $result->is_success;
-        $status_line = $result->status_line; 
-
-        if($doubleCheck){
-            $content->{stat} = 'fail' if !$self->_exists($self->sum_original_file); 
+	    #print "form ", Dumper $form;
+		#print "status ", $status, "\n";
+		#print "status_line ", $status_line, "\n";
+	    # basic check, should perform a checkfile
+        $content->{stat} = !$self->_exists($progress->{original_sum}) ? 'fail' : 'ok'; 
+
+		last UPLOAD;
+    }# UPLOAD
+    
+    return ( $status,  $status_line, $content);
+}
+
+sub _checksum_files {
+    my ( $self, $progress ) = @_;
+
+    $self->sum(
+        {
+            file => $self->_checksum(
+                        $self->site_resized_file,
+                        $progress
+                    ),
+            thumb => $self->_checksum(
+                             $self->site_thumb_file,
+                             $progress
+                         ),
+            high => $self->_checksum(
+                        $self->site_high_file,
+                        $progress
+                    ),
+            original => $progress->{original_sum}
         }
-
-        last;
+    ); 
+}
+
+sub _check_files {
+    my ( $self ) = @_;
+
+    my $form = {
+        method   => 'pwg.images.checkFiles',
+        image_id => $self->image_id,
+    };
+    
+    @$form{'thumbnail_sum', 'file_sum' } = (
+        $self->sum->{thumb},
+        $self->sum->{file},
+    );
+
+    if($self->upload_high){
+        $form->{high_sum} = $self->sum->{high};
     }
-    
-    return ( $status,  $status_line, $content);
+
+    $self->_execute_post($form);    
+    my $hresult = $self->_json_response_content;
+
+    my $rval = 'ok' eq $hresult->{stat} ? $hresult->{result} : undef;
+    
+    $rval;
+}
+
+# $files is returned by _check_files
+# {
+#     thumbnail => 'equals', 'differs', 'missing'
+#     file => 'equals', 'differs', 'missing'
+#     high => 'equals', 'differs', 'missing'
+#}
+
+sub _add_files {
+    my ( $self, $files, $progress ) = @_;
+
+    map{
+        $self->_add_file($_, $progress);
+    }
+    map{
+        $self->typecode->{$_};
+    } grep { 'equals' ne $files->{$_} } keys %$files ;
+    	
+}
+
+sub _add_file {
+    my ( $self, $type_code, $progress ) = @_;
+
+    $self->_send_chunks(
+        $type_code,
+        $progress,
+    );
+
+    my $form = {
+        method => 'pwg.images.addFile',
+        image_id => $self->image_id,
+        type     => $type_code,
+        sum      => $self->sum->{$type_code},    	
+    };	
+
+    $self->_execute_post($form);    
+    my $hresult = $self->_json_response_content;
+print Dumper $hresult;
+    my $rval = 'ok' eq $hresult->{stat} ? $hresult->{result} : undef;
+    
+    $rval;
+}
+
+sub IsAlreadyUploaded {
+    my ( $self, $md5_sums ) = @_;
+	
+	# md5_sums is an array ref
+	$self->_execute_post({
+        method      => 'pwg.images.exist',
+        md5sum_list => join(',', @$md5_sums)
+	    }
+	);
+
+	my $sums = $self->_json_response_content->{result};
+
+    $sums;
 }
 
@@ -363,18 +472,10 @@
     };
 
-    my $result = $self->uagent->post(
-        $self->urlbase.'/ws.php?format=json',
-        $form
-    );
-
-    my $hresult = {};
-    eval {
-        $hresult = from_json(
-            $result->{_content}
-        );
-    };
-    my $id;
-    $id = $hresult->{result}{$self->sum_original_file} if 'ok' eq $hresult->{stat};
-    
+    $self->_execute_post($form);    
+    my $hresult = $self->_json_response_content;
+
+	$hresult->{result} = {} if 'HASH' ne ref $hresult->{result};
+    my $id = 'ok' eq $hresult->{stat} ? $hresult->{result}{$md5_sum} : undef ;
+
     $id;
 } 
@@ -405,5 +506,5 @@
 
 sub _send_chunks {
-    my ( $self, $type, $progress ) = @_;
+    my ( $self, $type_code, $progress ) = @_;
 
     my $msg = {
@@ -419,13 +520,13 @@
     };
 
-    $progress->{current_msg} = $progress->{$msg->{$type}};
+    $progress->{current_msg} = $progress->{$msg->{$type_code}};
     $progress->{yield}->();
 
     my $params = {
-         filepath      => $filepath->{$type},
-         type          => $type,
-         original_sum  => $self->sum_original_file,
-    };
-
+         filepath      => $filepath->{$type_code},
+         type          => $type_code,
+         original_sum  => $self->sum->{original},
+    };
+print Dumper $params;
     $self->send_chunks(
        $params,
@@ -446,19 +547,6 @@
         
     };
-
-    my $result = $self->uagent->post(
-        $self->urlbase.'/ws.php?format=json',
-        $form
-    );
-
-    my $content = {};
-        eval {
-            $content = from_json(
-                $result->content
-            );
-        };
-
-    return ( $result->is_success, $result->status_line, $content );
 	
+    return ( $self->_execute_post($form), $self->_json_response_content );
 }
 
@@ -474,18 +562,5 @@
     };
 
-    my $result = $self->uagent->post(
-        $self->urlbase.'/ws.php?format=json',
-        $form
-    );
-
-    my $content = {};
-        eval {
-            $content = from_json(
-                $result->content
-            );
-        };
-
-    return ( $result->is_success, $result->status_line, $content );
-	
+    return ( $self->_execute_post($form), $self->_json_response_content );
 }
 
