function [mean_based_on_period period max_gap_between_peak] = findperiod(Signal,Timespan)

%Compute the gradient of the signal
FX = gradient(Signal);

%finding index with values between 0.1 and -0.1
[index] = find((FX <= (0.1)) & (FX >= (-0.1)));

%sum_period = 0;

%Set Ref_Check
if(FX(index(1)) > 0)
    Ref_Check = 1; %Positive
    FirstCheck = 1;
else
    Ref_Check = 0; %Negative
    FirstCheck = 0;
end
%Check for a change in sign
count = 1;
for i = 2: length(index)
    if(FX(index(i)) >= 0)
       Check = 1;
    else 
       Check = 0;
    end
    
    if(Check ~= Ref_Check)
        Save_index(count) = index(i);
        Ref_Check = Check;
        count = count + 1;
    end    
end
%Calculate the period
time_per_point = Timespan / length(Signal);
%Taking the mean period
if(length(Save_index) >= 3)
    sum_period = 0;
    sum_mean = 0;
    count = 0;
    for j = 1 : 2: length(Save_index)- 2
        temp_period = (Save_index(j+2)- Save_index(j)) * time_per_point;
        sum_period = sum_period + temp_period;
        
        %Finding the baseline within a period
        temp = Signal(Save_index(j):Save_index(j+2));
        temp_mean = mean(temp);
        sum_mean = sum_mean + temp_mean;
        count = count + 1;
    end

period = sum_period / count;
mean_based_on_period = sum_mean/count;
end
%Finding the largest and smallest peak 
count = 1;
if ( FirstCheck == 1)
   start_j = 1; 
else
   start_j = 2;
end

if(length(Save_index) > 2)
    for j = start_j : 2: length(Save_index)
        temp_peak(count) = Signal(Save_index(j));
        count = count + 1;
    end
end
    maximum_peak = max(temp_peak);
    minimum_peak = min(temp_peak);
    max_gap_between_peak = maximum_peak - minimum_peak;

