function [outfile,struct] = analyze_shp(shpfile,shpfile_files,shpfile_shps,filelist,back_flag);

%define start time
eta_start = now;

%define the strings
clear str
str{1} = 'a1';
str{2} = 'c1';

%check inputs
invar = {'shpfile','shpfile_files','shpfile_shps','filelist','back_flag'};
for i=1:length(invar);
    if ~exist(invar{i},'var');
        eval([ invar{i} ' =[];']);
    end;
end;

%define default input for empty lakes
if isempty(shpfile);
    shpfile = 'Empty_Lake_Unit_v2.shp';
    shpfile_files = 'Empty_Lake_Unit_v2_files.mat';
    shpfile_shps  = 'Empty_Lake_Unit_v2_shapes.mat';
end;
if isempty(shpfile_files);
    pos = strfind( shpfile,'.shp');
    if isempty(pos);
        pos = strfind( shpfile,'.mat');
    end;
    shpfile_files = [shpfile(1:pos(end)-1) '_files.mat'];
end;
if isempty(shpfile_shps);
    pos = strfind( shpfile,'.shp');
    shpfile_shps = [shpfile(1:pos(end)-1) '_shapes.mat'];
end;

%determine the back flag
if isempty(back_flag);
    pos = strfind(shpfile,'background.mat');
    if ~isempty(pos);
        back_flag = 1;
    end;
end;
if isempty(back_flag); back_flag = 0; end;
if back_flag; disp(['Background Flag Set!']); end;

%define default input for the 060309 filelist
if isempty(filelist);;
    filelist = 'E:\Titan\BIDR\Scripts\BIDR_File_List_060309.txt';
end;
if ischar(filelist);
    pos = strfind(filelist,'txt');
    if length(pos) > 0;
        files =  read_filelist(filelist);
    else;
        files = filelist;
    end;
end;
files_f = fields(files);
files_num = length(files_f);

%load the requisit files
if back_flag;
    load(shpfile);
    shp = struct;
    cnt = 1;
    for i=1:length(shp);
        infiles(i).num = length(shp(i).lat);
        for j=1:infiles(i).num;
            infiles(i).names{j} = shp(i).file{j};
            ivals(cnt) = i;
            jvals(cnt) = j;
            cnt = cnt+1;
        end;
    end;    
else;
    shp = shaperead(shpfile);
    load(shpfile_files);
%     cnt=1;
%     for i=1:length(shp);
%         if infiles(i).num~=0;
%         for j=1:infiles(i).num;
%             ivals(cnt)=i;
%             jvals(cnt)=j;
%             cnt = cnt+1;
%         end;
%         else;
%             ivals(cnt)=i;
%             jvals(cnt)=0;
%             cnt = cnt+1;
%         end;
%     end;
end;      
if exist(shpfile_shps) ~= 2;
    disp(['Using Default No Intersections With Other Polygons!']);
    for i=1:length(shp);
        inshp(i).num = 0;
    end;
else;
    load(shpfile_shps);
end;

%%print an update to the screen
num = length(shp);
screen_prefix = ['Finished Analyzing Shape'];
screen_suffix = [ ' ' num2str(0) ' Of  ' num2str(num)  ...
    ' ( ' num2str(0) '  Percent Complete)'];
fprintf(1,[screen_prefix,screen_suffix]);
back_string = ['\b'];
while length(back_string) < 2*length(screen_suffix);
    back_string = ['\b' back_string];
end;

shp_num = length(shp);
%step through each shape and calculate the statistics
for i=1:shp_num;
           
    %get the lat and lon
    if back_flag;
        lat = shp(i).lat{1};
        lon = shp(i).lon{1};
    else;        
        lat = shp(i).Y;
        lon = shp(i).X;
    end;
    ind = find( ~isnan(lon) & ~isnan(lat) );
    lat = lat(ind);
    lon = lon(ind);
    %if there is no polygon, do not continue!
    if ~isempty(ind);
        
        %input the basic statistics
        struct(i).lat = lat;
        struct(i).lon = lon;
        struct(i).lat0 = mean(lat);
        struct(i).lon0 = mean(lon);
        struct(i).n_points = length(lat);
        struct(i).area = areaint(lat,lon,[2575,0]);
        struct(i).perim = calc_perim(lat,lon);      
        [D,L,s,Lo,so] = calc_fractal_dim(lat,lon);
        struct(i).frac_D = D;
        struct(i).frac_L = L;
        struct(i).frac_s = s;
        struct(i).frac_Lo = Lo;
        struct(i).frac_so = so;
        struct(i).date = date;
        
       
        %put in null values for other statistics for now
        struct(i).avg = nan;
        struct(i).med = nan;
        struct(i).std = nan;
        struct(i).inc_avg = nan;
        struct(i).inc_med = nan;
        struct(i).inc_std = nan;
        struct(i).sar_vals{1} = nan;
        struct(i).inc_vals{1} = nan;
        struct(i).sar_file{1} = nan;
        struct(i).inc_file{1} = nan;
        
        
        %step through each of the files which contain the shape
        for j=1:infiles(i).num;
            %define the sar file
            sar_file = infiles(i).names{j};    
            
            %find the associated incidence angle file
            clear inc_file
            sar_file = strrep(sar_file,'/','\');
            [sar_file_direc,sar_file_name,sar_file_ext] = fileparts(sar_file);            
            sar_file_name = [sar_file_name sar_file_ext];
            for k=1:files_num;
                [temp_direc,temp_name,temp_ext] = fileparts(eval(['files.' files_f{k}]));
                temp_name = [temp_name temp_ext];
                if strcmp(sar_file_name,temp_name);
                %if strcmp(sar_file,eval(['files.' files_f{k} ';']));
                    temp_str = strrep(files_f{k},str{1},str{2});                    
                    inc_file = eval(['files.' temp_str ';']);
                    [inc_file_direc,inc_file_name,inc_file_ext] = fileparts(inc_file);
                    inc_file_name = [inc_file_name inc_file_ext];
                    inc_file = [sar_file_direc '\' inc_file_name];
                    break
                end;
            end;
            if ~exist('inc_file','var');
                sar_file = strrep(sar_file,'\','/');
                for k=1:files_num;
                    if strcmp(sar_file,eval(['files.' files_f{k} ';']));
                        temp_str = strrep(files_f{k},str{1},str{2});
                        inc_file = eval(['files.' temp_str ';']);
                        break
                    end;
                end;
            end;
            if ~exist('inc_file','var');
                back_string= ['\b'];
                while length(back_string) < (2*length([screen_prefix,screen_suffix]));
                    back_string = ['\b' back_string];
                end;
                fprintf(1,back_string);
                
                disp(['Coud Not File Incidence Angle Files For ' sar_file]);
                
                fprintf(1,[screen_prefix,screen_suffix]);
                back_string = ['\b'];
                while length(back_string) < 2*length(screen_suffix);
                    back_string = ['\b' back_string];
                end;
                break
            end;
            
            %convert the polygon to sample and line space
            if back_flag;
                line = shp(i).line{j};
                sample = shp(i).sample{j};
                info = pds_label_parse(sar_file);
            else;
                [line,sample,info] = bidr_proj(lat,lon,sar_file);
            end;
            
            %get the size of the image
            %info = pds_label_parse(sar_file);
            if isfield(info,'qube')
                sz = info.qube.coreitems;
                if ischar(sz); sz = str2num(sz); end;
                sz_s = sz(1);
                sz_l = sz(2);
            elseif isfield(info,'image');
                sz_s = info.image.linesamples;
                sz_l = info.image.lines;
                if ischar(sz_s); sz_s = str2num(sz_s); end;
                if ischar(sz_l); sz_l = str2num(sz_l); end;
            else;
                disp(['Could Not Find Image Size For ' sarfile]);
                break
            end;
            
            %get the samples and lines associated with polygon            
            bb_min_s = max([1 floor(min(sample))]);
            bb_max_s = min([sz_s ceil(max(sample))]);
            bb_min_l = max([1 floor(min(line))]);
            bb_max_l = min([sz_l ceil(max(line))]);
            
            sar_samples = repmat([bb_min_s:bb_max_s],1,length([bb_min_l:bb_max_l]));
            temp_s = length([bb_min_s:bb_max_s]);
            temp_l = length([bb_min_l:bb_max_l]);
            temp_l2 = [bb_min_l:bb_max_l];
            sar_lines = zeros(size(sar_samples));
            for cntl=1:temp_l;
                sar_lines( ((cntl-1).*temp_s+1):(cntl.*temp_s) ) = temp_l2(cntl);
            end;

%             %read the data
%             sar = sar_readpds(sar_file,sar_samples,sar_lines);
%             sar = reshape(sar,bb_max_s - bb_min_s+1,bb_max_l - bb_min_l+1);
%             inc = sar_readpds(inc_file,sar_samples,sar_lines);
%             inc = reshape(inc,bb_max_s - bb_min_s+1,bb_max_l - bb_min_l+1);

            %create the mask array             
            mask = inpoly([sar_samples; sar_lines]',[sample; line]');
            
            %step through and mask out any overlapping polygons
            if exist('ivals','var');
                inshp_ind = find( ivals == i & jvals == j );
            else;
                inshp_ind=i;
            end;
            for k=1:inshp(inshp_ind).num;
                %get the lat and lon
                lat2 = inshp(inshp_ind).lats{k};
                lon2 = inshp(inshp_ind).lons{k};
                ind2 = find( ~isnan(lon2) & ~isnan(lat2) );
                lat2 = lat2(ind2);
                lon2 = lon2(ind2);
                [line2,sample2] = bidr_proj(lat2,lon2,sar_file);
                mask = mask.*(1 - inpoly([sar_samples; sar_lines]',[sample2; line2]'));
            end;
            
            %read in the good data and calculate the statistics
            gind = find(mask);
            if ~isempty(gind);
                %read in the good data
                sar = sar_readpds(sar_file,sar_samples(gind),sar_lines(gind));               
                inc = sar_readpds(inc_file,sar_samples(gind),sar_lines(gind));                
                gind2 = find( sar > -1 & sar < 5 );                
                sar = sar(gind2);
                inc = inc(gind2);
                %input the statistics
                if isempty(gind2);
                    struct(i).avg(j) = nan;
                    struct(i).med(j) = nan;
                    struct(i).std(j) = nan;
                    struct(i).inc_avg(j) = nan;
                    struct(i).inc_med(j) = nan;
                    struct(i).inc_std(j) = nan;
                    struct(i).sar_vals{j} = nan;
                    struct(i).inc_vals{j} = nan;
                    struct(i).sar_file{j} = sar_file;
                    struct(i).inc_file{j} = inc_file;
                else;
                    struct(i).avg(j) = mean(sar);
                    struct(i).med(j) = median(sar);
                    struct(i).std(j) = std(sar);
                    struct(i).inc_avg(j) = mean(inc);
                    struct(i).inc_med(j) = median(inc);
                    struct(i).inc_std(j) = std(inc);
                    struct(i).sar_vals{j} = sar;
                    struct(i).inc_vals{j} = inc;
                    struct(i).sar_file{j} = sar_file;
                    struct(i).inc_file{j} = inc_file;
                end;                
            end;
        end;
    end;
    
    %print an update to the screen
    if (i==1 | mod(i,20)==0);
        eta_end = now;
        eta_time = (eta_end-eta_start).*24./i.*(length(shp)-i);
        eta_time = num2str(round(eta_time.*60.*100)/100);
    end;
    if mod(i,1)==0;
        fprintf(1,back_string);
        screen_suffix = [ ' ' num2str(i) ' Of  ' num2str(num)  ...
            ' ( ' num2str(round(i./num.*100*10)/10) ' Percent Complete ' ...
            'ETA: ' eta_time ' min)'];
        fprintf(1, screen_suffix);
        back_string = ['\b'];
        while length(back_string) < 2*length(screen_suffix);
            back_string = ['\b' back_string];
        end;
    end;
    
end;

%save the output
pos = strfind(shpfile,'.shp');
if isempty(pos);
    pos = strfind(shpfile,'.mat');
end;
outfile = [shpfile(1:pos(end)-1) '_analysis.mat'];
save(outfile,'struct','-v7.3');

%get finish time
totmin = (now - eta_start).*24.*60;

%%clean up screen
back_string= ['\b'];
while length(back_string) < (2*length([screen_prefix,screen_suffix]));
    back_string = ['\b' back_string];
end;
fprintf(1,back_string);
disp(['All Done! ( ' outfile ' Written) Took ' num2str(totmin) ' minutes...']);
    
    

