#!/usr/bin/perl -w

use strict;

use lib ("$ENV{GEMC}/database_io");
use geo;
use geo qw($pi);

my $DetectorName = 'CLEO_ruler';

my $envelope = "solid_$DetectorName";
my $file     = "solid_$DetectorName.txt";

my $rmin      = 1;
my $rmax      = 1000000;

my %detector = ();    # hash (map) that defines the gemc detector
$detector{"rmin"} = $rmin;
$detector{"rmax"} = $rmax;

use Getopt::Long;
use Math::Trig;

sub mysub (&@) {
     my $coderef = shift;
     map $coderef->($_), @_;
}

sub make_detector
{
my $NUM  = 15;
 my $min_Z = -200;
 my $max_Z = 700;
# my $center_Z= 0.5*($max_Z - $min_Z);
 my $center_Z= $min_Z;
my $thick100 = 20;
my $thick50 = 10;
 my $num_layer = ($max_Z - $min_Z) / 10 * 4 +1;
 my $num_thick = ($max_Z - $min_Z) / 10;
 my @Z1 = mysub { $_ * 10 +$min_Z +10. -0.5} 0 .. $num_thick;
 my @Z2 = mysub { $_ * 10 +$min_Z +0.5} 0 .. $num_thick;
 my $Rout = 400;
 my $dimension1 = "0*deg 360*deg $num_layer ";
 my @dimension2;
 for(my $n=0; $n<$num_thick; $n++)
 {
  
    my $b= $n % 5;
    my $c= $n % 10;
    if ( $n == ($num_thick -1) ) {
	push(@dimension2,$Rout-3,$Rout-1,$Rout-1,$Rout-3,$Rout-$thick100);
    }
    elsif ( $c == 0 ) {
	push(@dimension2,$Rout-$thick100,$Rout-1,$Rout-1,$Rout-3); 
    }
    elsif ( $b == 0 ) {
	push(@dimension2,$Rout-$thick50,$Rout-1,$Rout-1,$Rout-3); 
    }
    else {
	push(@dimension2,$Rout-3,$Rout-1,$Rout-1,$Rout-3); 
    }


 }

 for(my $n=0; $n<$num_thick; $n++)
 {
     if ( $n == ($num_thick -1) ) {
	 push(@dimension2,$Rout,$Rout,$Rout,$Rout,$Rout);
     }
     else {
	 push(@dimension2,$Rout,$Rout,$Rout,$Rout);
     }

 }

 for(my $n=0; $n<$num_thick; $n++)
 {
     if ( $n == ($num_thick -1) ) {
	 push(@dimension2,$Z2[$n],$Z2[$n],$Z1[$n],$Z1[$n],$Z2[$n+1]);
     }
     else {
	 push(@dimension2,$Z2[$n],$Z2[$n],$Z1[$n],$Z1[$n]);
     }

 }
my $dimension3 = join "*cm ", @dimension2; 

my $dimension = $dimension1 . $dimension3 . "*cm";

 
 my $material = "Air ";
 my $color= "000000";


 
 
    $detector{"name"}        = "$DetectorName";
    $detector{"mother"}      = "root";
    $detector{"description"} = $detector{"name"};
    $detector{"pos"}        = "0*cm 0*cm $center_Z*cm";
    $detector{"rotation"}   = "0*deg 0*deg 0*deg";
    $detector{"color"}      = $color;
    $detector{"type"}       = "Polycone";
    $detector{"dimensions"} = $dimension;
    $detector{"material"} = $material;
    $detector{"mfield"}     = "no";
    $detector{"ncopy"}	     = 1;
    $detector{"pMany"}       = 1;
    $detector{"exist"}       = 1;
    $detector{"visible"}     = 1;
    $detector{"style"}       = 1;
    $detector{"sensitivity"} = "no";
    $detector{"hit_type"}    = "";
    $detector{"identifiers"} = $detector{"name"};
    print_det(\%detector, $file);
}
make_detector();
	


